JList not updating when adding element to DefaultListModel - java

I'm trying to create a simple program to manage Employees. When trying to add a new employee I can't seem to get the employee to be displayed on the Jlist.
The main frame...
public class EmployeeFrame extends JFrame implements ActionListener {
// The buttons to display
private JButton addButton;
private JButton editButton;
private JButton deleteButton;
private JButton saveButton;
// The underlying list of employees, and the GUI object to display them
private DefaultListModel<Employee> listModel;
private JList<Employee> employeeList;
public static final String SAVE_FILE = "employees.txt";
/**
* Creates and displays a new EmployeeFrame. The program exits when the
* window is closed.
*/
public EmployeeFrame() {
// Basic window features
super("Employee Manager");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Try to make it look like a native application -- using try/multi-catch
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
// Initialise an empty list model, a JList to display it, and a scroll
// pane to contain the list
listModel = new DefaultListModel<>();
employeeList = new JList<>(listModel);
JScrollPane employeeScroll = new JScrollPane(employeeList);
employeeScroll.setBorder(new TitledBorder("Employee List"));
// Initialise all buttons and add the current class as an action
// listener to all
addButton = new JButton("Add Employee");
addButton.addActionListener(this);
editButton = new JButton("Edit Employee");
editButton.addActionListener(this);
deleteButton = new JButton("Delete Employee");
deleteButton.addActionListener(this);
saveButton = new JButton("Save Employee List");
saveButton.addActionListener(this);
// Lay out the buttons in a line
Box topBox = Box.createHorizontalBox();
topBox.add(addButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(editButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(deleteButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(saveButton);
// Lay out the window
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topBox, BorderLayout.NORTH);
getContentPane().add(employeeScroll, BorderLayout.CENTER);
pack();
}
public DefaultListModel<Employee> getListModel() {
return this.listModel;
}
#Override
public void actionPerformed(ActionEvent event) {
// Determine which button was pushed
Object source = event.getSource();
// Here's what to do with the delete button
if (source == deleteButton) {
Employee selection = employeeList.getSelectedValue();
if (selection != null) {
listModel.removeElement(selection);
}
}
if (source == addButton) {
AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
frame.setVisible(true);
}
}
public static void main(String[] args) {
new EmployeeFrame().setVisible(true);
}
}
The dialogue that adds the employee...
public class AddEmployeeDialog extends JDialog implements ActionListener {
// Common fields
private JComboBox<String> workerType;
private JTextField givenNameField;
private JTextField familyNameField;
private JDatePicker startDatePicker;
// Fields that depend on the employee type
private JTextField rateField;
private JTextField hoursField;
private JTextField salaryField;
// Buttons
private JButton okButton;
private JButton cancelButton;
// The employee frame -- used to position the dialog and to access the
// employee list
private EmployeeFrame employeeFrame;
public AddEmployeeDialog(final EmployeeFrame frame) {
// Basic initialisation
super(frame, "Add Employee", true);
setLocationRelativeTo(employeeFrame);
this.employeeFrame = frame;
// Common fields
workerType = new JComboBox<String>(Employee.getEmployeeTypes());
givenNameField = new JTextField(20);
familyNameField = new JTextField(20);
startDatePicker = new JDateComponentFactory().createJDatePicker();
// Fields only for hourly workers
rateField = new JTextField(10);
hoursField = new JTextField(5);
// Field only for salaried worker
salaryField = new JTextField(10);
// Top line
Box workerBox = Box.createHorizontalBox();
workerBox.add(new JLabel("Worker type"));
workerBox.add(workerType);
workerBox.add(new JLabel("Start date"));
workerBox.add((JPanel) startDatePicker);
// Next lines (names)
Box givenNameBox = Box.createHorizontalBox();
givenNameBox.add(new JLabel("Given name "));
givenNameBox.add(givenNameField);
Box familyNameBox = Box.createHorizontalBox();
familyNameBox.add(new JLabel("Family name"));
familyNameBox.add(familyNameField);
// Hourly-worker fields
Box hourlyBox = Box.createHorizontalBox();
hourlyBox.setBorder(new TitledBorder("Hourly worker information"));
hourlyBox.add(new JLabel("Rate"));
hourlyBox.add(rateField);
hourlyBox.add(Box.createHorizontalStrut(10));
hourlyBox.add(new JLabel("Hours"));
hourlyBox.add(hoursField);
// Salaried-worker fields
Box salariedBox = Box.createHorizontalBox();
salariedBox.setBorder(new TitledBorder("Salaried worker information"));
salariedBox.add(new JLabel("Salary"));
salariedBox.add(salaryField);
// Ensure that only the appropriate fields are enabled, depending on the
// worker type chosen
workerType.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent arg0) {
String type = (String) workerType.getSelectedItem();
salaryField.setEnabled("Salaried".equals(type));
rateField.setEnabled("Hourly".equals(type));
hoursField.setEnabled("Hourly".equals(type));
}
});
workerType.setSelectedItem(null);
// Create buttons and add the current class as an ActionListener
okButton = new JButton("OK");
okButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
// Bottom row of GUI: buttons
Box bottomBox = Box.createHorizontalBox();
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(okButton);
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(cancelButton);
bottomBox.add(Box.createHorizontalGlue());
// Lay out the GUI
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(workerBox);
getContentPane().add(givenNameBox);
getContentPane().add(familyNameBox);
getContentPane().add(hourlyBox);
getContentPane().add(salariedBox);
getContentPane().add(Box.createVerticalStrut(10));
getContentPane().add(bottomBox);
pack();
}
#Override
public void actionPerformed(ActionEvent event) {
// Convert the value from the date picker into a LocalDate
GregorianCalendar startDateValue = (GregorianCalendar) startDatePicker.getModel().getValue();
LocalDate startDate = startDateValue.toZonedDateTime().toLocalDate();
// Work out which button was pressed
Object source = event.getSource();
if (source == cancelButton) {
// Just close the window
dispose();
}
if (source == okButton) {
// Determine if the employee is hourly or salaried
if (workerType.getSelectedItem().toString() == "Salaried") {
// Create new salaried employee
if (salaryField.getText().matches("[0-9]+")) {
Employee employee = new SalariedEmployee(givenNameField.getText(),
familyNameField.getText(),
startDate,
Double.parseDouble(salaryField.getText()));
employeeFrame.getListModel().addElement(employee);
}
}
else {
// Create new hourly employee
if (rateField.getText().matches("[0-9]+") && hoursField.getText().matches("[0-9]+")) {
Employee employee = new HourlyEmployee(givenNameField.getText(),
familyNameField.getText(),
startDate,
Double.parseDouble(rateField.getText()),
Integer.parseInt(hoursField.getText()));
employeeFrame.getListModel().addElement(employee);
}
}
dispose();
}
}
}
This is what I'm using to add the employee
employeeFrame.getListModel().addElement(employee);
I think this is the right method but it doesn't seem to work. Any help will really be appreciated.

Two problems,
The first:
bad: if (workerType.getSelectedItem().toString() == "Salaried") {. Use equals(...) or equalsIgnoreCase(...). Understand that == checks for reference equality which is most definitely not what you're interested in. You want functional equality which is what the methods test for.
So: if ("Salaried".equalsIgnoreCase(workerType.getSelectedItem().toString())) {
The second:
AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
You're passing in a new EmployeeFrame object meaning you're updating the list model for the wrong EmployeeFrame. Instead pass in the visualized EmployeeFrame.
Change it to:
AddEmployeeDialog frame = new AddEmployeeDialog(EmployeeFrame.this);
My program that I created to shrink your code but still allow it to be runnable and to demonstrate your problem:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class EmployeeFrame extends JFrame implements ActionListener {
private JButton addButton;
private DefaultListModel<Employee> listModel;
private JList<Employee> employeeList;
public EmployeeFrame() {
super("Employee Manager");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
listModel = new DefaultListModel<>();
employeeList = new JList<>(listModel);
JScrollPane employeeScroll = new JScrollPane(employeeList);
employeeScroll.setBorder(new TitledBorder("Employee List"));
addButton = new JButton("Add Employee");
addButton.addActionListener(this);
Box topBox = Box.createHorizontalBox();
topBox.add(addButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topBox, BorderLayout.NORTH);
getContentPane().add(employeeScroll, BorderLayout.CENTER);
pack();
}
public DefaultListModel<Employee> getListModel() {
return this.listModel;
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == addButton) {
// !! AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
AddEmployeeDialog frame = new AddEmployeeDialog(EmployeeFrame.this);
frame.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EmployeeFrame().setVisible(true);
}
});
}
}
#SuppressWarnings("serial")
class AddEmployeeDialog extends JDialog implements ActionListener {
private JComboBox<String> workerType;
private JTextField givenNameField;
private JTextField familyNameField;
private JButton okButton;
private JButton cancelButton;
private EmployeeFrame employeeFrame;
public AddEmployeeDialog(final EmployeeFrame frame) {
super(frame, "Add Employee", true);
setLocationRelativeTo(employeeFrame);
this.employeeFrame = frame;
workerType = new JComboBox<String>(Employee.getEmployeeTypes());
givenNameField = new JTextField(20);
familyNameField = new JTextField(20);
Box workerBox = Box.createHorizontalBox();
workerBox.add(new JLabel("Worker type"));
workerBox.add(workerType);
workerBox.add(new JLabel("Start date"));
Box givenNameBox = Box.createHorizontalBox();
givenNameBox.add(new JLabel("Given name "));
givenNameBox.add(givenNameField);
Box familyNameBox = Box.createHorizontalBox();
familyNameBox.add(new JLabel("Family name"));
familyNameBox.add(familyNameField);
workerType.setSelectedItem(null);
// Create buttons and add the current class as an ActionListener
okButton = new JButton("OK");
okButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
Box bottomBox = Box.createHorizontalBox();
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(okButton);
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(cancelButton);
bottomBox.add(Box.createHorizontalGlue());
// Lay out the GUI
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(workerBox);
getContentPane().add(givenNameBox);
getContentPane().add(familyNameBox);
getContentPane().add(Box.createVerticalStrut(10));
getContentPane().add(bottomBox);
pack();
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == okButton) {
System.out.println("here");
System.out.println(workerType.getSelectedItem());
if ("Salaried".equalsIgnoreCase(workerType.getSelectedItem().toString())) {
Employee employee = new Employee("Salaried", givenNameField.getText(), familyNameField.getText());
employeeFrame.getListModel().addElement(employee);
} else {
Employee employee = new Employee("Hourly", givenNameField.getText(), familyNameField.getText());
employeeFrame.getListModel().addElement(employee);
}
}
dispose();
}
}
class Employee {
private static final String[] EMPLOYEE_TYPES = { "Salaried", "Hourly" };
private String givenName;
private String familyName;
private String type;
public Employee(String type, String givenName, String familyName) {
this.type = type;
this.givenName = givenName;
this.familyName = familyName;
}
public static String[] getEmployeeTypes() {
return EMPLOYEE_TYPES;
}
public String getGivenName() {
return givenName;
}
public String getFamilyName() {
return familyName;
}
public String getType() {
return type;
}
#Override
public String toString() {
return String.format("Employee: %s, %s %s", type, givenName, familyName);
}
}

Related

DefaultListModel and jList1.setModel not working [duplicate]

I'm trying to create a simple program to manage Employees. When trying to add a new employee I can't seem to get the employee to be displayed on the Jlist.
The main frame...
public class EmployeeFrame extends JFrame implements ActionListener {
// The buttons to display
private JButton addButton;
private JButton editButton;
private JButton deleteButton;
private JButton saveButton;
// The underlying list of employees, and the GUI object to display them
private DefaultListModel<Employee> listModel;
private JList<Employee> employeeList;
public static final String SAVE_FILE = "employees.txt";
/**
* Creates and displays a new EmployeeFrame. The program exits when the
* window is closed.
*/
public EmployeeFrame() {
// Basic window features
super("Employee Manager");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Try to make it look like a native application -- using try/multi-catch
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
// Initialise an empty list model, a JList to display it, and a scroll
// pane to contain the list
listModel = new DefaultListModel<>();
employeeList = new JList<>(listModel);
JScrollPane employeeScroll = new JScrollPane(employeeList);
employeeScroll.setBorder(new TitledBorder("Employee List"));
// Initialise all buttons and add the current class as an action
// listener to all
addButton = new JButton("Add Employee");
addButton.addActionListener(this);
editButton = new JButton("Edit Employee");
editButton.addActionListener(this);
deleteButton = new JButton("Delete Employee");
deleteButton.addActionListener(this);
saveButton = new JButton("Save Employee List");
saveButton.addActionListener(this);
// Lay out the buttons in a line
Box topBox = Box.createHorizontalBox();
topBox.add(addButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(editButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(deleteButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(saveButton);
// Lay out the window
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topBox, BorderLayout.NORTH);
getContentPane().add(employeeScroll, BorderLayout.CENTER);
pack();
}
public DefaultListModel<Employee> getListModel() {
return this.listModel;
}
#Override
public void actionPerformed(ActionEvent event) {
// Determine which button was pushed
Object source = event.getSource();
// Here's what to do with the delete button
if (source == deleteButton) {
Employee selection = employeeList.getSelectedValue();
if (selection != null) {
listModel.removeElement(selection);
}
}
if (source == addButton) {
AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
frame.setVisible(true);
}
}
public static void main(String[] args) {
new EmployeeFrame().setVisible(true);
}
}
The dialogue that adds the employee...
public class AddEmployeeDialog extends JDialog implements ActionListener {
// Common fields
private JComboBox<String> workerType;
private JTextField givenNameField;
private JTextField familyNameField;
private JDatePicker startDatePicker;
// Fields that depend on the employee type
private JTextField rateField;
private JTextField hoursField;
private JTextField salaryField;
// Buttons
private JButton okButton;
private JButton cancelButton;
// The employee frame -- used to position the dialog and to access the
// employee list
private EmployeeFrame employeeFrame;
public AddEmployeeDialog(final EmployeeFrame frame) {
// Basic initialisation
super(frame, "Add Employee", true);
setLocationRelativeTo(employeeFrame);
this.employeeFrame = frame;
// Common fields
workerType = new JComboBox<String>(Employee.getEmployeeTypes());
givenNameField = new JTextField(20);
familyNameField = new JTextField(20);
startDatePicker = new JDateComponentFactory().createJDatePicker();
// Fields only for hourly workers
rateField = new JTextField(10);
hoursField = new JTextField(5);
// Field only for salaried worker
salaryField = new JTextField(10);
// Top line
Box workerBox = Box.createHorizontalBox();
workerBox.add(new JLabel("Worker type"));
workerBox.add(workerType);
workerBox.add(new JLabel("Start date"));
workerBox.add((JPanel) startDatePicker);
// Next lines (names)
Box givenNameBox = Box.createHorizontalBox();
givenNameBox.add(new JLabel("Given name "));
givenNameBox.add(givenNameField);
Box familyNameBox = Box.createHorizontalBox();
familyNameBox.add(new JLabel("Family name"));
familyNameBox.add(familyNameField);
// Hourly-worker fields
Box hourlyBox = Box.createHorizontalBox();
hourlyBox.setBorder(new TitledBorder("Hourly worker information"));
hourlyBox.add(new JLabel("Rate"));
hourlyBox.add(rateField);
hourlyBox.add(Box.createHorizontalStrut(10));
hourlyBox.add(new JLabel("Hours"));
hourlyBox.add(hoursField);
// Salaried-worker fields
Box salariedBox = Box.createHorizontalBox();
salariedBox.setBorder(new TitledBorder("Salaried worker information"));
salariedBox.add(new JLabel("Salary"));
salariedBox.add(salaryField);
// Ensure that only the appropriate fields are enabled, depending on the
// worker type chosen
workerType.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent arg0) {
String type = (String) workerType.getSelectedItem();
salaryField.setEnabled("Salaried".equals(type));
rateField.setEnabled("Hourly".equals(type));
hoursField.setEnabled("Hourly".equals(type));
}
});
workerType.setSelectedItem(null);
// Create buttons and add the current class as an ActionListener
okButton = new JButton("OK");
okButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
// Bottom row of GUI: buttons
Box bottomBox = Box.createHorizontalBox();
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(okButton);
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(cancelButton);
bottomBox.add(Box.createHorizontalGlue());
// Lay out the GUI
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(workerBox);
getContentPane().add(givenNameBox);
getContentPane().add(familyNameBox);
getContentPane().add(hourlyBox);
getContentPane().add(salariedBox);
getContentPane().add(Box.createVerticalStrut(10));
getContentPane().add(bottomBox);
pack();
}
#Override
public void actionPerformed(ActionEvent event) {
// Convert the value from the date picker into a LocalDate
GregorianCalendar startDateValue = (GregorianCalendar) startDatePicker.getModel().getValue();
LocalDate startDate = startDateValue.toZonedDateTime().toLocalDate();
// Work out which button was pressed
Object source = event.getSource();
if (source == cancelButton) {
// Just close the window
dispose();
}
if (source == okButton) {
// Determine if the employee is hourly or salaried
if (workerType.getSelectedItem().toString() == "Salaried") {
// Create new salaried employee
if (salaryField.getText().matches("[0-9]+")) {
Employee employee = new SalariedEmployee(givenNameField.getText(),
familyNameField.getText(),
startDate,
Double.parseDouble(salaryField.getText()));
employeeFrame.getListModel().addElement(employee);
}
}
else {
// Create new hourly employee
if (rateField.getText().matches("[0-9]+") && hoursField.getText().matches("[0-9]+")) {
Employee employee = new HourlyEmployee(givenNameField.getText(),
familyNameField.getText(),
startDate,
Double.parseDouble(rateField.getText()),
Integer.parseInt(hoursField.getText()));
employeeFrame.getListModel().addElement(employee);
}
}
dispose();
}
}
}
This is what I'm using to add the employee
employeeFrame.getListModel().addElement(employee);
I think this is the right method but it doesn't seem to work. Any help will really be appreciated.
Two problems,
The first:
bad: if (workerType.getSelectedItem().toString() == "Salaried") {. Use equals(...) or equalsIgnoreCase(...). Understand that == checks for reference equality which is most definitely not what you're interested in. You want functional equality which is what the methods test for.
So: if ("Salaried".equalsIgnoreCase(workerType.getSelectedItem().toString())) {
The second:
AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
You're passing in a new EmployeeFrame object meaning you're updating the list model for the wrong EmployeeFrame. Instead pass in the visualized EmployeeFrame.
Change it to:
AddEmployeeDialog frame = new AddEmployeeDialog(EmployeeFrame.this);
My program that I created to shrink your code but still allow it to be runnable and to demonstrate your problem:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class EmployeeFrame extends JFrame implements ActionListener {
private JButton addButton;
private DefaultListModel<Employee> listModel;
private JList<Employee> employeeList;
public EmployeeFrame() {
super("Employee Manager");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
listModel = new DefaultListModel<>();
employeeList = new JList<>(listModel);
JScrollPane employeeScroll = new JScrollPane(employeeList);
employeeScroll.setBorder(new TitledBorder("Employee List"));
addButton = new JButton("Add Employee");
addButton.addActionListener(this);
Box topBox = Box.createHorizontalBox();
topBox.add(addButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topBox, BorderLayout.NORTH);
getContentPane().add(employeeScroll, BorderLayout.CENTER);
pack();
}
public DefaultListModel<Employee> getListModel() {
return this.listModel;
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == addButton) {
// !! AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
AddEmployeeDialog frame = new AddEmployeeDialog(EmployeeFrame.this);
frame.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EmployeeFrame().setVisible(true);
}
});
}
}
#SuppressWarnings("serial")
class AddEmployeeDialog extends JDialog implements ActionListener {
private JComboBox<String> workerType;
private JTextField givenNameField;
private JTextField familyNameField;
private JButton okButton;
private JButton cancelButton;
private EmployeeFrame employeeFrame;
public AddEmployeeDialog(final EmployeeFrame frame) {
super(frame, "Add Employee", true);
setLocationRelativeTo(employeeFrame);
this.employeeFrame = frame;
workerType = new JComboBox<String>(Employee.getEmployeeTypes());
givenNameField = new JTextField(20);
familyNameField = new JTextField(20);
Box workerBox = Box.createHorizontalBox();
workerBox.add(new JLabel("Worker type"));
workerBox.add(workerType);
workerBox.add(new JLabel("Start date"));
Box givenNameBox = Box.createHorizontalBox();
givenNameBox.add(new JLabel("Given name "));
givenNameBox.add(givenNameField);
Box familyNameBox = Box.createHorizontalBox();
familyNameBox.add(new JLabel("Family name"));
familyNameBox.add(familyNameField);
workerType.setSelectedItem(null);
// Create buttons and add the current class as an ActionListener
okButton = new JButton("OK");
okButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
Box bottomBox = Box.createHorizontalBox();
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(okButton);
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(cancelButton);
bottomBox.add(Box.createHorizontalGlue());
// Lay out the GUI
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(workerBox);
getContentPane().add(givenNameBox);
getContentPane().add(familyNameBox);
getContentPane().add(Box.createVerticalStrut(10));
getContentPane().add(bottomBox);
pack();
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == okButton) {
System.out.println("here");
System.out.println(workerType.getSelectedItem());
if ("Salaried".equalsIgnoreCase(workerType.getSelectedItem().toString())) {
Employee employee = new Employee("Salaried", givenNameField.getText(), familyNameField.getText());
employeeFrame.getListModel().addElement(employee);
} else {
Employee employee = new Employee("Hourly", givenNameField.getText(), familyNameField.getText());
employeeFrame.getListModel().addElement(employee);
}
}
dispose();
}
}
class Employee {
private static final String[] EMPLOYEE_TYPES = { "Salaried", "Hourly" };
private String givenName;
private String familyName;
private String type;
public Employee(String type, String givenName, String familyName) {
this.type = type;
this.givenName = givenName;
this.familyName = familyName;
}
public static String[] getEmployeeTypes() {
return EMPLOYEE_TYPES;
}
public String getGivenName() {
return givenName;
}
public String getFamilyName() {
return familyName;
}
public String getType() {
return type;
}
#Override
public String toString() {
return String.format("Employee: %s, %s %s", type, givenName, familyName);
}
}

Add Values from JTextFied to JTable

public class BillDetailsPanel implements ActionListener {
JPanel panel;
int flag = 0;
JLabel lItemName, lPrice, lQty, ltax, lDisPrice;
JTextField price, qty, tax, disPrice;
JComboBox<String> itemName;
String[] bookTitles = new String[] { "Effective Java", "Head First Java",
"Thinking in Java", "Java for Dummies" };
JButton addBtn
public BillDetailsPanel() {
panel = new JPanel();
panel.setPreferredSize(new Dimension(900, 50));
FlowLayout layout = new FlowLayout(FlowLayout.CENTER, 5, 15);
panel.setLayout(layout);
// panel.setBackground(Color.GREEN);
lItemName = new JLabel("Item Name");
lPrice = new JLabel("Price");
lQty = new JLabel("Quantity");
ltax = new JLabel("Tax");
lDisPrice = new JLabel("Discount Price");
itemName = new JComboBox<String>(bookTitles);
itemName.addActionListener(this);
price = new JTextField(8);
// price.setEditable(false);
qty = new JTextField(4);
tax = new JTextField(5);
// tax.setEditable(false);
disPrice = new JTextField(8);
addBtn = new JButton("Add");
addBtn.addActionListener(this);
panel.add(lItemName);
panel.add(itemName);
panel.add(lPrice);
panel.add(price);
panel.add(lQty);
panel.add(qty);
panel.add(ltax);
panel.add(tax);
panel.add(lDisPrice);
panel.add(disPrice);
panel.add(addBtn);
panel.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
BillTablePanel btp=new BillTablePanel();
String[] data=new String[5];
data[0]=(String) itemName.getSelectedItem();
data[1]=price.getText();
data[2]=qty.getText();
data[3]=tax.getText();
data[4]=qty.getText();
btp.model.addRow(data);
btp.model.addRow(data);
System.out.println(data+"dataaaaaaaaaaaa");
}
}
}
public class BillTablePanel implements ActionListener{
public JPanel panel;
public JTable table;
public JScrollPane scrollPane, scrollPane1;
public DefaultTableModel model;
public int a=10;
String[] data=new String[5];
public BillTablePanel () {
panel = new JPanel();
panel.setLayout(null);
model = new DefaultTableModel();
String columnNames[] = { "Item Name", "Actual Price", "Qty", "Tax",
"Price" };
table = new JTable();
model.setColumnIdentifiers(columnNames);
table.setModel(model);
table.setFocusable(false);
scrollPane = new JScrollPane(table);
scrollPane.setBounds(0, 0, 850, 100);
panel.add(scrollPane);
}
<br>
public class TestClassFrame {
JFrame f;
BillDetailsPanel bill = new BillDetailsPanel();
BillTablePanel billTablePanel = new BillTablePanel();
public TestClassFrame() {
f = new JFrame("Zeon Systems");
f.setLayout(null);
bill.panel.setBounds(0, 0, 900, 100);
f.add(bill.panel);
billTablePanel.panel.setBounds(0, 100, 900, 500);
f.add(billTablePanel.panel);
f.pack();
f.setSize(900, 550);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestClassFrame();
}
}
Problem with this code is The class Bill detais contain some text boxes and a button The BillTablepane class contain a Jtable I want to add the items from BillDetaisaPanel to the Jtable
On clicking the Jbutton which is not showing any error but the values are not inserting on it
The Full source is there Somebody please help me to find the logical error,
In your actionPerformed method, you're creating a new BillTablePanel object, at line (1), and then trying to add to the table model on line (2):
public void actionPerformed(ActionEvent e) {
BillTablePanel btp=new BillTablePanel(); // **** (1)
// ...
btp.model.addRow(data); // ***** (2)
But understand that that new BillTablePanel is just that, a completely new and distinct object, one completely unrelated to the one that is displayed. To change the state of the displayed data, you must call methods on the displayed BillTablePanel object, not on a new one that you create just for the actionPerformed method.
For example, here's a similar minimal program:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableExample extends JPanel {
private HoldsTable holdsTable = new HoldsTable();
private JTextField lastNameField = new JTextField(10);
private JTextField firstNameField = new JTextField(10);
public TableExample() {
JPanel fieldPanel = new JPanel();
fieldPanel.add(new JLabel("Last Name:"));
fieldPanel.add(lastNameField);
fieldPanel.add(new JLabel("First Name:"));
fieldPanel.add(firstNameField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(new AbstractAction("Your Action") {
#Override
public void actionPerformed(ActionEvent evt) {
HoldsTable ht = new HoldsTable(); // creates a new reference -- bad!
String lastName = lastNameField.getText();
String firstName = firstNameField.getText();
ht.addName(lastName, firstName);
}
}));
buttonPanel.add(new JButton(new AbstractAction("My Action") {
#Override
public void actionPerformed(ActionEvent evt) {
// HoldsTable ht = new HoldsTable();
String lastName = lastNameField.getText();
String firstName = firstNameField.getText();
// ht.addName(lastName, firstName);
holdsTable.addName(lastName, firstName); // use the ref to the displayed object
}
}));
setLayout(new BorderLayout());
add(holdsTable, BorderLayout.CENTER);
add(fieldPanel, BorderLayout.PAGE_START);
add(buttonPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
TableExample mainPanel = new TableExample();
JFrame frame = new JFrame("TableExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class HoldsTable extends JPanel {
private static final String[] COL_NAMES = { "Last Name", "First Name" };
private DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0);
private JTable table = new JTable(model);
public HoldsTable() {
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
public void addName(String lastName, String firstName) {
String[] row = { lastName, firstName };
model.addRow(row);
}
}
Your program creates a new non-displayed object, and changes its properties, similar to this code in my program above:
#Override
public void actionPerformed(ActionEvent evt) {
HoldsTable ht = new HoldsTable(); // creates a new reference --
// bad!
String lastName = lastNameField.getText();
String firstName = firstNameField.getText();
ht.addName(lastName, firstName);
}
}));
But since the object whose state is being changed, here ht, but in your code its btp, is not the one that is displayed, nothing will show.
The correct way is shown in the other action:
#Override
public void actionPerformed(ActionEvent evt) {
// HoldsTable ht = new HoldsTable();
String lastName = lastNameField.getText();
String firstName = firstNameField.getText();
// ht.addName(lastName, firstName);
holdsTable.addName(lastName, firstName); // use the ref to the
// displayed object
}
I create a field of the GUI view that holds the JTable, here holdsTable and call a method on it. Since holdsTable is visible, changes in its state will be shown in the program (here the JTable).

Trouble Updating AbstractTableModel from another Class

I'm trying to update a JTable that pulls in data from an ArrayList. I have two frames in my program. The first frame is a JTable (AbstractTableModel) that displays the contents of the ArrayList. I click the "New" button on that frame to bring up the second window, which lets me add to the aforementioned ArrayList. When I click my "Save" button, the second window closes and the first is supposed to refresh with the new row. I don't have any syntactical errors in my code, and it looks conceptually right. I think the first place to start troubleshooting would be in the NoteCntl class. I'm under the impression that getNoteTableUI() should update the view with the new data when it's called, but I'm stumped as to what's going on. I'm new to the concept of Model View Controller, but I'd like to follow that as closely as possible.
Here is the Controller class:
public class NoteCntl {
private NoteTableModel theNoteTableModel = new NoteTableModel();;
private NoteTableUI theNoteTableUI;
private NoteDetailUI theNoteDetailUI;
public NoteCntl(){
theNoteTableUI = new NoteTableUI(this);
}
public NoteTableModel getNoteTableModel(){
return theNoteTableModel;
}
public void getNoteDetailUI(Note theNote){
if (theNoteDetailUI == null || theNote == null){
theNoteDetailUI = new NoteDetailUI(this,theNote);
}
else{
theNoteDetailUI.setVisible(true);
}
}
public NoteTableUI getNoteTableUI(){
theNoteTableModel.fireTableDataChanged(); //why doesn't this do anything?
theNoteTableUI.setVisible(true);
return theNoteTableUI;
}
public void deleteNote(int noteToDelete){
theNoteTableModel.removeRow(noteToDelete);
}
}
The First UI (Table):
public class NoteTableUI extends JFrame{
NoteTableModel noteModel;
NoteCntl theNoteCntl;
JPanel buttonPanel;
JPanel tablePanel;
JTable theNoteTable;
JScrollPane theScrollPane;
JButton backButton;
JButton deleteButton;
JButton editButton;
JButton newButton;
public NoteTableUI(NoteCntl theParentNoteCntl){
theNoteCntl = theParentNoteCntl;
this.initComponents();
this.setSize(400, 500);
this.setLocationRelativeTo(null);
this.setTitle("NoteTableUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
buttonPanel = new JPanel();
tablePanel = new JPanel();
backButton = new JButton("Back");
newButton = new JButton("New");
newButton.addActionListener(new newButtonListener());
editButton = new JButton("Edit");
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new deleteButtonListener());
noteModel = theNoteCntl.getNoteTableModel();
theNoteTable = new JTable(theNoteCntl.getNoteTableModel());
theScrollPane = new JScrollPane(theNoteTable);
theNoteTable.setFillsViewportHeight(true);
tablePanel.add(theScrollPane);
buttonPanel.add(backButton);
buttonPanel.add(deleteButton);
buttonPanel.add(editButton);
buttonPanel.add(newButton);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(tablePanel, BorderLayout.CENTER);
}
public class deleteButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int selectedRow = theNoteTable.getSelectedRow();
if (selectedRow == -1){
System.out.println("No row selected");
}
else{
noteModel.removeRow(selectedRow);
}
revalidate();
repaint();
}
}
public class newButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
NoteTableUI.this.setVisible(false);
NoteTableUI.this.theNoteCntl.getNoteDetailUI(null);
/*
NoteDetailCntl theNoteDetailCntl = new NoteDetailCntl();
lastRow++;
long newRow = lastRow;
noteModel.addRow(newRow, 0, "", "");
revalidate();
repaint();
*/
}
}
The 2nd UI (Detail editor)
public class NoteDetailUI extends JFrame{
private final int FRAME_WIDTH = 700;
private final int FRAME_HEIGHT = 500;
private final int FIELD_WIDTH = 10;
JButton saveButton;
JButton backButton;
JTextField idField;
JTextField dateField;
JTextField nameField;
JTextField descriptionField;
JTextArea noteDetail;
JLabel idLabel;
JLabel dateLabel;
JLabel nameLabel;
JLabel descriptionLabel;
JPanel buttonPanel;
JPanel textFieldPanel;
JPanel textAreaPanel;
JPanel mainPanel;
NoteTableModel theNoteTableModel;
NoteDetailCntl theNoteDetailCntl;
NoteCntl theNoteCntl;
Note theCurrentNote;
public NoteDetailUI(){
this.initComponents();
this.setSize(FRAME_WIDTH,FRAME_HEIGHT);
this.setLocationRelativeTo(null);
this.setTitle("NoteDetailUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public NoteDetailUI(NoteCntl parentNoteCntl, Note theSelectedNote){
theNoteCntl = parentNoteCntl;
theCurrentNote = theSelectedNote;
this.initComponents();
this.setSize(400,500);
this.setLocationRelativeTo(null);
this.setTitle("Note");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
saveButton = new JButton("Save");
saveButton.addActionListener(new saveButtonListener());
backButton = new JButton("Back");
backButton.addActionListener(new backButtonListener());
idField = new JTextField(FIELD_WIDTH);
theNoteTableModel = new NoteTableModel();
idField.setText("10");
idField.setEditable(false);
dateField = new JTextField(FIELD_WIDTH);
dateField.setText("20131108");
nameField = new JTextField(FIELD_WIDTH);
nameField.setText("Untitled");
descriptionField = new JTextField(FIELD_WIDTH);
descriptionField.setText("not described");
idLabel = new JLabel("ID");
dateLabel = new JLabel("Date");
nameLabel = new JLabel("Name");
descriptionLabel = new JLabel("Description");
noteDetail = new JTextArea(25,60);
buttonPanel = new JPanel();
textFieldPanel = new JPanel();
textAreaPanel = new JPanel();
mainPanel = new JPanel(new BorderLayout());
buttonPanel.add(backButton);
buttonPanel.add(saveButton);
textFieldPanel.add(idLabel);
textFieldPanel.add(idField);
textFieldPanel.add(dateLabel);
textFieldPanel.add(dateField);
textFieldPanel.add(nameLabel);
textFieldPanel.add(nameField);
textFieldPanel.add(descriptionLabel);
textFieldPanel.add(descriptionField);
textAreaPanel.add(noteDetail);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.add(textAreaPanel, BorderLayout.CENTER);
add(mainPanel);
}
public ArrayList<String> getNoteDetails(){
ArrayList<String> newData = new ArrayList<String>();
newData.add(idField.getText());
newData.add(dateField.getText());
newData.add(nameField.getText());
newData.add(descriptionField.getText());
return newData;
}
public class saveButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
/*
* Access the noteTableData array in NoteTableModel
* Add the newData fields in order
*/
if(theCurrentNote == null){
int newNoteNumber = Integer.parseInt(NoteDetailUI.this.idField.getText());
int newNoteDate = Integer.parseInt(NoteDetailUI.this.dateField.getText());
String newNoteName = NoteDetailUI.this.nameField.getText();
String newNoteDescription = NoteDetailUI.this.descriptionField.getText();
NoteDetailUI.this.theCurrentNote = new EssayNote(newNoteNumber,newNoteDate,newNoteName,newNoteDescription);
NoteDetailUI.this.setVisible(false);
NoteDetailUI.this.dispose();
NoteDetailUI.this.theNoteCntl.getNoteTableUI();
}
else{
//if it's a current Note
}
//Refresh the JTable
}
}
public class backButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
}
}
Thanks for all the help. I can provide the other classes if you want to just run the program and see what's happening, but I suspect it's either a problem with the fireTableDataChanged() call in the controller class or a problem with updating the contents of the ArrayList in the SaveButtonListener.

Problems with JList

Our teacher doesn't want us doing anything inside of the GUI class so all of our adding and removing of elements has to be outside in its own class. I've read about vectors and the adding and removing of elements in JList but like i stated we are not allowed to do it that way. My question is how i would go about clearing my list or refreshing it when I need to populate it with a new one or update the original. What my problem is the list duplicates itself every time I click the open button, When what I need it to do is refresh every time it is clicked.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.util.Collections;
import java.io.*;
/* Simple example of using the contents of a file to populate a JList
*
* #author Jill Courte
*/
public class JListFromFile extends JFrame {
private TextField wordA;
private TextField wordB;
private JButton openButton;
private JButton newButton;
private JButton addButton;
private JButton deleteButton;
private JButton saveButton;
private TextField output;
private JList listFromFile;
private JPanel listPanel;
private JPanel textPanel;
private JPanel inputPanel;
private JPanel buttonsPanel;
private DataSource2 dataSource;
private WordPair wordPair;
public JListFromFile ()
{
// create the object to provide the data
dataSource = new DataSource2();
wordPair = new WordPair();
// use a border layout for the main window
getContentPane().setLayout(new BorderLayout(20, 20));
buttonsPanel = new JPanel();
openButton = new JButton("Open");
newButton = new JButton("New");
addButton = new JButton("Add");
deleteButton = new JButton("Delete");
saveButton = new JButton("Save");
addButton.setEnabled( false );
deleteButton.setEnabled( false );
saveButton.setEnabled( false );
buttonsPanel.add(openButton);
buttonsPanel.add(newButton);
buttonsPanel.add(addButton);
buttonsPanel.add(deleteButton);
buttonsPanel.add(saveButton);
//add the button listeners
openButton.addActionListener(new OpenButtonListener());
addButton.addActionListener(new AddButtonListener());
add(buttonsPanel, BorderLayout.NORTH);
// create the panel to hold the list
listPanel = new JPanel();
// create your JList
listFromFile = new JList();
listFromFile.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listFromFile.setSelectedIndex(0);
//add the list selection listener
listFromFile.addListSelectionListener(new WordSelection());
//add the translation text box
textPanel = new JPanel();
output = new TextField();
output.setEditable(false);
output.setPreferredSize(new Dimension(200, 25));
textPanel.add(output);
// add scroll bars to list
JScrollPane listScrollPane = new JScrollPane(listFromFile);
listScrollPane.setPreferredSize(new Dimension(150, 200));
//add user input textfield
wordA = new TextField ("Word to Add");
wordB = new TextField ("Translated word");
wordA.setPreferredSize(new Dimension(200, 25));
wordB.setPreferredSize(new Dimension(200, 25));
wordA.setEnabled(false);
wordB.setEnabled(false);
//create panel to hold input textfield
inputPanel = new JPanel();
inputPanel.add(wordA);
inputPanel.add(wordB);
//add the list (via the scroll pane) to the panel
listPanel.add(listScrollPane);
//add the panels to the frame
add(listPanel, BorderLayout.WEST);
add(textPanel, BorderLayout.CENTER);
add(inputPanel, BorderLayout.SOUTH);
pack();
}
private File findFile ()
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// Start in current directory
chooser.setCurrentDirectory(new File("."));
int status = chooser.showOpenDialog(null);
if (status != JFileChooser.APPROVE_OPTION)
{
JOptionPane.showMessageDialog(null, "No File Selected");
throw new NoFileChoosenException();
}
else
{
File file = chooser.getSelectedFile();
System.out.println(file.getName());
System.out.println(file.getPath());
return file;
}
}
private class OpenButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
File file = null;
try
{
file = findFile();
//tell the data source what file to use
dataSource.readDataFromFile(file);
//JList needs an array of strings, retrieve it from the data source
String [] data = dataSource.getData();
data = dataSource.insertion(data);
data = wordPair.remove(data);
listFromFile.setListData(data);
}
catch (Exception e)
{
}
addButton.setEnabled(true);
deleteButton.setEnabled(true);
saveButton.setEnabled(true);
wordA.setEnabled(false);
wordB.setEnabled(false);
}
}
private class AddButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
wordA.setEnabled(true);
wordB.setEnabled(true);
}
}
private class WordSelection implements ListSelectionListener
{
public void valueChanged (ListSelectionEvent event)
{
int index = listFromFile.getSelectedIndex();
if (index >= 0)
{
String s = wordPair.getWord(2, index);
output.setText(s);
}
}
}
public static void main(String[] args)
{
JListFromFile jListFromFile = new JListFromFile();
jListFromFile.setVisible(true);
}
}

Java Error: IllegalArgumentException: adding a window to a container

I keep receiving the error:
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:483)
at java.awt.Container.addImpl(Container.java:1084)
at java.awt.Container.add(Container.java:966)
at Lab2.EmployeeGUI.main(EmployeeGUI.java:28)
Can someone please help me and tell me what I'm doing wrong?
I am beginner programmer.
package Lab2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* #author Jim Doyle
*/
public class EmployeeGUI extends JFrame implements ActionListener {
JTextField fName, mName, lName, phone, sal, years;
JComboBox boxTitle, boxDept;
DefaultListModel lstdefault;
JList project;
DbWork dbw = new DbWork("Lab2");
DbWork Title = new DbWork("Lab2");
DbWork Dept = new DbWork("Lab2");
DbWork Prjs = new DbWork("Lab2");
DbWork PrjList = new DbWork("Lab2");
public static void main(String[] args) {
EmployeeGUI app = new EmployeeGUI();
JFrame frame = new JFrame("Employee Interface by Jim Doyle");
frame.getContentPane().add(app, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public EmployeeGUI() {
JPanel labels = new JPanel();
labels.setLayout(new GridLayout(8,1));
labels.add(new JLabel("First Name"));
labels.add(new JLabel("MI"));
labels.add(new JLabel("Last Name"));
labels.add(new JLabel("Title"));
labels.add(new JLabel("Telephone"));
labels.add(new JLabel("Salary"));
labels.add(new JLabel("Department"));
labels.add(new JLabel("Years in Service"));
getContentPane().add(labels, BorderLayout.WEST);
JPanel fields = new JPanel();
fields.setLayout(new GridLayout(8,1));
fName = new JTextField(15);
mName = new JTextField(15);
lName = new JTextField(15);
phone = new JTextField(15);
sal = new JTextField(15);
years = new JTextField(15);
boxTitle = new JComboBox();
boxDept = new JComboBox();
fields.add(fName);
fields.add(mName);
fields.add(lName);
fields.add(boxTitle);
fields.add(phone);
fields.add(sal);
fields.add(years);
getContentPane().add(fields, BorderLayout.CENTER);
JPanel prjinfo = new JPanel();
prjinfo.setLayout(new GridLayout(1,2));
prjinfo.add(new JLabel("Project Description"));
project = new JList();
lstdefault = new DefaultListModel();
// add items to title combo box
while(Title.nextRecord()) {
String txtTit = Title.getField(1);
if(txtTit!=null) {
boxTitle.addItem(Title.getField(1));
}
}
// add items to department combo box
while(Dept.nextRecord()) {
String txtDept = Dept.getField(2);
if(txtDept!=null) {
boxDept.addItem(Dept.getField(2));
}
}
while(PrjList.nextRecord()) {
lstdefault.addElement(PrjList.getField(1));
}
project = new JList(lstdefault);
project.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
prjinfo.add(project);
getContentPane().add(prjinfo, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
String button = e.getActionCommand();
if(button == "First") {
if(dbw.firstRecord()) {
Execute();
}
}
else if(button == "Next") {
if(dbw.nextRecord()) {
Execute();
}
}
else if(button == "Save") {
String sql = "UPDATE FirstName, MiddleName, LastName, WorkPhone, Salary, YearsInService FROM Employee;";
dbw.processQuery(sql);
}
}
private void action() {
boxTitle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox b = (JComboBox)e.getSource();
String ntitle = (String)b.getSelectedItem();
updateTitle(ntitle);
}
});
}
private void Execute() {
fName.setText(dbw.getField(1));
mName.setText(dbw.getField(2));
lName.setText(dbw.getField(3));
phone.setText(dbw.getField(5));
sal.setText(dbw.getField(6));
years.setText(dbw.getField(8));
String ftext = dbw.getField(4);
int dx = TitleList(ftext);
boxTitle.setSelectedIndex(dx);
String dtext = dbw.getField(7);
int dx2 = DeptList(dtext);
boxDept.setSelectedIndex(dx2);
action();
}
int TitleList(String title) {
int dx = 0;
for(int z=0; z<boxTitle.getItemCount(); z++) {
if(title.equals(boxTitle.getItemAt(z))) {
dx = z;
}
}
return dx;
}
int DeptList(String dept) {
int dx = 0;
for(int z=0; z<boxDept.getItemCount(); z++) {
if(dept.equals(boxDept.getItemAt(z))) {
dx = z;
}
}
return dx;
}
private void updateTitle(String title) {
}
}
EmployeeGUI extends from JFrame, but in your main method, you are creating a new JFrame and are trying to add an instance of EmployeeGUI to it.
Change EmployeeGUI so it extends from JPanel instead
Here:
frame.getContentPane().add(app, BorderLayout.CENTER);
you're trying to add a JFrame to a JFrame which makes no sense.
Why not instead just try to display app rather than add it to a JFrame. Or even better, not have EmployeeGUI extend JFrame.
You can't add a JFrame to another JFrame.
But you can add a JPanel to a JFrame, in other words change EmployeeGUI to make it extends JPanel.

Categories