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);
}
}
Related
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);
}
}
I tried to add data to the JTable Dynamically using DefaultTableModel, but it isn't working.
I had created two classes: One class (Input.java) represents a popup which allows you to write the data (name, option and constraint) and save it. Another class represents a popup which includes a table (InputMain.java). InputMain will then transform those info (if received) to a row with in the table that list out those all the information in three columns. In Input, I created an instance of InputMain, and set the model of the table to a new DefaultTableModel() (if I don't do this, it will throw an error) (a table is already created in InputMain, so that if I create an instance of InputMain, I am probably calling the table within InputMain). Then, according to actionPerformed(ActionEvent e), after the 'enter' button is clicked within the JPanel, it will create a new array of data with nameText, optionText and constraintText. And finally, the data will be added to the model.
I don't know why I can't add all those data into the table, except that method above sounds logical to me.
Here's the InputMain.java class:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by paull on 14/5/2016.
*/
public class InputMain {
JButton add;
JButton change;
JButton delete;
JTable table;
String[] columns;
String[][] data;
JButton create;
JPanel labelPanel;
JPanel bigPanel;
JPanel centerPanel;
public InputMain() {
int fontSize = 50;
add = new JButton("add");
change = new JButton("change");
delete = new JButton("delete");
create = new JButton("create");
columns = new String[]{"name","option","constraint"};
data = new String[][]{{"","",""}};
table = new JTable(data,columns) {
#Override
public boolean isCellEditable(int row, int column) {
return false; //to avoid it from being changable by double clicking any data
}
};
table.setPreferredScrollableViewportSize(new Dimension(450,63));
table.setFillsViewportHeight(true);
JScrollPane jsp = new JScrollPane(table); // not always can the table be fully shown --> add a scrollbar
add.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
change.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
delete.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
create.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
table.setFont(new Font(table.getName(),Font.PLAIN,fontSize));
//table.getEditorComponent().setFont(new Font(add.getName(),Font.PLAIN,fontSize));
table.getTableHeader().setFont(new Font(table.getName(),Font.PLAIN,fontSize));
labelPanel = new JPanel();
labelPanel.add(add);
labelPanel.add(change);
labelPanel.add(delete);
labelPanel.setLayout(new FlowLayout(10,30,10));
centerPanel = new JPanel();
centerPanel.add(labelPanel);
centerPanel.setLayout(new GridBagLayout());
bigPanel = new JPanel();
bigPanel.setLayout(new GridLayout(3,0));
bigPanel.add(centerPanel);
bigPanel.add(jsp);
bigPanel.add(create);
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
Input i = new Input();
s.add(i.labelPanel);
s.setVisible(true);
}
}); // pressing add button pops up the Input Frame
}
}
And here's the Input.java class:
package com.company;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by paull on 14/5/2016.
*/
public class Input extends JPanel{
JLabel nameLabel;
JLabel optionLabel;
JLabel constraintLabel;
JButton enter;
JPanel labelPanel;
JPanel jp2;
JPanel jp3;
JPanel jp4;
JTextField nameText;
String[] optionStrings;
JComboBox<String> optionText;
JCheckBox wk1;
JCheckBox wk2;
JCheckBox wk3;
JCheckBox wk4;
JCheckBox wk5;
public Input() {
nameLabel = new JLabel("name: ");
optionLabel = new JLabel("option: ");
constraintLabel = new JLabel("constraint:");
enter = new JButton("add");
nameText = new JTextField(10);
Options c = new Options();
optionStrings = new String[]{c.satNight,c.sunEight,c.sunNineThirty,c.sunEleven,c.sunNight};
optionText = new JComboBox<String>(optionStrings);
wk1 = new JCheckBox("1");
wk2 = new JCheckBox("2");
wk3 = new JCheckBox("3");
wk4 = new JCheckBox("4");
wk5 = new JCheckBox("5");
int fontSize = 50;
nameLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
optionLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
constraintLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
enter.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
nameText.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
optionText.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk1.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk2.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk3.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk4.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk5.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
labelPanel = new JPanel();
labelPanel.add(nameLabel);
labelPanel.add(nameText);
labelPanel.add(optionLabel);
labelPanel.add(optionText);
labelPanel.add(constraintLabel);
labelPanel.add(wk1);
labelPanel.add(wk2);
labelPanel.add(wk3);
labelPanel.add(wk4);
labelPanel.add(wk5);
labelPanel.add(enter);
labelPanel.setLayout(new FlowLayout(10,30,10));
InputMain i = new InputMain();
i.table.setModel(new DefaultTableModel());
DefaultTableModel model = (DefaultTableModel) i.table.getModel();
enter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String constraintText = "";
String[] data = new String[]{nameText.getText(),optionText.getSelectedItem().toString(),constraintText};
model.addRow(data);
nameText.setText("");
}
});
}
}
Thanks in advance.
I think the problem lies in the actionPerformed of InputMain.
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
Input i = new Input();
s.add(i.labelPanel);
s.setVisible(true);
}
});
You construct a new instance of Input. That means that you create a new empty DefaultTableModel and attach it to your table each time you click on the add button. Try move the construction of the Input outside of your actionPerformed like this:
Input i = new Input();
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
s.add(i.labelPanel);
s.setVisible(true);
}
UPDATE
Of course the instantiation of InputMain inside of Input should be removed, too. Instead have a member of Type InputMain in Input:
private InputMain inputMain;
and change the constructor of Input to set the value:
public Input (InputMain inputMain) {
this.inputMain = inputMain;
...
And change the instantiation of Input in InputMain to
Input i = new Input(this);
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);
}
}
I'm trying to open a text file using JFilechooser and put strings in JList. I think all the strings go into the list but I don't know why the strings don't appear on JScrollPane. Is there any problem with grouplayout? i don't know what to change..
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.List;
public class WordFinder extends JFrame implements ActionListener {
private WordList words = new WordList();
private JScrollPane scroll;
private JLabel label;
private JLabel word;
private JTextField textArea;
private JButton button;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItem, menuItem2;
private JFileChooser fc;
private JList list;
static private final String newline = "\n";
private int lineCount;
public WordFinder() {
super("Word Finder");
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
menuBar = new JMenuBar();
menu = new JMenu("File");
menuBar.add(menu);
menuItem = new JMenuItem("Open...");
menuItem.addActionListener(this);
menuItem2 = new JMenuItem("Exit");
menuItem2.addActionListener(this);
menu.add(menuItem);
menu.add(menuItem2);
setJMenuBar(menuBar);
label = new JLabel("Find: ");
word = new JLabel(lineCount + " words total");
textArea = new JTextField();
textArea.setEditable(true);
textArea.setPreferredSize(new Dimension(200, 20));
button = new JButton("Clear");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.setText("");
}
});
scroll = makeListView();
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(new Dimension(200, 230));
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(label)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(textArea)
.addComponent(word)
.addComponent(scroll))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(button)));
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(label)
.addComponent(textArea)
.addComponent(button))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(word))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING))
.addComponent(scroll));
setVisible(true);
pack();
// call System.exit() when user closes the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JScrollPane makeListView() {
// String[] labels = {"1", "2", "3"};
// list = new JList(labels);
JScrollPane listScroller = new JScrollPane(list);
return listScroller;
}
private void updateListView(DefaultListModel listModel) {
list = new JList(listModel);
scroll = new JScrollPane(list);
}
public void actionPerformed(ActionEvent e) {
DefaultListModel listModel = new DefaultListModel();
if (e.getSource() == menuItem) {
int returnVal = fc.showOpenDialog(WordFinder.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String fileName = file.getAbsolutePath();
try {
FileReader files = new FileReader(fileName);
BufferedReader br = new BufferedReader(files);
String str;
while((str = br.readLine()) != null) {
listModel.addElement(str);
//System.out.println(str);
lineCount++;
}
System.out.println(lineCount);
updateListView(listModel);
br.close();
} catch (Exception ex) {
ex.printStackTrace(System.out);
System.out.println("can't read file");
}
System.out.println("Opening: " + file.getName() + newline);
}
} else if (e.getSource() == menuItem2) {
setVisible(false);
dispose();
}
}
/**
* Main method. Makes and displays a WordFinder window.
* #param args Command-line arguments. Ignored.
*/
public static void main(String[] args) {
// In general, Swing objects should only be accessed from
// the event-handling thread -- not from the main thread
// or other threads you create yourself. SwingUtilities.invokeLater()
// is a standard idiom for switching to the event-handling thread.
SwingUtilities.invokeLater(new Runnable() {
public void run () {
// Make and display the WordFinder window.
new WordFinder();
}
});
}
}
When you call makeListView the JList is null as it hasn't been initialized yet...thus, you are basically saying scroll = new JScrollPane(null);...which isn't particularly helpful...
Next, when you call updateListView, you create a new instance of the JList and JScrollPane and do nothing with them...
private void updateListView(DefaultListModel listModel) {
list = new JList(listModel);
scroll = new JScrollPane(list);
}
so they will never be displayed on the screen...
To rectify this, you will need to make some modifications...
Create an instance of the JList and assign it to the instance field list, before you create the JScrollPane
Instead of creating new instances of the list and scroll, simply use JList#setModel
You may also like to have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
With JList, you affect the size of the JScrollPane through the use of JList#setVisibleRowCount and JList#setPrototypeCellValue
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.