I'm trying to debug my program for homework, but I can't even do that because I don't know why my buttons aren't working.
Any help is appreciated, thanks! (I know that my findnext is screwy for now, but I didn't know what else to do so I'm just debugging it for now)
public class Window extends JFrame implements ActionListener {
private JButton findnext;
private JButton replace;
private JButton delete;
private JButton upper;
private JTextField from,to;
private JTextArea textArea;
final static Color found = Color.PINK;
final Highlighter hilit;
final Highlighter.HighlightPainter painter;
public Window() {
setTitle("Project 8");
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setSize((d.width/4)*3,d.height);
textArea = new JTextArea ("The apple ate the apple.",8,40);
textArea.setLineWrap(true);
Container contentPane = getContentPane();
addWindowListener(new Close());
contentPane.add(textArea);
JPanel panel = new JPanel();
JButton findnext = new JButton("FindNext");
panel.add(findnext);
from = new JTextField(8);
panel.add(from);
findnext.addActionListener(this);
JButton replace = new JButton("Replace");
panel.add(replace);
to = new JTextField(8);
panel.add(to);
findnext.addActionListener(this);
JButton delete = new JButton("Delete");
panel.add(delete);
findnext.addActionListener(this);
JButton upper = new JButton("Upper");
panel.add(upper);
findnext.addActionListener(this);
contentPane.add(panel, "South");
hilit = new DefaultHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(found);
textArea.setHighlighter(hilit);
}
public void actionPerformed(ActionEvent evt) {
String f = from.getText();
String t = to.getText();
int n = textArea.getText().indexOf(f);
Object source = evt.getSource();
if (source == findnext) {
hilit.removeAllHighlights();
String text = textArea.getText();
int index = text.indexOf(f,0);
if (index>0) {
try {
hilit.addHighlight(index, index+f.length(), DefaultHighlighter.DefaultPainter);
}
catch (BadLocationException e) {
;
}
}else if (source == replace) {
if (n>=0 && f.length() > 0) {
textArea.replaceRange(to.getText(),n,n+f.length());
;
}else if (source == delete) {
textArea.setText(" ");
}else if (source == upper) {
f.toUpperCase() ;
}
}
}
}
}
You have a shadowing problem. You declare...
private JButton findnext;
private JButton replace;
private JButton delete;
private JButton upper;
But in your constructor you do...
JButton findnext = new JButton("FindNext");
//...
JButton replace = new JButton("Replace");
//...
JButton delete = new JButton("Delete");
//...
JButton upper = new JButton("Upper");
Which is re-declaring those variables.
This means that when you try and do...
if (source == findnext) {
It's always false
You're also adding the ActionListener (this) to the findnext button four times...I think you mean to be adding it to each of the other buttons
Beware, there is already a class called Window in AWT, which could cause confusion for people. It's also discouraged to extend directly from a top level container like JFrame and instead should start with a JPanel and the add it to an instance of JFrame (or what ever container you like)
try this:
in ur constructor update this lines:
JButton findnext = new JButton("FindNext");
//
JButton replace = new JButton("Replace");
//
JButton delete = new JButton("Delete");
//
JButton upper = new JButton("Upper");
use this one:
findnext = new JButton("FindNext");
//
replace = new JButton("Replace");
//
delete = new JButton("Delete");
//
upper = new JButton("Upper");
Related
I am not sure what I am doing wrong. I am trying to create 4 buttons using the arrays and passing the method to the Set Panel class. When I run it I only get one button. Any help would be great. Essentially what I want is a Panel with four buttons, through the use of Methods.
public class SetButtons extends JButton implements ActionListener {
JButton [] buttonArray = new JButton[4];
JButton exitBtn, newGameBtn, checkBtn, clearBtn;
Font myFont = new Font("ink free", Font.BOLD,22);
public SetButtons(){
this.exitBtn = new JButton("Exit");
this.newGameBtn = new JButton("New Game");
this.checkBtn = new JButton("Check Answer");
this.clearBtn = new JButton("Clear");
this.buttonArray[0] = exitBtn;
this.buttonArray[1] = newGameBtn;
this.buttonArray[2] = checkBtn;
this.buttonArray[3] = clearBtn;
for (int i = 0; i < 4; i++){
this.buttonArray[i].addActionListener(this);
this.buttonArray[i].setFont(myFont);
this.buttonArray[i].setFocusable(false);
this.buttonArray[i].setLayout(new FlowLayout());
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this){
System.exit(0);
}
}
}
import javax.swing.*;
import java.awt.*;
public class SetPanel extends JPanel {
Font myFont = new Font("ink free", Font.BOLD,22);
SetLabels labels;
SetButtons exitButton;
SetPanel(){
SetButtons btn = new SetButtons();
this.add(btn);
this.setBackground(Color.darkGray);
this.setLayout(new FlowLayout());
}
}
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.
I am trying to retrieve the information from a TextArea which has been defined as follows
JTextArea a1 = new JTextArea(15, 50);
a1.setEditable(true);
centerPanel.add(a1);
a1.setVisible(true);
and in my listener class
private class JobHandler implements ActionListener {
boolean c2shortHand = false;
boolean c1translation = false;
boolean c3onsite = false;
String custName = "";
String jobInfo ="";
String line = "";
public void actionPerformed(ActionEvent e) {
jobInfo=a1.getText();
if (c1.isSelected()) {
c1translation = true;
}
if (c2.isSelected()) {
c2shortHand = true;
}
if (c3.isSelected()) {
c3onsite = true;
}jobInfo=a1.getText();
}
}
When i run the GUI it is fine until i added the last part, where i am trying to assign the TextArea information to a String variable called jobInfo
The Error i get is, which seems to be complaining about threading. Is the problem the fact that i am trying to retrieve the information without doing something else first?
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at JobsGUI$JobHandler.actionPerformed(JobsGUI.java:202)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
The declaration of a1
public class JobsGUI {
private Manager mmm = new Branch("Watford");
private JFrame myFrame = new JFrame("Jobs GUI");
private Container contentPane = myFrame.getContentPane();
private JButton quitButton = new JButton("Quit");
private JButton addJobButton = new JButton("Add Job");
private JButton clearListButton = new JButton("Clear List");
private JPanel eastPanel = new JPanel();
private JPanel westPanel = new JPanel();
private JPanel centerPanel = new JPanel();
private JPanel northPanel = new JPanel();
private JPanel southPanel = new JPanel();
JCheckBox c1, c2, c3;
JTextField t1, t2, t3;
JLabel l1, l2;
JTextArea a1;
JScrollPane s1;
public JobsGUI() {
addAllStaff();
makeFrame();
makeMenus(myFrame);
makeTypes();
addJobs();
}
private void addJobs() {
t1 = new JTextField(10); //Customer name
northPanel.add(t1);
l1 = new JLabel("Enter Customer name here");
northPanel.add(l1);
c1 = new JCheckBox("Translation");
westPanel.add(c1);
c2 = new JCheckBox("ShortHand?");
westPanel.add(c2);
c3 = new JCheckBox("OnSite");
westPanel.add(c3);
JLabel l2 = new JLabel("Job Information");
centerPanel.add(l2);
l2.setVisible(true);
JTextArea a1 = new JTextArea(15, 50);
a1.setEditable(true);
centerPanel.add(a1);
a1.setVisible(true);
addJobButton.addActionListener(new JobHandler());
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class filecabinet extends JFrame implements ActionListener {
private String folder = "";
//create buttons
private JButton a = new JButton("A");
private JButton b = new JButton("B");
private JButton c = new JButton("C");
private JButton d = new JButton("D");
private JButton e = new JButton("E");
private JButton f = new JButton("F");
private JButton g = new JButton("G");
private JButton h = new JButton("H");
private JButton i = new JButton("I");
private JButton j = new JButton("J");
private JButton k = new JButton("K");
private JButton l = new JButton("L");
private JButton m = new JButton("M");
private JButton n = new JButton("N");
private JButton o = new JButton("O");
private JButton p = new JButton("P");
private JButton q = new JButton("Q");
private JButton r = new JButton("R");
private JButton s = new JButton("S");
private JButton t = new JButton("T");
private JButton u = new JButton("U");
private JButton v = new JButton("V");
private JButton w = new JButton("W");
private JButton x = new JButton("X");
private JButton y = new JButton("Y");
private JButton z = new JButton("Z");
//create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane(){
//set buttons to panels
aF.add(a);
aF.add(b);
aF.add(c);
aF.add(d);
aF.add(e);
aF.add(f);
//set layout of panels
aF.setLayout(new GridLayout(2,3));
gL.add(g);
gL.add(h);
gL.add(i);
gL.add(j);
gL.add(k);
gL.add(l);
gL.setLayout(new GridLayout(2,3));
mR.add(m);
mR.add(n);
mR.add(o);
mR.add(p);
mR.add(q);
mR.add(r);
mR.setLayout(new GridLayout(2,3));
sX.add(s);
sX.add(t);
sX.add(u);
sX.add(v);
sX.add(w);
sX.add(x);
sX.setLayout(new GridLayout(2,3));
yZ.add(y);
yZ.add(z);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2,3));
}
public filecabinet(){
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5,1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
addActionListener();
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
}
public void addActionListener(){
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
f.addActionListener(this);
g.addActionListener(this);
h.addActionListener(this);
i.addActionListener(this);
j.addActionListener(this);
k.addActionListener(this);
l.addActionListener(this);
m.addActionListener(this);
n.addActionListener(this);
o.addActionListener(this);
p.addActionListener(this);
q.addActionListener(this);
r.addActionListener(this);
s.addActionListener(this);
t.addActionListener(this);
u.addActionListener(this);
v.addActionListener(this);
w.addActionListener(this);
x.addActionListener(this);
y.addActionListener(this);
z.addActionListener(this);
}
public static void main(String[]args){
filecabinet frame = new filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
}
I would prefer not to have to write out a listener for every button
and I was wandering if I could just get the text contained in the button.
such as "You have selected foler X", X is the button chosen.
Again, either use arrays and/or a for loop to consolidate your code getting rid of code redundancy. For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class FileCabinet2 extends JPanel {
public static final char FIRST_LETTER = 'A';
public static final char LAST_LETTER = 'Z';
private static final float lARGE_FONT_POINTS = 32f;
private static final int GRID_COLS = 3;
private JLabel chosenLabel = new JLabel();
public FileCabinet2() {
JPanel letterPanel = new JPanel(new GridLayout(0, GRID_COLS));
ActionListener btnListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
chosenLabel.setText(evt.getActionCommand());
}
};
for (char c = FIRST_LETTER; c <= LAST_LETTER; c++) {
String buttonTitle = String.valueOf(c);
JButton button = new JButton(buttonTitle);
setFontPoints(button, lARGE_FONT_POINTS);
letterPanel.add(button);
button.addActionListener(btnListener);
}
JLabel selectionLabel = new JLabel("Selection: ", SwingConstants.RIGHT);
setFontPoints(selectionLabel, lARGE_FONT_POINTS);
setFontPoints(chosenLabel, lARGE_FONT_POINTS);
JPanel bottomPanel = new JPanel(new GridLayout(1, 0));
bottomPanel.add(selectionLabel);
bottomPanel.add(chosenLabel);
bottomPanel.setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
add(letterPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private void setFontPoints(JComponent jComp, float points) {
jComp.setFont(jComp.getFont().deriveFont(points));
}
private static void createAndShowGui() {
FileCabinet2 mainPanel = new FileCabinet2();
JFrame frame = new JFrame("File Cabinet");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Now if you want to change how many button columns there are, all you need to do is change one constant, GRID_COLS, and the same for the size of the font, just change LARGE_FONT_POINTS.
For this:
would prefer not to have to write out a listener for every button
Create a method that accept the JPanel as the parameter and then iterate to each component in JPanel, add the action listener if the component is JButton
This one:
I was wandering if I could just get the text contained in the button.
Just set the value in the JLabel. You already get the button content right?
So, the full code is:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class filecabinet extends JFrame implements ActionListener {
private String folder = "";
// create buttons
private JButton a = new JButton("A");
private JButton b = new JButton("B");
private JButton c = new JButton("C");
private JButton d = new JButton("D");
private JButton e = new JButton("E");
private JButton f = new JButton("F");
private JButton g = new JButton("G");
private JButton h = new JButton("H");
private JButton i = new JButton("I");
private JButton j = new JButton("J");
private JButton k = new JButton("K");
private JButton l = new JButton("L");
private JButton m = new JButton("M");
private JButton n = new JButton("N");
private JButton o = new JButton("O");
private JButton p = new JButton("P");
private JButton q = new JButton("Q");
private JButton r = new JButton("R");
private JButton s = new JButton("S");
private JButton t = new JButton("T");
private JButton u = new JButton("U");
private JButton v = new JButton("V");
private JButton w = new JButton("W");
private JButton x = new JButton("X");
private JButton y = new JButton("Y");
private JButton z = new JButton("Z");
// create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane() {
// set buttons to panels
aF.add(a);
aF.add(b);
aF.add(c);
aF.add(d);
aF.add(e);
aF.add(f);
// set layout of panels
aF.setLayout(new GridLayout(2, 3));
gL.add(g);
gL.add(h);
gL.add(i);
gL.add(j);
gL.add(k);
gL.add(l);
gL.setLayout(new GridLayout(2, 3));
mR.add(m);
mR.add(n);
mR.add(o);
mR.add(p);
mR.add(q);
mR.add(r);
mR.setLayout(new GridLayout(2, 3));
sX.add(s);
sX.add(t);
sX.add(u);
sX.add(v);
sX.add(w);
sX.add(x);
sX.setLayout(new GridLayout(2, 3));
yZ.add(y);
yZ.add(z);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2, 3));
}
public filecabinet() {
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
addActionListener(aF);
addActionListener(gL);
addActionListener(mR);
addActionListener(sX);
addActionListener(yZ);
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
// set the label with folder value
notify.setText("You have selected folder " + folder);
}
// Attach event handler to each JButton in JPanel
public void addActionListener(JPanel panel) {
Component[] components = panel.getComponents();
for (Component component : components) {
if (component instanceof JButton) {
((JButton) component).addActionListener(this);
}
}
}
public static void main(String[] args) {
filecabinet frame = new filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
}
A quick review of your code, brought your code down to this length.
Imagine, what you can achieve if you give it a bit more insight.
Furthermore, when you see that in your code, you are repeating some
lines again and again for the same thingy, you can indeed think of a
pattern that can accomplish that for you in a rightful manner, with
fewer keystrokes.
Try this modified code of yours :-)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class Filecabinet extends JFrame implements ActionListener {
private String folder = "";
//create buttons
private JButton[] button = new JButton[26];
//create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane(){
init_Buttons(button);
//set buttons to panels
for (int i = 0; i < 6; i++)
aF.add(button[i]);
//set layout of panels
aF.setLayout(new GridLayout(2,3));
for (int i = 6; i < 12; i++)
gL.add(button[i]);
gL.setLayout(new GridLayout(2,3));
for (int i = 12; i < 18; i++)
mR.add(button[i]);
mR.setLayout(new GridLayout(2,3));
for (int i = 18; i < 24; i++)
sX.add(button[i]);
sX.setLayout(new GridLayout(2,3));
for (int i = 24; i < 26; i++)
yZ.add(button[i]);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2,3));
}
private void init_Buttons(JButton[] button)
{
int value = 65;
for (int i = 0; i < button.length; i++)
{
button[i] = new JButton(Character.toString((char) value++));
button[i].addActionListener(this);
}
}
public Filecabinet(){
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5,1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
notify.setText(folder);
}
public static void main(String[]args){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
Filecabinet frame = new Filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
//frame.setSize(WIDTH, HEIGHT);
frame.pack();
frame.setVisible(true);
}
});
}
}
You can subclass JButton and write a constructor for the subclass that takes in as a parameter a reference to the action listener, your JFrame.
For instance, your subclass could simply be:
public class YourButton extends JButton {
public YourButton(String title, ActionListener listener) {
super(title);
this.addActionListener(listener);
}
}
So instead of:
private JButton a = new JButton("A");
You would call:
private YourButton a = new YourButton("A", this);
Additionally, as others have suggested, your actionPerformed(ActionEvent e) method requires you to update your notify JLabel instance to reflect the selected button's title.
Hope that helps!
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.