I have a problem with a JList. When I select an item, it resizes itself. How can I set the JList to a fixed size?
Here is a screenshot before I selected anything
and this is after
Here is my code:
public class AgendaView extends JFrame {
private JLabel firstNameLabel, lastNameLabel, adressLabel, phoneNumberLabel, extraInfoLabel;
private Button editButton, addButton, deleteButton, showButton;
private JPanel labels, gui, buttons;
private DefaultListModel model;
private JList list;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem newItem, saveItem, saveAsItem, exitItem, openItem;
private Agenda agenda;
private JScrollPane scrollPane;
public AgendaView() {
super("***Agenda View***");
menuBar = new JMenuBar();
menu = new JMenu("Menu");
menu.add(new JSeparator());
newItem = new JMenuItem("New");
saveItem = new JMenuItem("Save");
saveItem.setEnabled(false);
saveAsItem = new JMenuItem("Save as..");
saveAsItem.setEnabled(false);
exitItem = new JMenuItem("Exit");
openItem = new JMenuItem("Open");
saveItem.add(new JSeparator());
exitItem.add(new JSeparator());
menu.add(newItem);
menu.add(openItem);
menu.add(saveItem);
menu.add(saveAsItem);
menu.add(exitItem);
gui = new JPanel(new BorderLayout(2, 2));
gui.setBorder(new TitledBorder("Owner"));
labels = new JPanel(new GridLayout(0, 1, 1, 1));
labels.setBorder(new TitledBorder("Contact "));
buttons = new JPanel(new GridLayout(1, 0, 1, 1));
editButton = new Button("Edit");
addButton = new Button("Add");
deleteButton = new Button("Delete");
showButton = new Button("Show");
editButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
showButton.setEnabled(false);
buttons.add(showButton);
buttons.add(editButton);
buttons.add(addButton);
buttons.add(deleteButton);
firstNameLabel = new JLabel("First name: ");
lastNameLabel = new JLabel("Last name: ");
adressLabel = new JLabel("Adress: ");
phoneNumberLabel = new JLabel("Phone number: ");
extraInfoLabel = new JLabel("Extra info: ");
labels.add(firstNameLabel);
labels.add(lastNameLabel);
labels.add(adressLabel);
labels.add(phoneNumberLabel);
labels.add(extraInfoLabel);
model = new DefaultListModel();
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setVisibleRowCount(-1);
list.addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
String name = list.getSelectedValue().toString();
String[] split = name.split(" ");
Contact contact = agenda.searchContactbyName(split[0], split[1]);
firstNameLabel.setText("First name: " + contact.getFirstName());
lastNameLabel.setText("Last name: " + contact.getLastName());
adressLabel.setText("Adress: " + contact.getAdress());
phoneNumberLabel.setText("Phone number: " + contact.getPhoneNumber());
if (contact.getType().compareTo("Acquaintance") == 0) {
extraInfoLabel.setText("Occupation: " + contact.getExtraInfo());
} else if (contact.getType().compareTo("Colleague") == 0) {
extraInfoLabel.setText("Email: " + contact.getExtraInfo());
} else if (contact.getType().compareTo("Friend") == 0) {
extraInfoLabel.setText("Birthdate: " + contact.getExtraInfo());
} else {
extraInfoLabel.setVisible(false);
}
}
});
scrollPane = new JScrollPane(list);
gui.add(labels, BorderLayout.CENTER);
gui.add(scrollPane, BorderLayout.WEST);
gui.add(buttons, BorderLayout.SOUTH);
add(gui);
menuBar.add(menu);
setJMenuBar(menuBar);
Here is where I display the GUI:
public class JavaLab3_pb1Java {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
Agenda agenda = new Agenda();
AgendaView agendaView = new AgendaView();
agendaView.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
agendaView.setSize(500, 300);
agendaView.pack();
agendaView.setVisible(true);
}
}
You need to call pack() on your JFrame after adding all components and before calling setVisible(true) on it. This will tell the GUI's layout managers to manage their layouts, and will resize the GUI to the preferred size as specified by the components and the layouts.
Edit
Never call setSize(...) on anything. Better to override getPreferredSize(). For example, my sscce:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class AgendaView extends JFrame {
private static final int PREF_W = 500;
private static final int PREF_H = 300;
private JLabel firstNameLabel, lastNameLabel, adressLabel, phoneNumberLabel,
extraInfoLabel;
private JButton editButton, addButton, deleteButton, showButton;
private JPanel labels, gui, buttons;
private DefaultListModel<String> model;
private JList<String> list;
private JScrollPane scrollPane;
public AgendaView() {
super("***Agenda View***");
gui = new JPanel(new BorderLayout(2, 2));
gui.setBorder(new TitledBorder("Owner"));
labels = new JPanel(new GridLayout(0, 1, 1, 1));
labels.setBorder(new TitledBorder("Contact "));
buttons = new JPanel(new GridLayout(1, 0, 1, 1));
editButton = new JButton("Edit");
addButton = new JButton("Add");
deleteButton = new JButton("Delete");
showButton = new JButton("Show");
editButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
showButton.setEnabled(false);
buttons.add(showButton);
buttons.add(editButton);
buttons.add(addButton);
buttons.add(deleteButton);
firstNameLabel = new JLabel("First name: ");
lastNameLabel = new JLabel("Last name: ");
adressLabel = new JLabel("Adress: ");
phoneNumberLabel = new JLabel("Phone number: ");
extraInfoLabel = new JLabel("Extra info: ");
labels.add(firstNameLabel);
labels.add(lastNameLabel);
labels.add(adressLabel);
labels.add(phoneNumberLabel);
labels.add(extraInfoLabel);
model = new DefaultListModel<String>();
list = new JList<String>(model);
String[] eles = { "Ciprian Aftode", "Andrei Batinas", "Bogdan Fichitiu",
"Valentin Pascau" };
for (String ele : eles) {
model.addElement(ele);
}
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// list.setVisibleRowCount(-1);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
firstNameLabel.setText("First name: first name");
lastNameLabel.setText("Last name: last name");
adressLabel.setText("Address: Address");
phoneNumberLabel.setText("Phone number: PhoneNumber");
extraInfoLabel.setText("Occupation: ExtraInfo");
}
});
int ebGap = 8;
list.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
scrollPane = new JScrollPane(list);
gui.add(labels, BorderLayout.CENTER);
gui.add(scrollPane, BorderLayout.WEST);
gui.add(buttons, BorderLayout.SOUTH);
add(gui);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
AgendaView frame = new AgendaView();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Related
how do you get the User input inside JTextFeild and SET/ADD the input to the table in another frame? Student objects are stored in an ArrayList. The array list is added to table view and displayed in another frame. StudentCntl, StudentListUI, StudentUI are shown below. StudentListUI(left) StudentUI(right)
public class StudentCntl {
private static final int STARTING_INDEX_OF_DISPLAY = 0;
StudentCntl studentCntl;
StudentList studentList;
StudentUI studentUI;
StudentListUI studentListUI;
StudentTableModel theStudentTable;
public StudentCntl() {
studentList = new StudentList();
theStudentTable = new StudentTableModel(studentList.getStudentList());
studentUI = new StudentUI(this, STARTING_INDEX_OF_DISPLAY);
studentUI.setVisible(true);
studentListUI = new StudentListUI(this, studentUI);
studentListUI.setVisible(true);
}
public StudentTableModel getStudentTableModel() {
return theStudentTable;
}
Student getStudent(int index) {
Student student = studentList.getStudentList().get(index);
return student;
}
public class StudentUI extends JFrame {
private int indexOfElementToDisplay;
private final JTextField firstNameDisplayValue = new JTextField(15);
private final JTextField lastNameDisplayValue = new JTextField(15);
private final JTextField gpaDisplayValue = new JTextField(15);
private JPanel studentPanel;
private JPanel buttonPanel;
String[] info = {firstNameDisplayValue.getText(),lastNameDisplayValue.getText(),gpaDisplayValue.getText()};
private final StudentCntl studentCntl;
public StudentUI(StudentCntl studentCntl, int startingIndexOfDisplay) {
this.studentCntl = studentCntl;
indexOfElementToDisplay = startingIndexOfDisplay;
initComponents();
setFieldView();
}
private void initComponents() {
setTitle("Student Viewer");
setSize(500, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
studentPanel = new JPanel(new GridLayout(5, 1));
studentPanel.add(new JLabel("First Name"));
studentPanel.add(firstNameDisplayValue);
studentPanel.add(new JLabel("Last Name"));
studentPanel.add(lastNameDisplayValue);
studentPanel.add(new JLabel("GPA"));
studentPanel.add(gpaDisplayValue);
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton nextButton = new JButton("Next");
JButton previousButton = new JButton("Previous");
JButton deleteButton = new JButton("Delete");
JButton newButton = new JButton("New Entry");
JButton saveButton = new JButton("Save");
nextButton.addActionListener(e -> showNext(indexOfElementToDisplay));
buttonPanel.add(nextButton);
previousButton.addActionListener(e -> showPrevious(indexOfElementToDisplay));
buttonPanel.add(previousButton);
deleteButton.addActionListener(e -> showDelete(indexOfElementToDisplay));
buttonPanel.add(deleteButton);
saveButton.addActionListener(e -> addToList(info));
buttonPanel.add(saveButton);
newButton.addActionListener(e -> showNew());
buttonPanel.add(newButton);
setContentPane(new JPanel(new BorderLayout()));
getContentPane().add(studentPanel, BorderLayout.CENTER);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
private void setFieldView() {
firstNameDisplayValue.setText(studentCntl.getStudent(indexOfElementToDisplay).getFirstName());
lastNameDisplayValue.setText(studentCntl.getStudent(indexOfElementToDisplay).getLastName());
gpaDisplayValue.setText(Double.toString(studentCntl.getStudent(indexOfElementToDisplay).getGpa()));
}
private void NewEntryView() {
firstNameDisplayValue.setText(" ");
lastNameDisplayValue.setText(" ");
gpaDisplayValue.setText(" ");
}
private void addToList(String[] info){
studentCntl.studentList.getStudentList().add(new Student(info));
}
private void showNew() {
NewEntryView();
}
void refreshDisplayWithNewValues(int index) {
setFieldView();
this.repaint();
}
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
How can I set a button to link to a completely different grid pane? If I click the JButton "More options" for example, I want it to link me to a new page with more JButton options. Right now, everything is static.
The program right now just calculates the area of a rectangle given an length and width when you press "Calculate." The grid layout is 4 x 2, denoted by JLabel, JTextField, and JButton listed below.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private JButton calculateB, exitB;
//Button handlers:
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public RectangleProgram()
{
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
//SPecify handlers for each button and add (register) ActionListeners to each button.
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Sample Title: Area of a Rectangle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}
}
You can use CardLayout. It allows the two or more components share the same display space.
Here is a simple example
public class RectangleProgram {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Area of a Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField lengthField = new JTextField(10);
JTextField widthField = new JTextField(10);
JTextField areaField = new JTextField(10);
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
final JPanel content = new JPanel(new CardLayout());
JButton optionsButton = new JButton("More Options");
optionsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) content.getLayout();
cardLayout.next(content);
}
});
JPanel panel = new JPanel(new GridLayout(0, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
};
panel.add(new JLabel("Enter the length: ", JLabel.RIGHT));
panel.add(lengthField);
panel.add(new JLabel("Enter the width: ", JLabel.RIGHT));
panel.add(widthField);
panel.add(new JLabel("Area: ", JLabel.RIGHT));
panel.add(areaField);
panel.add(calculateButton);
panel.add(exitButton);
JPanel optionsPanel = new JPanel();
optionsPanel.add(new JLabel("Options", JLabel.CENTER));
content.add(panel, "Card1");
content.add(optionsPanel, "Card2");
frame.add(content);
frame.add(optionsButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
Read How to Use CardLayout
I have been googling an sherthing for an solution to this problem a lot but can't find any answer how to fix this. My problem is that when i start a new jframe from an actionevent from pressing a button the class white the JFrame opens but then the programs starts to freeze and the pop up windows stays blank.
Her is the cod i apologize if there is some bad programing or some words in swedish:
The start upp class:
import java.util.ArrayList;
public class maineClassen {
ArrayList<infoClass> Infon = new ArrayList<>();
public static void main (String [] args)
{
referenser referens = new referenser();
Startskärmen ss = new Startskärmen(referens);
}
}
The "startskärm" the first screen to com to:
public class Startskärmen extends JFrame implements ActionListener {
referenser referens;
ArrayList<infoClass> Infon;
JButton öppna = new JButton("open");
JButton ny = new JButton("create new");
JButton radera = new JButton("erase");
JScrollPane pane = new JScrollPane();
DefaultListModel mod = new DefaultListModel();
JList list = new JList(mod);
JScrollPane sp = new JScrollPane(list);
JLabel texten = new JLabel("pre-alpha 0.1");
public Startskärmen(referenser re)
{
//references should be sent by itself or received
referens = re;
Infon = referens.getInfoReferens();
//build up the window
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.LINE_AXIS));
labelPanel.setBorder(BorderFactory.createEmptyBorder(10,10,0,10));
labelPanel.add(texten);
JPanel scrollPanel = new JPanel();
scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.LINE_AXIS));
scrollPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
scrollPanel.add(sp);// man kan ocksä sätta in --> pane <--
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(öppna);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(ny);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(radera);
Container contentPane = getContentPane();
contentPane.add(labelPanel,BorderLayout.NORTH);
contentPane.add(scrollPanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setSize(500, 500);
//adda action listener
ny.addActionListener(this);
öppna.addActionListener(this);
radera.addActionListener(this);
//skapaNyIC();
}
infoClass hh;
public void skapaNyIC()
{
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ny)
{
skapaNyIC();
}
else if(e.getSource() == öppna)
{
JOptionPane.showMessageDialog(texten,"This function doesn't exist yet");
}
else if(e.getSource() == radera)
{
JOptionPane.showMessageDialog(texten, "This function doesn't exist yet");
}
}
}
The class where the information will be stored and that creates the window (class) that will show the info:
public class infoClass {
ArrayList<infoClass> Infon;
private infoClass ic;
private String namn = "inget namn existerar";
private String infoOmInfo = null;
private int X_Rutor = 3;
private int Y_Rutor = 3;
private String[] information = new String[X_Rutor + Y_Rutor];
//info om dessa värden
public infoClass()
{
}
public void referenser(infoClass Tic)
{
ic = Tic;
infonGrafiskt ig = new infonGrafiskt(ic);
}
public void referenser(ArrayList<infoClass> Tic)
{
ic = Tic.get((Tic.size() - 1 ));
System.out.println("inna");
infonGrafiskt ig = new infonGrafiskt(ic);
ig.setVisible(true);
System.out.println("efter");
}
public String namnPåInfon()
{
return namn;
}
//namnen
public String getName()
{
return namn;
}
public void setNamn(String n)
{
namn = n;
}
//xkordinaterna
public int getX_Rutor()
{
return X_Rutor;
}
public void setX_Rutor(int n)
{
X_Rutor = n;
}
//y kordinaterna
public int getY_Rutor()
{
return Y_Rutor;
}
public void setY_Rutor(int n)
{
Y_Rutor = n;
}
//informationen
public String[] getInformationen()
{
return information;
}
public void setInformationen(String[] n)
{
information = n;
}
//infoOmInfo
public String getinfoOmInfo()
{
return infoOmInfo;
}
public void setinfoOmInfo(String n)
{
infoOmInfo = n;
}
}
The class that will show the info created by the window a bow:
public class infonGrafiskt extends JFrame implements ActionListener{
infoClass ic;
infonGrafiskt ig;
//tillrutnätet
JPanel panel = new JPanel(new SpringLayout());
boolean pausa = true;
//sakerna till desigen grund inställningar GI = grund inställningar
JButton GIklarKnapp = new JButton("Spara och gå vidare");
JTextField GInamn = new JTextField();
JLabel GINamnText = new JLabel("Namn:");
JTextField GIxRutor = new JTextField();
JLabel GIxRutorText = new JLabel("Antal rutor i X-led:");
JTextField GIyRutor = new JTextField();
JLabel GIyRutorText = new JLabel("Antal rutor i Y-led:");
JLabel GIInfo = new JLabel("Grund Inställningar");
// de olika framm:arna
JFrame GIframe = new JFrame("SpringGrid");
JFrame frame = new JFrame("SpringGrid");
//info om denna infon som finns här
JTextArea textArea = new JTextArea();
JScrollPane infoOmClasen = new JScrollPane(textArea); //hadde text area förut
JLabel infoRutan = new JLabel("Informatin om denna resuldatdatabank:");
//namnet på informationsdatabanken
JLabel namnetPåInfot = new JLabel("Namnet på denna resuldatdatabas.");
JButton ändraNamn = new JButton("Ändra namn");
JButton sparaAllt = new JButton("Spara allt");
public infonGrafiskt(infoClass Tic)
{
//få startinfo
namnOchRutor();
ic = Tic;
//skapar om rutan
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));
p1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
namnetPåInfot.setFont(new Font("Dialog",1,22));
p1.add(namnetPåInfot);
//pausa programet tills grundinställningarna är instälda
int m =1;
try {
while(m ==1)
{
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
//Create the panel and populate it. skapar den så alla kommer åt den
//JPanel panel = new JPanel(new SpringLayout());
for (int i = 0; i < ic.getX_Rutor()*ic.getY_Rutor(); i++) {
JTextField textField = new JTextField(Integer.toString(i));
panel.add(textField);
}
//Lay out the panel.
SpringUtilities.makeGrid(panel,
ic.getY_Rutor(), ic.getX_Rutor(), //rows, cols
5, 5, //initialX, initialY
5, 5);//xPad, yPad
//set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//p1.add(ändraNamn);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS));
p2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
p2.add(infoRutan);
infoOmClasen.setPreferredSize(new Dimension(0,100));
p2.add(infoOmClasen);
JPanel p3 = new JPanel();
p3.setLayout(new FlowLayout());
p3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
p3.setLayout(new BoxLayout(p3, BoxLayout.LINE_AXIS));
p3.add(ändraNamn);
p3.add(sparaAllt);
//Set up the content pane.
panel.setOpaque(true); //content panes must be opaque
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
frame.add(p1);
frame.add(p2);
frame.add(panel);//frame.setContentPane(panel);
frame.add(p3);
//Display the window.
frame.pack();
sparaAllt.addActionListener(this);
ändraNamn.addActionListener(this);
}
private void namnOchRutor()
{
System.out.println("inna 2");
//sättigång action listner
GIklarKnapp.addActionListener(this);
frame.setVisible(false);
//frameStart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GIframe.setLayout(new BoxLayout(GIframe.getContentPane(), BoxLayout.PAGE_AXIS));
JPanel GIP0 = new JPanel();
GIP0.setLayout(new BoxLayout(GIP0,BoxLayout.LINE_AXIS));
GIP0.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP0.add(GIInfo);
GIInfo.setFont(new Font("Dialog",1,22));
JPanel GIP1 = new JPanel();
GIP1.setLayout(new BoxLayout(GIP1,BoxLayout.LINE_AXIS));
GIP1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP1.add(GINamnText);
GIP1.add(Box.createRigidArea(new Dimension(10, 0)));
GIP1.add(GInamn);
JPanel GIP2 = new JPanel();
GIP2.setLayout(new BoxLayout(GIP2,BoxLayout.LINE_AXIS));
GIP2.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP2.add(GIxRutorText);
GIP2.add(Box.createRigidArea(new Dimension(10, 0)));
GIP2.add(GIxRutor);
JPanel GIP3 = new JPanel();
GIP3.setLayout(new BoxLayout(GIP3,BoxLayout.LINE_AXIS));
GIP3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP3.add(GIyRutorText);
GIP3.add(Box.createRigidArea(new Dimension(10, 0)));
GIP3.add(GIyRutor);
JPanel GIP4 = new JPanel();
GIP4.setLayout(new BoxLayout(GIP4,BoxLayout.LINE_AXIS));
GIP4.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP4.add(GIklarKnapp);
System.out.println("inna 3");
//lägga till sakerna gurund instllnings framen
GIframe.add(GIP0);
GIframe.add(GIP1);
GIframe.add(GIP2);
GIframe.add(GIP3);
GIframe.add(GIP4);
//desigen
System.out.println("inna 4");
GIframe.pack();
GIframe.setVisible(true);
System.out.println("inna5");
}
/*public static void main (String [] args)
{
infoClass i = new infoClass();
infonGrafiskt ig = new infonGrafiskt(i);
}*/
public void referenserna( infonGrafiskt Tig)
{
ig = Tig;
}
private void skrivTillbaka()
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
((JTextField)children[i]).setText(tillfäligString[i]);
System.out.println(tillfäligString[i]);
}
}
namnetPåInfot.setText(ic.getName());
textArea.setText(ic.getinfoOmInfo());
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == GIklarKnapp)
{
//skicka x och y antal ett och så
ic.setNamn(GInamn.getText());
ic.setX_Rutor(Integer.parseInt(GIxRutor.getText()));
ic.setY_Rutor(Integer.parseInt( GIyRutor.getText()));
namnetPåInfot.setText(ic.getName());
pausa = false;
GIframe.setVisible(false);
frame.setVisible(true);
}
if(e.getSource() == sparaAllt)
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
tillfäligString[i] = ((JTextField)children[i]).getText();
System.out.println(tillfäligString[i]);
}
}
ic.setInformationen(tillfäligString);
ic.setNamn(namnetPåInfot.getText());
ic.setinfoOmInfo(textArea.getText());
}
if(e.getSource() == ändraNamn)
{
skrivTillbaka();
}
}
}
so my problem now is that i can't create a new "infoclass" that will show the info in the "infoGrafikst" class. with the code:
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
that am triggered by an button click.
Sorry for all the cod, but didn't know how to show my problem in another way.
Thanks a lot. I did find out that it was this code
int m =1;
try {
while(m ==1) {
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
that made it not work...
Well I haven't gone through your code may be beacuse I am too lazy to read pages of code.Well i think the new window you are creating must be interfering with EDT.
Well i have done a short example which may help you, and its smooth:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameLaunch {
void inti(){
final JFrame f=new JFrame();
final JFrame f2=new JFrame();
final JTextArea ja=new JTextArea();
JButton b =new JButton("press for a new JFrame");
f2.add(b);
f2.pack();
f2.setVisible(true);
b.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e) {
f2.setVisible(false);
f.setSize(200,200);
ja.setText("THIS IS NOT FROZEN");
f.add(ja);
f.setVisible(true);
f.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args)
{
FrameLaunch frame = new FrameLaunch();
frame.inti();
}
}
I have a simple form setup and I was following how the book, Core Java Vol I, sets up their forms, where they have a top level class that extends JFrame create objects of the different components, and lays them out in the frame. If this isn't the way you are "typically" supposed to do it, please let me know.
I got confused when I wrote my inner classes to perform actions when buttons were pressed. I could put my inner class in my AddressBookForm class since that's where I put my buttons and it would have access to the private variables of the JTextFields. The problem I have (assuming so far the other parts are 'ok'), is I don't know how to get the addressList.size() so I can update my statusBar label with the total number of people when the Insert button is pressed. Any thoughts? Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
public class AddressBook
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
AddressBookFrame frame = new AddressBookFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem saveAsItem = new JMenuItem("Save As");
JMenuItem printItem = new JMenuItem("Print");
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(saveAsItem);
fileMenu.add(printItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
JMenu editMenu = new JMenu("Edit");
JMenuItem newItem = new JMenuItem("New");
JMenuItem editItem = new JMenuItem("Edit");
JMenuItem deleteItem = new JMenuItem("Delete");
JMenuItem findItem = new JMenuItem("Find");
JMenuItem firstItem = new JMenuItem("First");
JMenuItem previousItem = new JMenuItem("Previous");
JMenuItem nextItem = new JMenuItem("Next");
JMenuItem lastItem = new JMenuItem("Last");
editMenu.add(newItem);
editMenu.add(editItem);
editMenu.add(deleteItem);
editMenu.add(findItem);
editMenu.add(firstItem);
editMenu.add(previousItem);
editMenu.add(nextItem);
editMenu.add(lastItem);
menuBar.add(editMenu);
JMenu helpMenu = new JMenu("Help");
JMenuItem documentationItem = new JMenuItem("Documentation");
JMenuItem aboutItem = new JMenuItem("About");
helpMenu.add(documentationItem);
helpMenu.add(aboutItem);
menuBar.add(helpMenu);
frame.setVisible(true);
}
});
}
}
class AddressBookFrame extends JFrame
{
public AddressBookFrame()
{
setLayout(new BorderLayout());
setTitle("Address Book");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
AddressBookToolBar toolBar = new AddressBookToolBar();
add(toolBar, BorderLayout.NORTH);
AddressBookStatusBar aStatusBar = new AddressBookStatusBar();
add(aStatusBar, BorderLayout.SOUTH);
AddressBookForm form = new AddressBookForm();
add(form, BorderLayout.CENTER);
}
public static final int DEFAULT_WIDTH = 500;
public static final int DEFAULT_HEIGHT = 500;
}
/* Create toolbar buttons and add buttons to toolbar */
class AddressBookToolBar extends JPanel
{
public AddressBookToolBar()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
JToolBar bar = new JToolBar();
JButton newButton = new JButton("New");
JButton editButton = new JButton("Edit");
JButton deleteButton = new JButton("Delete");
JButton findButton = new JButton("Find");
JButton firstButton = new JButton("First");
JButton previousButton = new JButton("Previous");
JButton nextButton = new JButton("Next");
JButton lastButton = new JButton("Last");
bar.add(newButton);
bar.add(editButton);
bar.add(deleteButton);
bar.add(findButton);
bar.add(firstButton);
bar.add(previousButton);
bar.add(nextButton);
bar.add(lastButton);
add(bar);
}
}
/* Creates the status bar string */
class AddressBookStatusBar extends JPanel
{
public AddressBookStatusBar()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
this.statusBarString = new JLabel("Total: " + totalContacts);
add(this.statusBarString);
}
public void updateLabel(int n)
{
contactsLabel.setText((new Integer(n)).toString());
}
private JLabel statusBarString;
private JLabel contactsLabel;
}
class AddressBookForm extends JPanel
{
public AddressBookForm()
{
// create form panel
this.setLayout(new GridLayout(2, 1));
JPanel formPanel = new JPanel();
formPanel.setLayout(new GridLayout(4, 2));
firstName = new JTextField(20);
lastName = new JTextField(20);
telephone = new JTextField(20);
email = new JTextField(20);
JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT);
formPanel.add(firstNameLabel);
formPanel.add(firstName);
JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT);
formPanel.add(lastNameLabel);
formPanel.add(lastName);
JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT);
formPanel.add(telephoneLabel);
formPanel.add(telephone);
JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT);
formPanel.add(emailLabel);
formPanel.add(email);
add(formPanel);
// create button panel
JPanel buttonPanel = new JPanel();
JButton insertButton = new JButton("Insert");
JButton displayButton = new JButton("Display");
ActionListener insertAction = new AddressBookListener();
ActionListener displayAction = new AddressBookListener();
insertButton.addActionListener(insertAction);
displayButton.addActionListener(displayAction);
buttonPanel.add(insertButton);
buttonPanel.add(displayButton);
add(buttonPanel);
}
public int getTotalContacts()
{
return addressList.size();
}
private JTextField firstName;
private JTextField lastName;
private JTextField telephone;
private JTextField email;
private JLabel contacts;
private List<Person> addressList = new ArrayList<Person>();
private class AddressBookListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String buttonPressed = e.getActionCommand();
System.out.println(buttonPressed);
if (buttonPressed == "Insert") {
Person aPerson = new Person(firstName.getText(), lastName.getText(), telephone.getText(), email.getText());
addressList.add(aPerson);
}
else {
for (Person p : addressList) {
System.out.println(p);
}
}
}
}
}
Don't store a list of persons in a component, that's tight coupling.
Have a service class or interface that provides the list of Persons, something like this
public interface AddressBookService {
List<Person> getContacts();
void addContact(Person contact);
void deleteContact(Person person);
}
Now give each of your components access to this service, either by injecting it or by using it as a singleton or any other lookup method.
I vote for seanizer's solution, but if you insist on using your code, you can make use of accessing outer class's addressList variable (AddressBookFrame) in its inner classes this way:
class AddressBookFrame extends JFrame {
private List<Person> addressList = new ArrayList<Person>();
public AddressBookFrame() {
setLayout(new BorderLayout());
setTitle("Address Book");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
AddressBookToolBar toolBar = new AddressBookToolBar();
add(toolBar, BorderLayout.NORTH);
AddressBookStatusBar aStatusBar = new AddressBookStatusBar();
add(aStatusBar, BorderLayout.SOUTH);
AddressBookForm form = new AddressBookForm();
add(form, BorderLayout.CENTER);
}
public static final int DEFAULT_WIDTH = 500;
public static final int DEFAULT_HEIGHT = 500;
/* Creates the status bar string */
class AddressBookStatusBar extends JPanel {
public AddressBookStatusBar() {
setLayout(new FlowLayout(FlowLayout.LEFT));
this.statusBarString = new JLabel("Total: " + addressList.size());
add(this.statusBarString);
}
public void updateLabel(int n) {
contactsLabel.setText((new Integer(n)).toString());
}
private JLabel statusBarString;
private JLabel contactsLabel;
}
/* Create toolbar buttons and add buttons to toolbar */
class AddressBookToolBar extends JPanel {
public AddressBookToolBar() {
setLayout(new FlowLayout(FlowLayout.LEFT));
JToolBar bar = new JToolBar();
JButton newButton = new JButton("New");
JButton editButton = new JButton("Edit");
JButton deleteButton = new JButton("Delete");
JButton findButton = new JButton("Find");
JButton firstButton = new JButton("First");
JButton previousButton = new JButton("Previous");
JButton nextButton = new JButton("Next");
JButton lastButton = new JButton("Last");
bar.add(newButton);
bar.add(editButton);
bar.add(deleteButton);
bar.add(findButton);
bar.add(firstButton);
bar.add(previousButton);
bar.add(nextButton);
bar.add(lastButton);
add(bar);
}
}
class AddressBookForm extends JPanel {
public AddressBookForm() {
// create form panel
this.setLayout(new GridLayout(2, 1));
JPanel formPanel = new JPanel();
formPanel.setLayout(new GridLayout(4, 2));
firstName = new JTextField(20);
lastName = new JTextField(20);
telephone = new JTextField(20);
email = new JTextField(20);
JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT);
formPanel.add(firstNameLabel);
formPanel.add(firstName);
JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT);
formPanel.add(lastNameLabel);
formPanel.add(lastName);
JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT);
formPanel.add(telephoneLabel);
formPanel.add(telephone);
JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT);
formPanel.add(emailLabel);
formPanel.add(email);
add(formPanel);
// create button panel
JPanel buttonPanel = new JPanel();
JButton insertButton = new JButton("Insert");
JButton displayButton = new JButton("Display");
ActionListener insertAction = new AddressBookListener();
ActionListener displayAction = new AddressBookListener();
insertButton.addActionListener(insertAction);
displayButton.addActionListener(displayAction);
buttonPanel.add(insertButton);
buttonPanel.add(displayButton);
add(buttonPanel);
}
public int getTotalContacts() {
return addressList.size();
}
private JTextField firstName;
private JTextField lastName;
private JTextField telephone;
private JTextField email;
private JLabel contacts;
private class AddressBookListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String buttonPressed = e.getActionCommand();
System.out.println(buttonPressed);
if (buttonPressed == "Insert") {
Person aPerson = new Person(firstName.getText(), lastName
.getText(), telephone.getText(), email.getText());
addressList.add(aPerson);
} else {
for (Person p : addressList) {
System.out.println(p);
}
}
}
}
}
}