Updating a JPanel from an array - java

In this program, i have to create a GUI that saves objects of Contacts onto an array which then is turned into an array to be passed into the constructor of the default table model.
I know i'm doing an extra step here.
The back up button actually saves whatever is in the Vector of contacts onto a binary file.
The load button will load whatever file name you put in the username back into the vector.
The view all contacts should display everything that is in the vector(well technically the contactListArray).
I'm having this problem where i can't get the JTable on the view card to update. If I load the contacts, and then click load contacts it shows, so i know the data is being written into the .dat file correctly. The problem seems to be that once i click on the view button the JTable is creating and won't change, even though i have it set to change in the method.
The problem, i think, is down at the where is says if(source == viewBut)
that entire block i think may be the problem.
Thank you for your help in advance, i really appreciate it.
/*
* Lab number: Final Project
* Robert Lopez
* Section number: 4
*/
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.table.TableModel;
class Contact implements Serializable{ String firstName, lastName, eAddress, address, phoneNum; }
public class finalLab implements ActionListener{
static CardLayout layout;
static private JFrame frame = new JFrame("Address Book");
static private JButton[] topMenuButton = new JButton[5];
static private Vector<Contact> contactList = new Vector<Contact>();
static private int contactSize = 0;
static private String[] columnNames = {"First Name", "Last Name","E-Mail Address", "Address", "Phone Number"};
static private String[][] contactListArray;
//START--------------------------Menu Card----------------------------------------------
static JPanel menuCard = new JPanel(new BorderLayout());
static JPanel menuTop = new JPanel( new GridLayout(2,1) );
static private JLabel firstLabel = new JLabel("Use The Buttons Below To Manage Contacts");
static JPanel menuMid = new JPanel(new FlowLayout());
static private JLabel userName = new JLabel("User Name:");
static private JTextField userNameField = new JTextField("", 15);
static private JLabel numContacts = new JLabel("Number of Contacts:");
static private JTextField numContactsField= new JTextField("", 15);
static private JPanel menuLower = new JPanel(new GridLayout(2,8));
static private JButton loadBut = new JButton("Load Contacts");
static private JButton addBut = new JButton("Add New Contacts");
static private JButton searchBut = new JButton("Search Contacts");
static private JButton sortBut = new JButton("Sort Contacts");
static private JButton deleteBut = new JButton("Delete Contacts");
static private JButton viewBut = new JButton("View All Contacts");
static private JButton backupBut = new JButton("Backup Contacts");
static private JButton blankBut = new JButton("");
//END---------------------------------Menu Card------------------------------------
//START---------------------------------View Card------------------------------------
//View Panel
static private JPanel viewCard = new JPanel(new BorderLayout());
static private JPanel viewCardLower = new JPanel();
static private JLabel viewLabel = new JLabel("Contact List");
static private JTable viewContacts;
static private JPanel viewCardMid = new JPanel(new BorderLayout());
static private JTableHeader header;
static private JScrollPane scrollPane = new JScrollPane();
//END---------------------------------View Card------------------------------------
//START-----------------------------------Delete Card------------------------------------
//Delete Panel
static private JPanel deleteCard = new JPanel(new GridLayout (3,1));
static private JPanel deleteMid = new JPanel();
static private JPanel deleteLower = new JPanel();
static private JLabel deleteLabel = new JLabel("Delete Contacts");
static private JLabel contactInfoLabel = new JLabel("Contact Phone #");
static private JTextField contactInfoField = new JTextField("", 15);
//END-----------------------------------Delete Card---------------------------------
//START-----------------------------------Add Contact-------------------------------
static private JPanel addCard = new JPanel(new GridLayout(6,2));
static private JLabel firstNameLabel = new JLabel("First Name");
static private JLabel lastNameLabel = new JLabel("Last Name");
static private JLabel eAddressLabel = new JLabel(" E-Mail Address");
static private JLabel addressLabel = new JLabel("Address");
static private JLabel phoneNumLabel = new JLabel("Phone No.");
static private JTextField firstNameField = new JTextField("", 10);
static private JTextField lastNameField = new JTextField("", 10);
static private JTextField eAddressField = new JTextField("", 10);
static private JTextField addressField = new JTextField("", 10);
static private JTextField phoneNumField = new JTextField("", 10);
static private JButton saveContactBut = new JButton("Save New Contact");
static private JPanel addLowerLeft = new JPanel();
static private JPanel addLowerRight = new JPanel();
//END------------------------------------Add Contact-----------------------------
//****************************** MAIN METHOD *******************************
static JPanel contentPane = (JPanel)frame.getContentPane();
static private JPanel mainPanel = new JPanel();
public static void main(String[] args){
ActionListener AL = new finalLab();
mainPanel.setLayout(layout = new CardLayout() );
contentPane.setLayout(new BorderLayout());
//Buttons, Labels
loadBut.addActionListener(AL);
for(int i = 0; i < 5; i++){
topMenuButton[i] = new JButton("Top Menu");
topMenuButton[i].addActionListener(AL);
}
backupBut.addActionListener(AL);
viewBut.addActionListener(AL);
addBut.addActionListener(AL);
deleteBut.addActionListener(AL);
saveContactBut.addActionListener(AL);
//-------------------------------------------------------
//Top Menu
firstLabel.setHorizontalAlignment(JTextField.CENTER);
firstLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
menuTop.add(firstLabel);
numContactsField.setEditable(false);
numContactsField.setText("" + contactSize);
//Adding Middle Content
menuMid.add(userName);
menuMid.add(userNameField);
menuMid.add(numContacts);
menuMid.add(numContactsField);
//Adding Lower Content
menuLower.add(loadBut);
menuLower.add(addBut);
menuLower.add(searchBut);
menuLower.add(sortBut);
menuLower.add(deleteBut);
menuLower.add(viewBut);
menuLower.add(backupBut);
menuLower.add(blankBut);
menuCard.add(menuTop, BorderLayout.NORTH);
menuCard.add(menuMid, BorderLayout.CENTER);
menuCard.add(menuLower, BorderLayout.SOUTH);
//-------------------------------------------------------
//Delete Card
deleteLabel.setHorizontalAlignment(JTextField.CENTER);
deleteLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
deleteCard.add(deleteLabel);
deleteMid.add(contactInfoLabel);
deleteMid.add(contactInfoField);
deleteCard.add(deleteMid);
deleteLower.add(topMenuButton[0]);
deleteCard.add(deleteLower);
//-------------------------------------------------------
//Add Card
firstNameLabel.setHorizontalAlignment(JTextField.RIGHT);
lastNameLabel.setHorizontalAlignment(JTextField.RIGHT);
eAddressLabel.setHorizontalAlignment(JTextField.RIGHT);
addressLabel.setHorizontalAlignment(JTextField.RIGHT);
phoneNumLabel.setHorizontalAlignment(JTextField.RIGHT);
addCard.add(firstNameLabel);
addCard.add(firstNameField);
addCard.add(lastNameLabel);
addCard.add(lastNameField);
addCard.add(eAddressLabel);
addCard.add(eAddressField);
addCard.add(addressLabel);
addCard.add(addressField);
addCard.add(phoneNumLabel);
addCard.add(phoneNumField);
addLowerLeft.add(saveContactBut);
addLowerRight.add(topMenuButton[1]);
addCard.add(addLowerLeft);
addCard.add(addLowerRight);
//----------------------------------------------------------
//View Card
viewLabel.setHorizontalAlignment(JTextField.CENTER);
viewLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
viewCard.add(viewLabel, BorderLayout.NORTH);
viewCardLower.add(topMenuButton[2]);
viewCard.add(viewCardLower, BorderLayout.SOUTH);
//Adding to frame
mainPanel.add("Menu Card", menuCard);
mainPanel.add("Delete Card", deleteCard);
mainPanel.add("Add Card", addCard);
//mainPanel.add("View Card", viewCard);
contentPane.add(mainPanel);
layout.show(mainPanel, "Menu Card");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 275);
frame.setResizable(false);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Object source =e.getSource();
if(source == loadBut){
try {
FileInputStream fis = new FileInputStream (userNameField.getText());
ObjectInputStream ois = new ObjectInputStream(fis);
contactList.clear();
contactSize = 0;
for(; true; contactSize++){
contactList.add( (Contact) ois.readObject() );
numContactsField.setText("" + (contactSize+1) );
}
} catch(EOFException e2){
} catch(Exception e2){
e2.printStackTrace();
}
}
if(source == addBut)
layout.show(mainPanel, "Add Card");
if(source == viewBut){
contactListArray = new String[contactSize][5];
for(int i = 0; i < contactSize; i++){
contactListArray[i][0] = contactList.get(i).firstName;
contactListArray[i][1] = contactList.get(i).lastName;
contactListArray[i][2] = contactList.get(i).eAddress;
contactListArray[i][3] = contactList.get(i).address;
contactListArray[i][4] = contactList.get(i).phoneNum;
}
DefaultTableModel model = new DefaultTableModel(contactListArray,columnNames);
viewContacts = new JTable(model);
header = viewContacts.getTableHeader();
viewContacts.setFillsViewportHeight(true);
viewContacts.revalidate();
viewCardMid.add(header, BorderLayout.NORTH);
viewCardMid.add(viewContacts, BorderLayout.CENTER);
viewCard.add(viewCardMid, BorderLayout.CENTER);
mainPanel.add("View Card", viewCard);
layout.show(mainPanel, "View Card");
}
if(source == deleteBut)
layout.show(mainPanel, "Delete Card");
if(source == saveContactBut){
contactList.add(new Contact());
contactList.get(contactSize).firstName = firstNameField.getText();
contactList.get(contactSize).lastName = lastNameField.getText();
contactList.get(contactSize).eAddress = eAddressField.getText();
contactList.get(contactSize).address = addressField.getText();
contactList.get(contactSize).phoneNum = phoneNumField.getText();
contactSize++;
firstNameField.setText("");
lastNameField.setText("");
eAddressField.setText("");
addressField.setText("");
phoneNumField.setText("");
}
if(source == backupBut){
try{
FileOutputStream fos = new FileOutputStream (userNameField.getText(), false);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(int i = 0; i < contactSize; i++)
oos.writeObject(contactList.get(i));
oos.close();
}
catch (IOException e2){
System.out.println("IO Exception " + e2);
}
}
for(int i = 0; i < 5; i++)
if(source == topMenuButton[i]){
layout.show(mainPanel, "Menu Card");
numContactsField.setText("" + contactSize);
}
}
}

The problem revolves around you lack of understanding in how tables and the CardLayout works..
// This is good...
DefaultTableModel model = new DefaultTableModel(contactListArray, columnNames);
// This is bad...
viewContacts = new JTable(model);
// This is bad...and raises some eyebrows
header = viewContacts.getTableHeader();
// This okay, but doesn't belong here, and is pointless given the following code...
viewContacts.setFillsViewportHeight(true);
// Pointless, you've not added the component to anything yet..
viewContacts.revalidate();
// ?? What ??
viewCardMid.add(header, BorderLayout.NORTH);
// Not good. The table should be added to a JScrollPane first and the scroll
// pane added to the card
viewCardMid.add(viewContacts, BorderLayout.CENTER);
// Okay, but wrong place...
viewCard.add(viewCardMid, BorderLayout.CENTER);
// Here is your main problem. The card layout only allows one component to exist
// for a given name. If you try and add another card, it is discarded and the first
// component with that name remains
mainPanel.add("View Card", viewCard);
// Not bad...
layout.show(mainPanel, "View Card");
Instead of creating the table view when the view button is pressed, you should initalise and the view when you first create the UI and replace/update the table model when you click the view button...
In your constructor you should add...
viewContacts = new JTable(); // Don't need the model at this stage
viewContacts.setFillsViewportHeight(true);
viewCardMid.add(new JScrollPane(viewContacts), BorderLayout.CENTER);
mainPanel.add("View Card", viewCard);
And in your view button action code...
DefaultTableModel model = new DefaultTableModel(contactListArray, columnNames);
viewContacts.setModel(model);
mainPanel.add("View Card", viewCard);
Also, as has begin pointed about, you should not be using static class fields, it's not required in your case and will cause you issues as the complexity of your program grows.
You should be using if-else statements in you action performed method, this will reduce the possibility of logic errors and help improve performance
You should also investigate moving the logic for each view into it's own class, so as to reduce the clutter in your main class
Take the time to read through Creating a GUI With JFC/Swing, in particular, I'd looking into How to use Tables and How to use CardLayout

You make your variables static. The memory for static variables is not allocated on the stack but in regular memory. I didnt look at your code in detail but i would try to remove all static variables in your class and try again from there.

Related

StackOverflowError when adding JTextField to the constructor

So I do know what an StackOverflowError is, the problem however is I can't find it here. I am supposed to make a simple GUI with labels, text fields and buttons. One of these buttons is supposed to "clear" the text fields, so I add that by putting text field as an argument in the constructor, but when I actually add the text fields i just get an stack overflow error. Here is the code:
Orders class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Orders extends JFrame {
public Orders() {
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(4, 2, 2, 2));
JLabel name = new JLabel("Item name:");
JLabel number = new JLabel("Number of:");
JLabel cost = new JLabel("Cost:");
JLabel amount = new JLabel("Amount owed:");
JTextField nameJtf = new JTextField(10);
JTextField numberJtf = new JTextField(10);
JTextField costJtf = new JTextField(10);
JTextField amountJtf = new JTextField(10);
panel1.add(name);
panel1.add(nameJtf);
panel1.add(number);
panel1.add(numberJtf);
panel1.add(cost);
panel1.add(costJtf);
panel1.add(amount);
panel1.add(amountJtf);
JPanel panel2 = new JPanel();
JButton calculate = new JButton("Calculate");
JButton save = new JButton("Save");
JButton clear = new JButton("Clear");
JButton exit = new JButton("Exit");
panel2.add(calculate);
panel2.add(save);
panel2.add(clear);
panel2.add(exit);
OnClick action = new OnClick(exit, clear, save, calculate, nameJtf, numberJtf, costJtf, amountJtf);
exit.addActionListener(action);
this.setTitle("Otto's Items Orders Calculator");
this.add(panel1, BorderLayout.NORTH);
this.add(panel2, BorderLayout.SOUTH);
this.setSize(400, 200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Orders();
}
}
OnClick class :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OnClick extends Orders implements ActionListener {
private JButton exitModify = null;
private JButton clearModify = null;
private JButton saveModify = null;
private JButton calculateModify = null;
private JTextField nameModify = null;
private JTextField numberModify = null;
private JTextField costModify = null;
private JTextField amountModify = null;
public OnClick (JButton _exitModify, JButton _clearModify, JButton _saveModify, JButton _calculateModify, JTextField _nameModify, JTextField _numberModify, JTextField _costModify, JTextField _amountModify) {
exitModify = _exitModify;
clearModify = _clearModify;
saveModify = _saveModify;
calculateModify = _calculateModify;
nameModify = _nameModify;
numberModify = _numberModify;
costModify = _numberModify;
amountModify = _amountModify;
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == this.exitModify) {
System.exit(0);
} else if (o == this.clearModify) {
amountModify = null;
nameModify = null;
costModify = null;
numberModify = null;
}
}
}
As soon as I add nameJtf I get this error.

Java Swing: Can't show several instances of my JPanel

I'm making a GUI and having trouble with a JPanel.
First of all here is my JPanel:
public class ExperimentPanel extends JPanel{
private static File file1,file2=null;
private static DefaultListModel model = new DefaultListModel();
private static JList list = new JList(model);
private static JPanel mainpanel = new JPanel();
private static JPanel leftpanel = new JPanel();
private static JPanel rightpanel = new JPanel();
private static JPanel twoFiles = new SelectTwoFiles();
private static JPanel folderOrFile = new SelectFolderOrFile();
private static JPanel foldersOrFiles = new SelectTwoFoldersOrFiles();
public ExperimentPanel(int selectID){
this.setBorder(new EmptyBorder(10, 10, 10, 10));
if(selectID==Constants.SelectTwoFiles){
this.add(twoFiles, BorderLayout.NORTH);
}
else if(selectID==Constants.SelectFolderOrFile){
this.add(folderOrFile, BorderLayout.NORTH);
}
else if(selectID==Constants.SelectTwoFoldersOrFiles){
this.add(foldersOrFiles,BorderLayout.NORTH);
}
JButton remove =new JButton("Remove Method");
JButton add = new JButton("Add Method");
JButton save = new JButton("Save list");
JButton load = new JButton("Load list");
leftpanel.add(new JScrollPane(list));
Box listOptions = Box.createVerticalBox();
listOptions.add(add);
listOptions.add(remove);
listOptions.add(save);
listOptions.add(load);
rightpanel.add(listOptions);
Box mainBox = Box.createHorizontalBox();
mainBox.add(leftpanel);
mainBox.add(rightpanel);
//mainBox.add(leftleft);
this.add(mainBox, BorderLayout.CENTER);
//start jobs
JButton start = new JButton("Launch experiment");
this.add(start,BorderLayout.PAGE_END);
start.addActionListener(launch);
add.addActionListener(adding);
remove.addActionListener(delete);
}
public static ActionListener launch = new ActionListener(){
public void actionPerformed(ActionEvent event){
//check the files
if((file1==null)||(file2==null)){
JOptionPane.showMessageDialog(null,
"A graph file is missing",
"Wrong files",
JOptionPane.ERROR_MESSAGE);
}
//checks the list
}
};
public static ActionListener delete = new ActionListener() {
public void actionPerformed(ActionEvent event) {
ListSelectionModel selmodel = list.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
if (index >= 0)
model.remove(index);
}
};
public static ActionListener adding = new ActionListener(){
public void actionPerformed(ActionEvent event){
JComboBox combo = new JComboBox();
final JPanel cards = new JPanel(new CardLayout());
JPanel form = new JPanel();
JPanel methode1 = new JPanel();
methode1.add(new JLabel("meth1"));
methode1.setBackground(Color.BLUE);
methode1.setName("meth1");
JPanel methode2 = new JPanel();
methode2.add(new JLabel("meth2"));
methode2.setBackground(Color.GREEN);
methode1.setName("meth2");
combo.addItem("meth1");
combo.addItem("meth2");
cards.add(methode1,"meth1");
cards.add(methode2,"meth2");
JPanel control = new JPanel();
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcb = (JComboBox) e.getSource();
CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, jcb.getSelectedItem().toString());
}
});
control.add(combo);
form.add(cards, BorderLayout.CENTER);
form.add(control, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null,form,"Select a method",JOptionPane.PLAIN_MESSAGE);
}
};
}
The problem is that if i create several instances of that panel they won't show like intended.
I tried creating 2 simple JFrames in my main with a new ExperimentPanel for each so the problem is not from the caller.
It works well with one JFrame calling one experiementPanel.
here is the display for one and 2 calls:
http://imgur.com/a/4DHJn
And how i call them:
JFrame test = new JFrame();
test.add(new ExperimentPanel(3));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
test.setLocation(dim.width/3 - test.getWidth()/3, dim.height/3 - test.getHeight()/3);
test.setSize(550,300);
test.setVisible(true);
JFrame test2 = new JFrame();
test2.add(new ExperimentPanel(3));
test2.setLocation(dim.width/3 - test.getWidth()/3, dim.height/3 - test.getHeight()/3);
test2.setSize(550,300);
test2.setVisible(true);
You create a Panel class ExperimentPanel which itself consists of several components which are stored in class fields of ExperimentPanel.
Since you declare these class fields as static there is only one instance of them. When you instantiate several ExperimentPanel objects they all want to share these fields, which leads to the effects you have seen.
Therefore remove the static modifier from these fields:
public class ExperimentPanel extends JPanel{
private File file1,file2=null;
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JPanel mainpanel = new JPanel();
private JPanel leftpanel = new JPanel();
...

Java Swing: Action Listener Not Working Correctly

For some reason my action listener isn't working correctly. When I add the first number to it it works fine, but when I continue to add numbers it stops working correctly. Any ideas on why this happens would be appreciated!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculatorFinal extends JFrame{
private JLabel additionLabel;
private JTextField additionField;
private JButton additionButton;
private JPanel multiplication;
private JLabel multiplicationLabel;
private JTextField multiplicationField;
private JButton multiplicationButton;
private JPanel total;
private JLabel totalLabel;
private JTextField totalField;
private JButton stopButton;
public BabyCalculatorFinal(){
setDefaultCloseOperation(EXIT_ON_CLOSE);// 1st thing to do
setName("Baby Calculator Final"); // 2nd thing to do
setLayout(new GridLayout(3,0)); //sets grid layout for the entire thing with 3 rows
// Create Action Event
BabyCalculatorListener listener = new BabyCalculatorListener();
//Addition
//Addition Set Layout
JPanel addition = new JPanel(new BorderLayout());
//Addition Features
additionLabel = new JLabel("Amount to add"); //Create label
additionField = new JTextField(10);
additionButton = new JButton("Add");
//Organize Addition Panel
addition.add(additionLabel, BorderLayout.WEST);//IMPORTANT FORMAT
addition.add(additionField, BorderLayout.CENTER);
addition.add(additionButton, BorderLayout.EAST);
//Add addition Panel to Frame
add(addition);
additionButton.addActionListener(listener);
//Multiplictation
//Multiplication Set Layout
multiplication = new JPanel();
multiplication.setLayout(new BorderLayout());//Trying a different way of setting the layout
//Multiplication Features
multiplicationLabel = new JLabel("Amount to Multiply"); //Create label
multiplicationField = new JTextField(10);
multiplicationButton = new JButton("Multiply");
//Organize Multiplication Panel
multiplication.add(multiplicationLabel, BorderLayout.WEST);
multiplication.add(multiplicationField, BorderLayout.CENTER);
multiplication.add(multiplicationButton, BorderLayout.EAST);
//Add Multiplication Panel to Frame
add(multiplication);
multiplicationButton.addActionListener(listener);
//Total
total = new JPanel(new FlowLayout());
totalLabel = new JLabel("Total");
totalField = new JTextField();
totalField.setText("0.0");
totalField.setEditable(false);
stopButton = new JButton("Stop");
total.add(totalLabel);
total.add(totalField);
total.add(stopButton);
//Add Total Panel to Frame
add(total);
pack();
setVisible(true);
}
public static void main(String[] args){
JFrame myFrame = new BabyCalculatorFinal();
}
public class BabyCalculatorListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String totalText = totalField.getText();
double totalAmount = Double.parseDouble(totalText);
if (e.getSource() == additionButton){
String additionText = additionField.getText();
double addAmount = Double.parseDouble(additionText);
totalAmount += addAmount;
}
else{
String multiplicationText = multiplicationField.getText();
double multiplicationAmount = Double.parseDouble(multiplicationText);
totalAmount *= multiplicationAmount;
}
totalField.setText(totalAmount + "");
}
}
}
Your code works fine for me. It could be a repaint issue that you're experiencing. Try resizing the frame when you stop seeing the "total" change. If that works, you could try a repaint() after setting the totalField text.

I need help figuring out why my clear button code does not work

I am working on a project for my Java class and cannot get my clear button to work. More specifically, I am having an issue implementing Action and ItemListeners. My understanding is that I need to use ActionListener for my clear button, but I need to use ItemListener for my ComboBoxes. I am very new to Java and this is an intro class. I haven't even begun to code the submit button and ComboBoxes and am a little overwhelmed. For now, I could use help figuring out why my clear function will not work. Any help is greatly appreciated. Thanks in advance.
Here is my updated code after suggestions:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class cousinsTree extends JApplet
{
Container Panel;
JButton submitButton;
JButton clearButton;
JTextField firstName;
JTextField lastName;
JTextField Address;
JTextField City;
JMenuBar menuBar;
JTextField Total;
JComboBox Service;
JComboBox howOften;
JComboBox numTrees;
LayoutManager setLayout;
String[] TreeList;
String[] numList;
String[] oftenList;
#Override
public void init()
{
Panel = getContentPane();
this.setLayout(new FlowLayout());
TreeList= new String[3];
TreeList [0] = "Trim";
TreeList [1] = "Chemical Spray";
TreeList [2] = "Injection";
numList = new String[3];
numList [0] = "0-5";
numList [1] = "6-10";
numList [2] = "11 >";
oftenList = new String[3];
oftenList [0] = "Monthly";
oftenList [1] = "Quarterly";
oftenList [2] = "Annually";
Panel.setBackground (Color.green);
submitButton = new JButton("Submit");
submitButton.setPreferredSize(new Dimension(100,30));
clearButton.addActionListener(new clrButton());
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(100,30));
firstName = new JTextField("", 10);
JLabel lblFirstName = new JLabel("First Name");
lastName = new JTextField("", 10);
JLabel lblLastName = new JLabel("Last Name");
Address = new JTextField("", 15);
JLabel lblAddress = new JLabel("Address");
City = new JTextField("Columbus", 10);
JLabel lblCity = new JLabel("City");
Total = new JTextField("", 10);
JLabel lblTotal = new JLabel("Total");
//Service = new TextField("Service (Trim, Chemical Spray, or Injection).", 20);
JLabel lblService = new JLabel("Service");
Service=new JComboBox(TreeList);
JLabel lblhowOften = new JLabel("How often?");
howOften = new JComboBox(oftenList);
JLabel lblnumTrees = new JLabel("Number of Trees");
numTrees = new JComboBox(numList);
/* Configuration */
//add items to panel
Panel.add(lblFirstName);
Panel.add(firstName);
Panel.add(lblLastName);
Panel.add(lastName);
Panel.add(lblAddress);
Panel.add(Address);
Panel.add(lblCity);
Panel.add(City);
Panel.add(lblnumTrees);
Panel.add(numTrees);
Panel.add(lblService);
Panel.add(Service);
Panel.add(lblhowOften);
Panel.add(howOften);
Panel.add(submitButton);
Panel.add(clearButton);
Panel.add(lblTotal);
Panel.add(Total);
this.setSize(new Dimension(375, 275));
this.setLocation(0,0);
Service.setSelectedIndex (1);
howOften.setSelectedIndex (1);
numTrees.setSelectedIndex (1);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menuFile = new JMenu("File", true);
menuFile.setMnemonic(KeyEvent.VK_F);
menuFile.setDisplayedMnemonicIndex(0);
menuBar.add(menuFile);
JMenu menuSave = new JMenu("Save", true);
menuSave.setMnemonic(KeyEvent.VK_S);
menuSave.setDisplayedMnemonicIndex(0);
menuBar.add(menuSave);
JMenu menuExit = new JMenu("Exit", true);
menuExit.setMnemonic(KeyEvent.VK_X);
menuExit.setDisplayedMnemonicIndex(0);
menuBar.add(menuExit);
}
class clrButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// clearButton.addActionListener(this);
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
class subButton implements ItemListener {
public void itemStateChanged(ItemEvent e) {
submitButton.addItemListener(this);
Service.addItemListener(this);
numTrees.addItemListener(this);
howOften.addItemListener(this);
}
}
}
I was able to get it to work...Thank you all for your help. I removed the class and it worked.
Here is the working code:
[Code]
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class cousinsTree extends JApplet implements ActionListener
{
Container Panel;
JButton submitButton;
JButton clearButton;
JTextField firstName;
JTextField lastName;
JTextField Address;
JTextField City;
JMenuBar menuBar;
JTextField Total;
JComboBox Service;
JComboBox howOften;
JComboBox numTrees;
LayoutManager setLayout;
String[] TreeList;
String[] numList;
String[] oftenList;
public void init()
{
Panel = getContentPane();
this.setLayout(new FlowLayout());
TreeList= new String[3];
TreeList [0] = "Trim";
TreeList [1] = "Chemical Spray";
TreeList [2] = "Injection";
numList = new String[3];
numList [0] = "0-5";
numList [1] = "6-10";
numList [2] = "11 >";
oftenList = new String[3];
oftenList [0] = "Monthly";
oftenList [1] = "Quarterly";
oftenList [2] = "Annually";
Panel.setBackground (Color.green);
submitButton = new JButton("Submit");
submitButton.setPreferredSize(new Dimension(100,30));
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setPreferredSize(new Dimension(100,30));
firstName = new JTextField("", 10);
JLabel lblFirstName = new JLabel("First Name");
lastName = new JTextField("", 10);
JLabel lblLastName = new JLabel("Last Name");
Address = new JTextField("", 15);
JLabel lblAddress = new JLabel("Address");
City = new JTextField("Columbus", 10);
JLabel lblCity = new JLabel("City");
Total = new JTextField("", 10);
JLabel lblTotal = new JLabel("Total");
//Service = new TextField("Service (Trim, Chemical Spray, or Injection).", 20);
JLabel lblService = new JLabel("Service");
Service=new JComboBox(TreeList);
JLabel lblhowOften = new JLabel("How often?");
howOften = new JComboBox(oftenList);
JLabel lblnumTrees = new JLabel("Number of Trees");
numTrees = new JComboBox(numList);
/* Configuration */
//add items to panel
Panel.add(lblFirstName);
Panel.add(firstName);
Panel.add(lblLastName);
Panel.add(lastName);
Panel.add(lblAddress);
Panel.add(Address);
Panel.add(lblCity);
Panel.add(City);
Panel.add(lblnumTrees);
Panel.add(numTrees);
Panel.add(lblService);
Panel.add(Service);
Panel.add(lblhowOften);
Panel.add(howOften);
Panel.add(submitButton);
Panel.add(clearButton);
Panel.add(lblTotal);
Panel.add(Total);
this.setSize(new Dimension(375, 275));
this.setLocation(0,0);
Service.setSelectedIndex (1);
howOften.setSelectedIndex (1);
numTrees.setSelectedIndex (1);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menuFile = new JMenu("File", true);
menuFile.setMnemonic(KeyEvent.VK_F);
menuFile.setDisplayedMnemonicIndex(0);
menuBar.add(menuFile);
JMenu menuSave = new JMenu("Save", true);
menuSave.setMnemonic(KeyEvent.VK_S);
menuSave.setDisplayedMnemonicIndex(0);
menuBar.add(menuSave);
JMenu menuExit = new JMenu("Exit", true);
menuExit.setMnemonic(KeyEvent.VK_X);
menuExit.setDisplayedMnemonicIndex(0);
menuBar.add(menuExit);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == clearButton) {
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
}
[/Code]
Add following line
clearButton.addActionListener(new clrButton());
class clrButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// clearButton.addActionListener(this); Comment it
// if(e.getSource() == clearButton){-> this line don't need.
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
You are doing good. But just place the following code
clearButton.addActionListener(new clrButton());
Before and outside of class clrButton
Also try placing these statements outside of class subButton
submitButton.addItemListener(new subButton());
Service.addItemListener(new anotherClass());
numTrees.addItemListener(new anotherClass());
howOften.addItemListener(new anotherClass());
You need to add actionlistener to your buttons. so, the action events will be propogated to the listener where you do your logic of the action. so, you have to addActionListener to your button
clearButton.addActionListener(new clrButton());
i.e in your init() method
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(100,30));
//add this below line to add action listener to the button
clearButton.addActionListener(new clrButton());
Onemore line to be removed is clearButton.addActionListener(this); from your action performed method

Java IOStream Arrays JFrame

I have to create a CD inventory program for my first Java class. The book is poorly written and extremely verbose. I have created 4 frames to handle each requirement of the assignment. But the book doesn't explain how to write arrays to a .dat file. If I could get an idea of how to add data to an array from my TextFields then write to a .dat file I could stumble through the rest. Here is what I have so far. How do I take my JTextFields from my Add CD listener and write to a .dat file so I can view it later.
import java.util.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
class CDinventoryItem extends JFrame implements Comparable <CDinventoryItem> {
private String sPtitle;
private String genreCD;
private int iPitemNumber;
private int iPnumberofUnits;
private double dPunitPrice;
private double dEvalue;
private JFrame frame2= new JFrame();
private JFrame frame3= new JFrame();
private JFrame frame4= new JFrame();
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private JPanel panel3 = new JPanel();
private JPanel panel4 = new JPanel();
private JPanel panel5 = new JPanel();
private JPanel panel6 = new JPanel();
private JLabel[] label = new JLabel[20];
private JTextField titleField;
private JTextField itemNField;
private JTextField numofunitsField;
private JTextField priceField;
private JButton next;
private JButton prev;
private JButton addCD = new JButton ("Add CD");
private JButton save = new JButton ("Save");
private JButton delete;
private JButton modify;
private JButton search = new JButton ("Search for CD");
private JButton mainmenu;
private JButton displayCD = new JButton ("Display Inventory");
private CDinventoryItem [] inven;
private DataOutputStream outFile;
private DataInputStream inputFile;
public CDinventoryItem (String title, int itemNumber, int numberofUnits,
double unitPrice, String genre){
sPtitle = title;
iPitemNumber = itemNumber;
iPnumberofUnits = numberofUnits;
dPunitPrice = unitPrice;
genreCD = genre;
for(int i = 0; i < label.length; i++) {
label[i] = new JLabel();
}
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel1.add(label[0]);
Icon bug = new ImageIcon( getClass().getResource( "mylogo.JPG" ) );
label[0].setIcon( bug );
label[0].setPreferredSize(new Dimension(400, 150));
panel1.add(label[1]);
label[1].setText("Press button to choose option:");
label[1].setPreferredSize(new Dimension(400, 50));
panel1.add(panel2);
panel2.setPreferredSize(new Dimension(400, 50));
ButtonListerner inputNewCD = new ButtonListerner();
panel2.add(addCD);
addCD.addActionListener(inputNewCD);
ButtonListerner searchCD = new ButtonListerner();
panel2.add(search);
search.addActionListener(searchCD);
ButtonListerner display = new ButtonListerner();
panel2.add(displayCD);
displayCD.addActionListener(display);
setContentPane(panel1);
}
private class ButtonListerner implements ActionListener
{
public void actionPerformed ( ActionEvent event) {
if (event.getActionCommand().equals("Add CD"))
{
frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame2.setLocation(525,100);
frame2.setSize(425, 425);
frame2.setVisible( true );
frame2.add(panel3);
panel3.add(label[0]);
panel3.add(label[2]);
label[2].setText("Enter title of CD:");
label[2].setPreferredSize(new Dimension(100, 25));
JTextField titleText = new JTextField(20);
panel3.add (titleText);
sPtitle.equals(titleText);
label[2].setPreferredSize(new Dimension(175, 25));
panel3.add(label[3]);
label[3].setText("Enter number of CDs:");
JTextField numCDText = new JTextField(5);
panel3.add(numCDText);
label[3].setPreferredSize(new Dimension(275, 25));
panel3.add(label[4]);
label[4].setText("Enter price of CD:");
JTextField priceCDText = new JTextField(6);
panel3.add(priceCDText);
label[4].setPreferredSize(new Dimension(274, 25));
panel3.add(label[5]);
label[5].setText("Pick genre:");
String stringBox[] = {"Drama","Action","Comedy"};
JComboBox comboBox = new JComboBox(stringBox);
comboBox.setEditable(false);
panel3.add(comboBox);
panel3.add(save);
}
if (event.getActionCommand().equals("Search for CD")){
frame3.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame3.setLocation(100,525);
frame3.setSize(425, 425);
frame3.setVisible( true );
frame3.add(panel4);
panel4.add(label[0]);
panel4.add(label[6]);
label[6].setText("Enter name of CD you want to search for:");
JTextField searchName = new JTextField(20);
panel4.add(searchName);
panel4.add(label[7]);
label[7].setText("Or search by genre:");
JCheckBox checkB1 = new JCheckBox("Drama");
JCheckBox checkB2 = new JCheckBox("Action");
JCheckBox checkB3 = new JCheckBox("Comedy");
panel4.add(checkB1);
panel4.add(checkB2);
panel4.add(checkB3);
}
if (event.getActionCommand().equals("Display Inventory")){
frame4.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame4.setLocation(525,525);
frame4.setSize(425, 425);
frame4.setVisible( true );
frame4.add(panel5);
panel5.add(label[0]);
panel5.add(label[8]);
label[8].setText("List of CDs:");
}
if (event.getActionCommand().equals("Save")){
String dataFile = "inventory.dat";
try{
outFile = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(dataFile)));
}
catch(FileNotFoundException fileNotFoundException ){
}
}
}}
public int compareTo(CDinventoryItem otherItem) {
return this.sPtitle.compareTo(otherItem.getTitle());
}
#Override
public String getTitle() {
return sPtitle;
}
}
public class CDinventoryprogram {
public static void main(String[] args) {
JOptionPane.showMessageDialog( null, "Welcome to my CD inventory program!!"
, "Inventory", JOptionPane.INFORMATION_MESSAGE);
CDinventoryItem initem = new CDinventoryItem ("", 0, 0, 0.0,"" );
initem.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
initem.setLocation(100,100);
initem.setSize(425, 425);
initem.setVisible( true );
}
Sorry to be a nit-picker, but this:
class CDinventoryItem extends JFrame implements Comparable <CDinventoryItem>
has a "God" class anti-pattern design smell to it. You are asking it to be a CDinventoryItem, to hold a collection of CDinventoryItems, to display this collection of items in a GUI and to be the root container of that GUI, and now to output that information to disk. In other words you are asking this poor class to do too much.
Before even thinking about creating a GUI to display this information or writing code to output anything to a file, you need to seriously refactor it.
I recommend in the least you consider doing this:
1) Create a class CDInventoryItem that's Comparable, and has fields to hold this information -- String title, int itemNumber, int numberofUnits, double unitPrice, String genre -- and that's it.
2) Create another class for manipulating a collection of the above with an add method, a remove method, a listAll() method, a sort method, a search method, an int to refer to the current CDInventoryItem in the collection and a getter method to obtain it the current item, a method to get the next() and the previous() items, and to advance or decrement this int index,...
3) A class for IO support for reading and writing CDInventoryItems to and from a file, perhaps using Serialization (then CDInventoryItem should be serializable).
4) And then and only then should you start the GUI portion of your program. The GUI should use the classes above as its underlying logic.
If you do this, your coding will go along much more smoothly. If not, you may have a ton of horrendous debugging ahead of you.
In the method ButtonListerner.actionPerformed(), when the Add CD button is pressed (checked by event.getActionCommand().equals("Add CD")), you are creating a local text field:
JTextField titleText = new JTextField(20);
panel3.add (titleText);
sPtitle.equals(titleText);
label[2].setPreferredSize(new Dimension(175, 25));
panel3.add(label[3]);
label[3].setText("Enter number of CDs:");
JTextField numCDText = new JTextField(5);
panel3.add(numCDText);
label[3].setPreferredSize(new Dimension(275, 25));
...
The first thing you need to do is use the one in the outer class (so you can get the values later):
titleField = new JTextField(20);
panel3.add (titleField);
sPtitle.equals(titleField);
label[2].setPreferredSize(new Dimension(175, 25));
panel3.add(label[3]);
label[3].setText("Enter number of CDs:");
itemNField = new JTextField(5);
panel3.add(itemNField);
label[3].setPreferredSize(new Dimension(275, 25));
...
After this, when Save button is clicked, now your fields will hold the user input, so you can now get those values:
String title = titleField.getText();
...
Now to write to a file, you need to use an OutputStream. There are many OutputStream subclasses, each one has it's own use. BufferedWriter is for writing text, DataOutputStream is for writing binary data, you should not use both together like you are doing now. Assuming you want to write binary data, you can do this:
try {
outFile = new DataOutputStream(new FileOutputStream(dataFile));
outFile.writeUTF(titleField.getText());
// convert string to int
int itemN = Integer.parseInt(itemNField.getText());
outFile.writeInt(itemN);
outFile.flush();
outFile.close();
}
catch(IOException error) {
error.printStackTrace();
}
Note: To keep things simple, I didn't added proper error handling (the outFile.close() should be in a finally statement).

Categories

Resources