The Artima Developer Community
Sponsored Link

Java Answers Forum
Naming object references at compile or run time?

4 replies on 1 page. Most recent reply: Jun 18, 2002 5:11 PM by Charles Bell

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 4 replies on 1 page
Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

Naming object references at compile or run time? Posted: Jun 18, 2002 12:49 PM
Reply to this message Reply
Advertisement
Maybe I am missing something here, but if I have an employee database or a space invader game for that matter, how do you create a vector of new 'alien' objects when you apparently need to know the name of each instantiation's reference at compile time. I dont understand yet of how to just create these object references on the fly. I am sure that I wont need to declare 5000 empty references like A0001,A0002,A0003 etc, 'just in case I need that many'. I appreciate any info, just trying to bridge the gap in understanding and havent reached that in the text yet.

thanks


Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: Naming object references at compile or run time? Posted: Jun 18, 2002 12:57 PM
Reply to this message Reply
Vector aliens = new Vector();
aliens.add(new Alien("v1"));
aliens.add(new Alien("alpha two"));
aliens.add(new Alien("r2d2"));
aliens.add(new Alien("victor"));
aliens.add(new Alien("spongeBob"));

class Alien{
private String name = "";
public Alien(String name){
this.name = name;
}

public String getName(){
return name;
}
}

Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

Re: Naming object references at compile or run time? Posted: Jun 18, 2002 1:07 PM
Reply to this message Reply
I understand that much, but if I want to go in and add 10 more aliens, I would have to go in and add them to the code and recompile in order to get this to work? there is no way to generate these object references 'on the fly' as I suggested? say I have a an employee database of 100 employees, I have no turn over and I need to hire 10 more people. I have only 100 references in the program, I want to add more references, do I always have to do this manually by adding more reference code?

I hope I am saying the right things here, I dont want to waste your time. I am basically looking for an answer to whether I can create a vector of no-name referenced objects so I can keep adding when ever I like... there, I think that finally said what i was getting at! :)

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: Naming object references at compile or run time? Posted: Jun 18, 2002 5:11 PM
Reply to this message Reply
The following is an example of a program that manages employee objects. The program allows the user to add, delete, and view employee objects which can be created, and deleted dynamically at run time, and saved for next time the program is started.
I used properties files as a convenient way to store the data for an employee in a file for easy retrieval.

Try it out, its fully functional.

I went ahead and wrote this because this type example program is requested so often by students who get asked to write programs for java classes.

I am a full time instructor at a large power plant in the U.S. I always learned by seeing what someone else wrote. I had to learn java all by myself, though.

I hope this helps. If there are any questions about it, let me know. (email: charbell@bellsouth.net)

You could change the text Employee in this with the text Alien and it would become an AlienManager is just seconds!!!



/* EmployeeManager.java
* @author: Charles Bell
* @version: June 18, 2002
*/
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class EmployeeManager{


public EmployeeManager(){
init();
}

public static void main(String[] args){
new EmployeeManager();
}

public void init(){
String action = "";
while ((action = getActionSelection(action)). compareTo("Exit") != 0){
if (action. compareTo("Add New Employee") == 0){
addNewEmployee();
}else if (action. compareTo("Delete Employee") == 0){
deleteEmployee();
}else if (action. compareTo("View Employees") == 0){
viewEmployees();
}
}
System.exit(0);
}

public void addNewEmployee(){
EmployeeEditor editor = new EmployeeEditor();
}

public void deleteEmployee(){
EmployeeSelector selector = new EmployeeSelector();
Employee employee = selector.select();
File file = new File(employee.getEmployeeNumber() + ".properties");
if (file.delete()){
String statusMessage = employee.getName() + " was deleted.";
JOptionPane.showMessageDialog(null,statusMessage,statusMessage,JOptionPane.INFO RMATION_MESSAGE);
}
}

public void viewEmployees(){
EmployeeViewer viewer = new EmployeeViewer();
viewer.view();
}



/** Pops up a user interface of JRadio buttons to select an action
* from a pallette of allowable Action Names.
*/
public String getActionSelection(String current){
String choice = current;
String message = "Select Action:";
String[] options = {"Add New Employee", "Delete Employee",
"View Employees", "Exit"};
JFrame f = new JFrame();
JPanel buttonPanel = new JPanel();
if (options.length/2 == 0){
buttonPanel.setLayout(new GridLayout(options.length/2,2));
}else{
buttonPanel.setLayout(new GridLayout(options.length/2+1,2));
}
ButtonGroup buttongroup = new ButtonGroup();
JRadioButton[] buttons = new JRadioButton[options.length];
for (int i = 0;i<options.length;i++){
buttons[i] = new JRadioButton(options[i],(current.compareTo(options[i]) == 0));
buttonPanel.add(buttons[i]);
buttongroup.add(buttons[i]);
}
JScrollPane scrollpane = new JScrollPane(buttonPanel);
scrollpane.setFont(new Font("SansSerif",Font.PLAIN,8));
JOptionPane editpane = new JOptionPane(scrollpane,JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
editpane.setFont(new Font("SansSerif",Font.PLAIN,8));
JDialog dialog = editpane.createDialog(f,message);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
f.pack();
f.setLocationRelativeTo(null);
dialog.show();
for (int i = 0;i<options.length;i++){
if (buttons[i].isSelected()) {
choice = buttons[i].getText();
}
}
dialog.dispose();
f.dispose();
return choice;
}

public Vector getAllEmployees(){
Vector v = new Vector();
File currentDirectory = new File(".");
String[] employeeFiles = currentDirectory.list(new EmployeeFileFilter());
EmployeeReader reader = new EmployeeReader();
for (int i = 0; i < employeeFiles.length; i++){
Employee nextEmployee = reader.getEmployee(employeeFiles[i]);
v.add(nextEmployee);
}
return v;
}

class Employee{

private String name = "";
private String employeeNumber = "";
private String hireDate = "";

public Employee(String name, String employeeNumber, String hireDate){
this.name = name;
this.employeeNumber = employeeNumber;
this.hireDate = hireDate;
}

public String getName(){
return name;
}

public String getEmployeeNumber(){
return employeeNumber;
}

public String getHireDate(){
return hireDate;
}

public void setName(String name){
this.name = name;
}

public void setEmployeeNumber(String getEmployeeNumber){
this.employeeNumber = getEmployeeNumber;
}

public void setHireDate(String hireDate){
this.hireDate = hireDate;
}

public String toString(){
return "Name= " + name + "\n"
+ "EmployeeNumber= " + employeeNumber + "\n"
+ "HireDate= " + hireDate + "\n";
}

public String toDisplayString(){
return "Name: " + name + "\t"
+ "Employee Number: " + employeeNumber + "\t"
+ "Hire Date: " + hireDate + "\n";
}
}

class EmployeeReader{

public EmployeeReader(){

}

public Employee getEmployee(String fileName){
Properties properties = new Properties();
Employee employee = null;
try{
File propertiesFile = new File(fileName);
properties.load(new FileInputStream(propertiesFile));
String name = properties.getProperty("Name");
String employeeNumber = properties.getProperty("EmployeeNumber");
String hireDate = properties.getProperty("HireDate");
if ((name.length() > 0)
&& (employeeNumber.length() > 0)
&& (hireDate.length() > 0)) {
employee = new Employee(name, employeeNumber, hireDate);
}
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
return employee;
}
}

class EmployeeWriter{

public EmployeeWriter(){

}

public void write(Employee employee){
try{
FileWriter fw = new FileWriter(employee.getEmployeeNumber() + ".properties");
fw.write(employee.toString());
fw.close();
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
}
}

class EmployeeFileFilter implements FilenameFilter{

public boolean accept(File dir, String name){
return (name.toLowerCase().indexOf(".properties") > 0);
}

}

class EmployeeSelector{

public Employee select(){
Employee selectedEmployee = null;
Vector employees = getAllEmployees();
JFrame f = new JFrame();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(employees.size(),1));
ButtonGroup buttongroup = new ButtonGroup();
JRadioButton[] buttons = new JRadioButton[employees.size()];
for (int i = 0;i<employees.size();i++){
Employee nextEmployee = (Employee)employees.elementAt(i);
buttons[i] = new JRadioButton(nextEmployee.toDisplayString());
buttonPanel.add(buttons[i]);
buttongroup.add(buttons[i]);
}

JScrollPane scrollpane = new JScrollPane(buttonPanel);
scrollpane.setFont(new Font("SansSerif",Font.PLAIN,8));
JOptionPane optionPane = new JOptionPane(scrollpane,JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
optionPane.setFont(new Font("SansSerif",Font.PLAIN,8));
JDialog dialog = optionPane.createDialog(f,"Select Employee");
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
f.pack();
f.setLocationRelativeTo(null);
dialog.show();
for (int i = 0; i < buttons.length; i++){
if (buttons[i].isSelected()) {
selectedEmployee = (Employee) employees.elementAt(i);
}
}
dialog.dispose();
f.dispose();
return selectedEmployee;
}
}

class EmployeeViewer{

public void view(){

Vector employees = getAllEmployees();
JTextArea display = new JTextArea(30,60);
display.setEditable(false);
ListIterator iterator = employees.listIterator();
while (iterator.hasNext()){
Employee nextEmployee = (Employee)iterator.next();
display.append(nextEmployee.toDisplayString() + "\n");
}
JScrollPane scrollPane = new JScrollPane(display);
JFrame f = new JFrame();
JOptionPane editpane = new JOptionPane(scrollPane,JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = editpane.createDialog(f,"Employees");
f.pack();
f.setLocationRelativeTo(null);
dialog.show();
}
}


class EmployeeEditor {

JTextField nameField = new JTextField(20);
JTextField numberField = new JTextField(20);
JTextField hireDateField = new JTextField(20);

public EmployeeEditor(){
init();
}

public void init(){

JLabel nameLabel = new JLabel("Name:");
JLabel numberLabel = new JLabel("Employee Number:");
JLabel hireDateLabel = new JLabel("Hire Date:");
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JPanel namePanel = new JPanel();
JPanel numberPanel = new JPanel();
JPanel hireDatePanel = new JPanel();
namePanel.add(nameLabel);
namePanel.add(nameField);
numberPanel.add(numberLabel);
numberPanel.add(numberField);
hireDatePanel.add(hireDateLabel);
hireDatePanel.add(hireDateField);
panel.add(namePanel,BorderLayout.NORTH);
panel.add(numberPanel, BorderLayout.CENTER);
panel.add(hireDatePanel, BorderLayout.SOUTH);
JFrame frame = new JFrame();
JOptionPane editpane = new JOptionPane(panel,JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = editpane.createDialog(frame,"EmployeeEditor");
frame.pack();
frame.setLocationRelativeTo(null);
dialog.show();
String name = nameField.getText();
String employeeNumber = numberField.getText();
String hireDate = hireDateField.getText();
if ((name.length() > 0)
&& (employeeNumber.length() > 0)
&& (hireDate.length() > 0)) {
Employee employee = new Employee(name, employeeNumber, hireDate);
EmployeeWriter writer = new EmployeeWriter();
writer.write(employee);
}
}
}
}

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: Naming object references at compile or run time? Posted: Jun 18, 2002 5:11 PM
Reply to this message Reply
The following is an example of a program that manages employee objects. The program allows the user to add, delete, and view employee objects which can be created, and deleted dynamically at run time, and saved for next time the program is started.
I used properties files as a convenient way to store the data for an employee in a file for easy retrieval.

Try it out, its fully functional.

I went ahead and wrote this because this type example program is requested so often by students who get asked to write programs for java classes.

I am a full time instructor at a large power plant in the U.S. I always learned by seeing what someone else wrote. I had to learn java all by myself, though.

I hope this helps. If there are any questions about it, let me know. (email: charbell@bellsouth.net)

You could change the text Employee in this with the text Alien and it would become an AlienManager is just seconds!!!



/* EmployeeManager.java
* @author: Charles Bell
* @version: June 18, 2002
*/
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class EmployeeManager{


public EmployeeManager(){
init();
}

public static void main(String[] args){
new EmployeeManager();
}

public void init(){
String action = "";
while ((action = getActionSelection(action)). compareTo("Exit") != 0){
if (action. compareTo("Add New Employee") == 0){
addNewEmployee();
}else if (action. compareTo("Delete Employee") == 0){
deleteEmployee();
}else if (action. compareTo("View Employees") == 0){
viewEmployees();
}
}
System.exit(0);
}

public void addNewEmployee(){
EmployeeEditor editor = new EmployeeEditor();
}

public void deleteEmployee(){
EmployeeSelector selector = new EmployeeSelector();
Employee employee = selector.select();
File file = new File(employee.getEmployeeNumber() + ".properties");
if (file.delete()){
String statusMessage = employee.getName() + " was deleted.";
JOptionPane.showMessageDialog(null,statusMessage,statusMessage,JOptionPane.INFO RMATION_MESSAGE);
}
}

public void viewEmployees(){
EmployeeViewer viewer = new EmployeeViewer();
viewer.view();
}



/** Pops up a user interface of JRadio buttons to select an action
* from a pallette of allowable Action Names.
*/
public String getActionSelection(String current){
String choice = current;
String message = "Select Action:";
String[] options = {"Add New Employee", "Delete Employee",
"View Employees", "Exit"};
JFrame f = new JFrame();
JPanel buttonPanel = new JPanel();
if (options.length/2 == 0){
buttonPanel.setLayout(new GridLayout(options.length/2,2));
}else{
buttonPanel.setLayout(new GridLayout(options.length/2+1,2));
}
ButtonGroup buttongroup = new ButtonGroup();
JRadioButton[] buttons = new JRadioButton[options.length];
for (int i = 0;i<options.length;i++){
buttons[i] = new JRadioButton(options[i],(current.compareTo(options[i]) == 0));
buttonPanel.add(buttons[i]);
buttongroup.add(buttons[i]);
}
JScrollPane scrollpane = new JScrollPane(buttonPanel);
scrollpane.setFont(new Font("SansSerif",Font.PLAIN,8));
JOptionPane editpane = new JOptionPane(scrollpane,JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
editpane.setFont(new Font("SansSerif",Font.PLAIN,8));
JDialog dialog = editpane.createDialog(f,message);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
f.pack();
f.setLocationRelativeTo(null);
dialog.show();
for (int i = 0;i<options.length;i++){
if (buttons[i].isSelected()) {
choice = buttons[i].getText();
}
}
dialog.dispose();
f.dispose();
return choice;
}

public Vector getAllEmployees(){
Vector v = new Vector();
File currentDirectory = new File(".");
String[] employeeFiles = currentDirectory.list(new EmployeeFileFilter());
EmployeeReader reader = new EmployeeReader();
for (int i = 0; i < employeeFiles.length; i++){
Employee nextEmployee = reader.getEmployee(employeeFiles[i]);
v.add(nextEmployee);
}
return v;
}

class Employee{

private String name = "";
private String employeeNumber = "";
private String hireDate = "";

public Employee(String name, String employeeNumber, String hireDate){
this.name = name;
this.employeeNumber = employeeNumber;
this.hireDate = hireDate;
}

public String getName(){
return name;
}

public String getEmployeeNumber(){
return employeeNumber;
}

public String getHireDate(){
return hireDate;
}

public void setName(String name){
this.name = name;
}

public void setEmployeeNumber(String getEmployeeNumber){
this.employeeNumber = getEmployeeNumber;
}

public void setHireDate(String hireDate){
this.hireDate = hireDate;
}

public String toString(){
return "Name= " + name + "\n"
+ "EmployeeNumber= " + employeeNumber + "\n"
+ "HireDate= " + hireDate + "\n";
}

public String toDisplayString(){
return "Name: " + name + "\t"
+ "Employee Number: " + employeeNumber + "\t"
+ "Hire Date: " + hireDate + "\n";
}
}

class EmployeeReader{

public EmployeeReader(){

}

public Employee getEmployee(String fileName){
Properties properties = new Properties();
Employee employee = null;
try{
File propertiesFile = new File(fileName);
properties.load(new FileInputStream(propertiesFile));
String name = properties.getProperty("Name");
String employeeNumber = properties.getProperty("EmployeeNumber");
String hireDate = properties.getProperty("HireDate");
if ((name.length() > 0)
&& (employeeNumber.length() > 0)
&& (hireDate.length() > 0)) {
employee = new Employee(name, employeeNumber, hireDate);
}
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
return employee;
}
}

class EmployeeWriter{

public EmployeeWriter(){

}

public void write(Employee employee){
try{
FileWriter fw = new FileWriter(employee.getEmployeeNumber() + ".properties");
fw.write(employee.toString());
fw.close();
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
}
}

class EmployeeFileFilter implements FilenameFilter{

public boolean accept(File dir, String name){
return (name.toLowerCase().indexOf(".properties") > 0);
}

}

class EmployeeSelector{

public Employee select(){
Employee selectedEmployee = null;
Vector employees = getAllEmployees();
JFrame f = new JFrame();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(employees.size(),1));
ButtonGroup buttongroup = new ButtonGroup();
JRadioButton[] buttons = new JRadioButton[employees.size()];
for (int i = 0;i<employees.size();i++){
Employee nextEmployee = (Employee)employees.elementAt(i);
buttons[i] = new JRadioButton(nextEmployee.toDisplayString());
buttonPanel.add(buttons[i]);
buttongroup.add(buttons[i]);
}

JScrollPane scrollpane = new JScrollPane(buttonPanel);
scrollpane.setFont(new Font("SansSerif",Font.PLAIN,8));
JOptionPane optionPane = new JOptionPane(scrollpane,JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
optionPane.setFont(new Font("SansSerif",Font.PLAIN,8));
JDialog dialog = optionPane.createDialog(f,"Select Employee");
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
f.pack();
f.setLocationRelativeTo(null);
dialog.show();
for (int i = 0; i < buttons.length; i++){
if (buttons[i].isSelected()) {
selectedEmployee = (Employee) employees.elementAt(i);
}
}
dialog.dispose();
f.dispose();
return selectedEmployee;
}
}

class EmployeeViewer{

public void view(){

Vector employees = getAllEmployees();
JTextArea display = new JTextArea(30,60);
display.setEditable(false);
ListIterator iterator = employees.listIterator();
while (iterator.hasNext()){
Employee nextEmployee = (Employee)iterator.next();
display.append(nextEmployee.toDisplayString() + "\n");
}
JScrollPane scrollPane = new JScrollPane(display);
JFrame f = new JFrame();
JOptionPane editpane = new JOptionPane(scrollPane,JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = editpane.createDialog(f,"Employees");
f.pack();
f.setLocationRelativeTo(null);
dialog.show();
}
}


class EmployeeEditor {

JTextField nameField = new JTextField(20);
JTextField numberField = new JTextField(20);
JTextField hireDateField = new JTextField(20);

public EmployeeEditor(){
init();
}

public void init(){

JLabel nameLabel = new JLabel("Name:");
JLabel numberLabel = new JLabel("Employee Number:");
JLabel hireDateLabel = new JLabel("Hire Date:");
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JPanel namePanel = new JPanel();
JPanel numberPanel = new JPanel();
JPanel hireDatePanel = new JPanel();
namePanel.add(nameLabel);
namePanel.add(nameField);
numberPanel.add(numberLabel);
numberPanel.add(numberField);
hireDatePanel.add(hireDateLabel);
hireDatePanel.add(hireDateField);
panel.add(namePanel,BorderLayout.NORTH);
panel.add(numberPanel, BorderLayout.CENTER);
panel.add(hireDatePanel, BorderLayout.SOUTH);
JFrame frame = new JFrame();
JOptionPane editpane = new JOptionPane(panel,JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = editpane.createDialog(frame,"EmployeeEditor");
frame.pack();
frame.setLocationRelativeTo(null);
dialog.show();
String name = nameField.getText();
String employeeNumber = numberField.getText();
String hireDate = hireDateField.getText();
if ((name.length() > 0)
&& (employeeNumber.length() > 0)
&& (hireDate.length() > 0)) {
Employee employee = new Employee(name, employeeNumber, hireDate);
EmployeeWriter writer = new EmployeeWriter();
writer.write(employee);
}
}
}
}

Flat View: This topic has 4 replies on 1 page
Topic: reading binary files Previous Topic   Next Topic Topic: Help! How to change panel's image?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use