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).
Related
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.
eqn.setABC() takes in three integers, but CoeffA, CoeffB, and CoeffC are JTextFields.
How can I take the input from the JTextFields, convert it to ints, and feed it to eqn.setABC()?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FactorQuadraticUI extends JFrame implements ActionListener {
public JTextField coeffA;
public JTextField coeffB;
public JTextField coeffC;
public JTextField factors; //contains answer in form (px+q)(rx+s)
public JButton findFactors;
public QuadraticEqn eqn;
static final long serialVersionUID = 12345L;
public FactorQuadraticUI(QuadraticEqn e) {
super("Quadratic Equation Factor Finder");
eqn = e;
Container c = getContentPane();
c.setLayout(new FlowLayout());
JPanel eqnArea = new JPanel(new FlowLayout());
coeffA = new JTextField(2);
eqnArea.add(coeffA);
eqnArea.add(new JLabel("x^2 +"));
coeffB = new JTextField(2);
eqnArea.add(coeffB);
eqnArea.add(new JLabel("x +"));
coeffC = new JTextField(2);
eqnArea.add(coeffC);
//////////JTextField f1 = new JTextField("-5");
//control button: find factors
findFactors = new JButton("factor!");
findFactors.addActionListener(this);
eqnArea.add(findFactors);
c.add(eqnArea);
//output area
factors = new JTextField(27);
factors.setEditable(false);
c.add(factors);
this.setBounds(100, 100, 350, 100);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//"factor" button pressed
//how to get the values out
// and make them ints
eqn.setABC(coeffA, coeffB, coeffC);
factors.setText(eqn.toString() + " = " + eqn.getQuadraticFactors() );
factors.setText("testing...");
}
}
You can extract integers from JTextField using:
Integer.parseInt(jtextField.getText());
This command has two parts:
First part:
JTextField.getText() // This gets text from text field. Ofcourse replace "JTextField" with your textfield's name.
Second part:
Integer.parseInt(..) // This gets/parses the integer values in a string. We are inputting the string here from above step.
I was wondering if we are adding the same components to java (in the main class)over and over again and writing separate code for each of them, would it be possible to make the code smaller? e.g. if we are adding buttons and labels many times, which each do different job, would it it possible to have them in less code or does it have to be like that e.g.
JLabel label = new JLabel("Text1");
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
JTextField field = new JTextField();
panel.add(field);
JLabel label1 = new JLabel("Text2");
label1.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label1);
JTextField field1 = new JTextField();
panel.add(field1);
field1.setEnabled(false);
JLabel label2 = new JLabel("Text3");
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label2);
JTextField field2 = new JTextField();
panel.add(field2);
field2.setEnabled(false);
In my code I have to add the same components over and over again like 10 times but each one is doing a different job, would it be possible to have them in less code?
Also I want to be able to store the values of each textbox in a different variable, e.g. store the value of field1 to int number;.
Create a method that you can reuse:
private void method createLabel(JPanel panel, String text) {
JLabel label = new JLabel(text);
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
JTextField field = new JTextField();
panel.add(field);
}
If you need extra things like setEnabled() or whatever, just pass parameters in order to do it or not depending on requirements. If you need the Labels back just change void to JLabel and return it. Then you call it like this
createLabel(panel, "text1");
createLabel(panel, "text2");
...
1.Create ArrayList
2.Create method for adding JLabel to arraylist
3.Make it take a String name parameter
4.Profit???
"would it be possible to make the code smaller? "
Yes. One way, as #iberbue suggested is to use a method. You can have a method that return a JPanel and pass arguments to it
Have a look at this example I was working on for a different question. But it serves the same purpose. Look at the method createPanel that return a JPanel. Then I just use JPanel panel = createPanel(...);
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test2 {
Map<String, JTextField> fields;
Map<String, JLabel> labels;
public Test2() {
fields = new HashMap<>();
labels = new HashMap<>();
JPanel mainPanel = new JPanel(new GridLayout(10, 1));
for (int i = 1; i <= 10; i++) {
JPanel panel = createPanel("Text Field " + i);
mainPanel.add(panel);
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Test2();
}
});
}
private JPanel createPanel(String fieldName) {
JPanel panel = new JPanel();
JTextField field = new JTextField(15);
field.addActionListener(new FieldListener());
fields.put(fieldName, field);
JLabel label = new JLabel(fieldName);
label.addMouseListener(new MouseHandler());
labels.put(fieldName, label);
JButton button = new JButton(fieldName);
button.addActionListener(new ButtonListener());
panel.add(label);
panel.add(field);
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
String fieldName = button.getText();
JTextField field = fields.get(fieldName);
System.out.println(field.getText());
}
}
public class FieldListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JTextField field = (JTextField)e.getSource();
System.out.println(field.getText());
}
}
public class MouseHandler extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
System.out.println(label.getText());
}
}
}
You can write a method, something like this.
private void add(JPanel panel, int i, boolean enabled){
JLabel label = new JLabel("Text" + i);
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
JTextField field = new JTextField();
panel.add(field);
field.setEnabled(enabled);
}
And then you call it 3 times as needed.
You've noticed that most code is repeated. This is a good first step.
Then, notice what parts change (semantically) between iterations (that is, ignore the different variable names and other unimportant info): new JLabel(theLabelThatChanges)and .setEnabled(thisFieldEnabled).
Then, put all these in a loop:
for(int i = 0; i < 10; i++)
{
JLabel label2 = new JLabel(theLabelThatChanges);
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label2);
JTextField field2 = new JTextField();
panel.add(field2);
field1.setEnabled(thisFieldEnabled);
}
Make sure have a collection of values for the thing that changes:
String[] labels = new String[] { "Text1", "Text2", "Text3" };
boolean[] enabledBoxes = new boolean { true, false, true };
Be sure to grab a value in each iteration:
String theLabelThatChanges = labels[i];
boolean thisFieldEnabled = enabledBoxes[i];
Final code:
String[] labels = new String[] { "Text1", "Text2", "Text3" };
boolean[] enabledBoxes = new boolean { true, false, true };
for(int i = 0; i < 3; i++)
{
String theLabelThatChanges = labels[i];
boolean thisFieldEnabled = enabledBoxes[i];
JLabel label2 = new JLabel(theLabelThatChanges);
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label2);
JTextField field2 = new JTextField();
panel.add(field2);
field1.setEnabled(thisFieldEnabled);
}
As others have commented, you could then take the part that creates all this stuff and make it a separate procedure that takes the label and the enabled status as parameters:
private void addControls(String theLabelThatChanges, boolean thisFieldEnabled)
{
JLabel label2 = new JLabel(theLabelThatChanges);
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label2);
JTextField field2 = new JTextField();
panel.add(field2);
field1.setEnabled(thisFieldEnabled);
}
Then call it from the loop:
for(int i = 0; i < 3; i++)
{
addControls(labels[i], enabledBoxes[i]);
}
Complexer answer.
If you want to be OO.
Make class CustomJButton extends JButton
Set Everything you need in the contructor
You will be able to do this if you're not going to use the Button vars anymore
new CustomJButton("NAME");
You will be able to do this if you're going to use the Button vars
CustomJButton j = new CustomJButton("NAME");
I thought there already should be some fluent swing GUI API, but I did not find any on the spur. JavaFX GUI on Java 8 is nice.
Though Java 8 allows terse event listeners with Java 7 one can do a fluent API too.
JPanel panel = new FrameBuilder().panel()
.children()
.label("Text1")
.setHorizontalAlignment(SwingConstants.CENTER)
.textField()
.setId("field1")
.label("Text2")
.setHorizontalAlignment(SwingConstants.CENTER)
.textField()
.setId("field2")
.setEnabled(false)
.endChildren()
.create();
Where FrameBuilder.panel gives a PanelBuilder whose create returns the JPanel. Or so.
I haven't used comboBox much in java before and I'm having a bit of trouble getting my textfile to appear. I believe I have the files load correctly but it seems like I'm finding difficult to implement it in the code. I do have multiple movie names in the textfile. and when selecting a different movie in the combo box it changes the price,rating etc...
I did this correctly once using an initialize array.
example of the textfile[Taken,PG-13,8:00Am, 7,50
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
import javax.swing.*;
public class MovieSelection extends JFrame {
private JPanel ratingPanel;
private JPanel panel;
private JLabel priceLabel;
private JLabel label;
private JButton addCart;
private JButton backButton;
private JButton resetButton;
private JTextField selectedRatingPanel;
private JTextField amountTextField;
private JComboBox movieBox;
private ArrayList<String> movieName;
private ArrayList<String> movieRating;
private ArrayList<String> movieTime;
private ArrayList<String> moviePrice;
public MovieSelection() {
super("Please select your movie");
setSize(575,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
buildMoviePanel();
buildRatingPanel();
add(panel);
setVisible(true);
movieName = new ArrayList<>();
movieRating = new ArrayList<>();
movieTime = new ArrayList<>();
moviePrice = new ArrayList<>();
}
private void readMovies() {
Scanner input=null;
try{
input = new Scanner(new File("TheMovies.txt"));
while(input.hasNext()){
String str = input.nextLine();
StringTokenizer strT = new StringTokenizer(str, ",");
movieName.add(strT.nextToken());
movieRating.add(strT.nextToken());
moviePrice.add(strT.nextToken());
movieTime.add(strT.nextToken());
}
}
catch(Exception element){
input.close();
JOptionPane.showMessageDialog(null, "Error");
}
}
private void buildMoviePanel() {
panel = new JPanel();
priceLabel = new JLabel("Cost:");
backButton = new JButton("Back");
resetButton = new JButton("Rest");
backButton.addActionListener(new BackButton());
resetButton.addActionListener(new ResetButton());
addCart = new JButton("Add to cart");
JTextField totalTextField = new JTextField(10);
JTextField priceTextField = new JTextField(5);
JTextField amountTextField = new JTextField(4);
priceTextField.setEditable(false);
priceTextField.setText(moviePrice);
totalTextField.setEditable(false);
JComboBox movieLists = new JComboBox(movieName);
movieLists.setSelectedIndex(0);
movieLists.addActionListener(new MovieLists());
panel.add(movieLists).setBounds(20,52,80,40);
panel.add(priceLabel).setBounds(375,0,80,40);
panel.add(priceTextField).setBounds(375,52,75,40);
panel.add(backButton).setBounds(20,310,80,40);
panel.add(addCart).setBounds(380,310,100,40);
panel.add(resetButton).setBounds(200, 310, 80, 40);
panel.add(amountTextField);
panel.setLayout(null);
}//buildPanel
private void buildRatingPanel(){
ratingPanel = new JPanel();
label = new JLabel("Rating:");
selectedRatingPanel = new JTextField(9);
selectedRatingPanel.setEditable(false);
selectedRatingPanel.setText("R");
panel.add(label).setBounds(245, 0, 100,40);
panel.add(selectedRatingPanel).setBounds(245,52,100,40);
}
private class MovieLists implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String theMovie = (String) cb.getSelectedItem();
System.out.println(cb.getSelectedIndex());
}
}
private class BackButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// return back to home page
if (e.getSource() == backButton)
new SelectUserWindow();
setVisible(false);
}
}
private class ResetButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// return back to home page
if (e.getSource() == resetButton);
}
}
}
Learn to use layout managers
JComboBox does not take an ArrayList (or Collection) as a viable parameter (it can take Object[] or Vector)
movieName, movieRating, movieTime, moviePrice are all uninitialised when you create the UI because you initialise them AFTER the creation of the UI.
JTextField#setText does not take an ArrayList as a viable parameter
Learn to read the output of your application from the console or IDE
Learn to use a debugger - it will save you many hours of frustration and annoyance ;)
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.