Braces preventing Compilation - java

Im currently creating a GUI from scratch and I am including multiple classes on one page. Unfortunately, something is preventing me from seeing a class and I think it has to do with opening and closing brackets. Can anyone possibly help with where I went wrong so I dont do this in the future? My program is throwing an exception at RentalPanel class. It does not see it for some reason.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MavGUI2 extends JFrame
{
private JDesktopPane theDesktop;
public MavGUI2()
{
super("Mav Rental System");
theDesktop = new JDesktopPane();
JMenuBar bar = new JMenuBar();
JMenu addMenu = new JMenu("Add");
JMenuItem addRental = new JMenuItem ("Add Rental");
JMenuItem addCustomer = new JMenuItem("Add Customer");
addMenu.add(addRental);
addMenu.add(addCustomer);
bar.add(addMenu);
add(theDesktop);
setJMenuBar(bar);
addCustomer.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JInternalFrame frame = new JInternalFrame("Add Customer", true, true, true, true);
CustomerPanel cp = new CustomerPanel();
frame.add(cp);
frame.pack();
theDesktop.add(frame);
frame.setVisible(true);
}
});
addRental.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JInternalFrame frame = new JInternalFrame("Add Rental", true, true, true, true);
RentalPanel rp = new RentalPanel();
frame.add(rp);
frame.pack();
theDesktop.add(frame);
frame.setVisible(true);
}
});
JMenu exitMenu = new JMenu("Exit");
JMenuItem calCharges = new JMenuItem("Calculate Charges");
JMenuItem close = new JMenuItem("Close");
close.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
calCharges.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Calculations");
}
});
exitMenu.add(calCharges);
exitMenu.add(close);
bar.add(exitMenu);
add(theDesktop);
setJMenuBar(bar);
}
public static void main(String args[])
{
MavGUI2 m = new MavGUI2();
m.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
m.setSize(500,500);
m.setVisible(true);
}
class CustomerPanel extends Panel
{
private JLabel nameLabel;
private JLabel streetLabel;
private JLabel cityLabel;
private JLabel stateLabel;
private JLabel creditLabel;
private JLabel zipLabel;
private JLabel submitLabel;
private JButton submitButton;
private JTextField nameField;
private JTextField streetField;
private JTextField cityField;
private JTextField stateField;
private JTextField creditField;
private JTextField zipField;
public CustomerPanel()
{
setLayout(new GridLayout(7,2));
nameLabel = new JLabel(" Enter name: ");
streetLabel = new JLabel(" Enter street: ");
cityLabel = new JLabel(" Enter city: ");
stateLabel = new JLabel (" Enter state: ");
zipLabel = new JLabel(" Enter zip: ");
creditLabel = new JLabel(" Enter credit card number: ");
submitLabel = new JLabel(" Click when done!");
nameField = new JTextField(20);
streetField = new JTextField(20);
cityField = new JTextField(20);
stateField = new JTextField(20);
zipField = new JTextField(20);
creditField = new JTextField(20);
submitButton = new JButton(" SUBMIT ");
MyListener handler = new MyListener();
submitButton.addActionListener(handler);
add(nameLabel);
add(nameField);
add(streetLabel);
add(streetField);
add(cityLabel);
add(cityField);
add(stateLabel);
add(stateField);
add(zipLabel);
add(zipField);
add(creditLabel);
add(creditField);
add(submitLabel);
add(submitButton);
}
class MyListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.printf(nameField.getText() +" " + streetField.getText() + " "+ cityField.getText());
nameField.setText("");
streetField.setText("");
cityField.setText("");
stateField.setText("");
zipField.setText("");
creditField.setText("");
nameField.requestFocus();
}
}
class RentalPanel extends Panel
{
private JLabel custNameLabel;
private JLabel numDaysLabel;
private JLabel perDayLabel;
private JButton submit2Button;
private JLabel submit2Label;
private JTextField custNameField;
private JTextField numDaysField;
private JTextField perDayField;
private JCheckBox furnBox;
private JCheckBox elecBox;
private JComboBox<String> furnType;
String types[] = {"BED", "COUCH", "CHAIR"};
private JComboBox<String> elecType;
String type2[] = {"COMPUTER","TV"};
public RentalPanel()
{
setLayout(new GridLayout(6,2));
ButtonGroup group = new ButtonGroup();
furnBox = new JCheckBox(" Furniture ");
elecBox = new JCheckBox(" Electronic");
group.add(furnBox);
group.add(elecBox);
custNameLabel = new JLabel(" Enter customer name");
numDaysLabel = new JLabel(" Enter number of days");
perDayLabel = new JLabel(" Enter price per day");
submit2Label = new JLabel(" Click when done");
submit2Button = new JButton(" SUBMIT");
custNameField = new JTextField(20);
numDaysField = new JTextField(20);
perDayField = new JTextField(20);
furnType = new JComboBox<String>(types);
elecType = new JComboBox<String>(type2);
add(custNameLabel);
add(custNameField);
add(furnBox);
add(elecBox);
add(numDaysLabel);
add(numDaysField);
add(perDayLabel);
add(perDayField);
add(furnType);
add(elecType);
add(submit2Label);
add(submit2Button);
}//closes Rental Panel constructor
}//close rental panel
}// closes customer panel
}//closes MAVGUI
Blockquote

The trouble is, the RentalPanel class is a non-static inner class inside CustomerPanel. So you cannot directly access it from MavGUI2 class. Making RentalPanel and CustomerPanel classes static inner classes, will solve the compilation error.
In fact, it would be advisable to move them to their separate files.

Related

How can I transfer data between one jframe to another jframe?

I'm new to java and for some reason I don't know any other way to transfer the data from another frame after pressing submit. For example, it will show the output frame the label and textfield that the user wrote in the first frame like this "Name: "user's name". If you do know please post the code I should put, thank you!
package eventdriven;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDriven extends JFrame {
JPanel items = new JPanel();
JLabel fName = new JLabel("First Name: ");
JLabel lName = new JLabel("Last Name: ");
JLabel mName = new JLabel("Middle Name: ");
JLabel mNum = new JLabel("Mobile Number: ");
JLabel eAdd = new JLabel("Email Address: ");
JTextField fname = new JTextField(15);
JTextField lname = new JTextField(15);
JTextField mname = new JTextField(15);
JTextField mnum = new JTextField(15);
JTextField eadd = new JTextField(15);
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear All");
JButton okay = new JButton("Okay");
JTextArea infos;
JFrame output;
public EventDriven()
{
this.setTitle("INPUT");
this.setResizable(false);
this.setSize(230, 300);
this.setLocation(300, 300);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(fName);
this.add(fname);
this.add(lName);
this.add(lname);
this.add(mName);
this.add(mname);
this.add(mNum);
this.add(mnum);
this.add(eAdd);
this.add(eadd);
submit.addActionListener(new btnSubmit());
this.add(submit);
clear.addActionListener(new btnClearAll());
this.add(clear);
okay.addActionListener(new btnOkay());
this.add(items);
this.setVisible(true);
}
class btnSubmit implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submit)
{
submit.setEnabled(false);
output = new JFrame("OUTPUT");
output.show();
output.setSize(300,280);
output.setTitle("OUTPUT");
output.add(okay);
output.setLayout(new FlowLayout(FlowLayout.CENTER));
}
}
}
class btnClearAll implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == clear)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
class btnOkay implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == okay)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
public static void main(String[] args)
{
EventDriven window = new EventDriven();
}
}
It's not clear what problem you are having displaying a value from one field in another frame. But here's an example of doing that (with fields reduced to just one for demonstration):
public class EventDriven extends JFrame {
private final JTextField nameField = new JTextField(15);
private final JButton submit = new JButton("Submit");
private final JButton clear = new JButton("Clear All");
public EventDriven() {
setTitle("Input");
setLayout(new FlowLayout(FlowLayout.CENTER));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Name: "));
add(nameField);
submit.addActionListener(this::showOutput);
add(submit);
clear.addActionListener(this::clearInput);
add(clear);
pack();
}
private void showOutput(ActionEvent ev) {
submit.setEnabled(false);
JDialog output = new JDialog(EventDriven.this, "Output", true);
output.add(new Label("Name: " + nameField.getText()), BorderLayout.CENTER);
JButton okButton = new JButton("OK");
output.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(bv -> output.setVisible(false));
output.pack();
output.setVisible(true);
}
private void clearInput(ActionEvent ev) {
nameField.setText(null);
submit.setEnabled(true);
}
public static void main(String[] args) {
EventDriven window = new EventDriven();
window.setVisible(true);
}
}
You will also see that I've simplified your action listeners to demonstrate an easier way to respond to user driven event.s

How to take User input in one frame and adding it to an arraylist to display on another frame

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();
}

JFrame/JPanel's not showing with Group Layout

I have a pretty big setup here and its still very much a WIP. Right now I want to get my GUI displaying properly, and switching between panels at the click of a button. In my GUI() method, I set up my various panels with group layout. At the end of the class, you will notice methods i want to use to set the various panels visible or invisible. LoginP is the panel i want to see when i run the code, so i call the corresponding method at the end of my GUI() method, but for some strange reason, when I run it is as if there are no panels at all, just a blank JFrame. I added a System.out.println(); just after I call the method to set LoginP to visible (at the end of the GUI() method), but alas, that line is not printed. I'm sure the answer is staring me right in the face, but I'm just not able to see it.
Edit: For those who feel like playing a bit, here are all the source files: http://goo.gl/KjW8cH
//Individual Imports
/*
import java.awt.GroupLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class GUI extends JFrame
{
/*#################################################################################################################################################################
*#####################################################################################################################################################
*###############################################################################################################################################################*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Login Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel loginP;
private JLabel titleL;
private JLabel instructL;
private JLabel usernameL;
private JLabel passwordL;
private JLabel loginL;
private JButton studentB;
private JButton lecturerB;
private JTextField usernameTF;
private JTextField passwordTF;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Add Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ private JPanel addQP;
private JPanel addQP;
private JLabel instructionsL;
private JLabel txtL;
private JLabel infoL;
private JButton appendB;
private JButton overwriteB;
private JTextField pathTF;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel questionP;
private JLabel qNumL;
private JLabel groupL;
private JLabel questionL;
private JLabel opt1L;
private JLabel opt2L;
private JLabel opt3L;
private JLabel opt4L;
private JButton opt1B;
private JButton opt2B;
private JButton opt3B;
private JButton opt4B;
String qNumber = "3";
String group = "JDBC";
String question = "This is the question";
String opt1 = "This is option 1";
String opt2 = "This is option 2";
String opt3 = "This is option 3";
String opt4 = "This is option 4";
String a = "a.";
String b = "b.";
String c = "c.";
String d = "d.";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Viewer Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel viewerP;
private JLabel aL;
private JLabel bL;
private JLabel cL;
private JLabel dL;
private JButton nextB;
private JButton closeB;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Select Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel selectQP;
private JLabel instruct1L;
private JLabel askL;
private JCheckBox checkBox1;
private JCheckBox checkBox2;
private JCheckBox checkBox3;
private JCheckBox checkBox4;
private JButton viewB;
private JButton startB;
private JTextField numOfQTF;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mark Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel markP;
private JLabel percentageL;
private JLabel outOfL;
private JButton backB;
private JButton logOutB;
Connection con;
Statement stmt;
ResultSet rs;
/*#################################################################################################################################################################
*#########################################################################Panels##################################################################################
*###############################################################################################################################################################*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Login Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public GUI()
{
super("Tester");
setLayout(new FlowLayout());
loginP = new JPanel();
add(loginP);
GroupLayout loginPLayout = new GroupLayout(loginP);
loginP.setLayout(loginPLayout);
loginPLayout.setAutoCreateGaps(true);
loginPLayout.setAutoCreateContainerGaps(true);
Font font = new Font("Freestyle Script", Font.PLAIN,80);
titleL = new JLabel("Tester");
titleL.setFont(font);
instructL = new JLabel("Please eneter your name and password and select your login type to login.");
usernameL = new JLabel("Username:");
passwordL = new JLabel("Password:");
loginL = new JLabel("Login as");
studentB = new JButton("Student");
lecturerB = new JButton("Lecturer");
usernameTF = new JTextField("", 100);
passwordTF = new JTextField("", 100);
studentB.addActionListener(new studentH());
lecturerB.addActionListener(new lecturerH());
loginPLayout.setHorizontalGroup(loginPLayout.createSequentialGroup()
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(usernameL)
.addComponent(passwordL))
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(titleL)
.addComponent(instructL)
.addComponent(usernameTF)
.addComponent(passwordTF)
.addComponent(loginL)
.addGroup(loginPLayout.createSequentialGroup()
.addComponent(studentB)
.addComponent(lecturerB)))
);
loginPLayout.setVerticalGroup(loginPLayout.createSequentialGroup()
.addComponent(titleL)
.addComponent(instructL)
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(usernameL)
.addComponent(usernameTF))
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(passwordL)
.addComponent(passwordTF))
.addComponent(loginL)
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(studentB)
.addComponent(lecturerB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Select Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
selectQP = new JPanel();
add(selectQP);
GroupLayout selectQPLayout = new GroupLayout(selectQP);
selectQP.setLayout(selectQPLayout);
selectQPLayout.setAutoCreateGaps(true);
selectQPLayout.setAutoCreateContainerGaps(true);
String cat1 = "Collections";
String cat2 = "Multithreading";
String cat3 = "Networking";
String cat4 = "JDBC";
instruct1L = new JLabel("Select the groups of questions you would like to be tested on");
askL = new JLabel("How many questions would you like?");
checkBox1 = new JCheckBox(cat1);
checkBox2 = new JCheckBox(cat2);
checkBox3 = new JCheckBox(cat3);
checkBox4 = new JCheckBox(cat4);
viewB = new JButton("View Questions");
startB = new JButton("Start Test");
numOfQTF = new JTextField("", 100);
viewB.addActionListener(new viewH());
startB.addActionListener(new startH());
selectQPLayout.setHorizontalGroup(selectQPLayout.createParallelGroup()
.addComponent(instruct1L)
.addComponent(checkBox1)
.addComponent(checkBox2)
.addComponent(checkBox3)
.addComponent(checkBox4)
.addComponent(askL)
.addComponent(numOfQTF)
.addGroup(selectQPLayout.createSequentialGroup()
.addComponent(viewB)
.addComponent(startB))
);
selectQPLayout.setVerticalGroup(selectQPLayout.createSequentialGroup()
.addComponent(instruct1L)
.addComponent(checkBox1)
.addComponent(checkBox2)
.addComponent(checkBox3)
.addComponent(checkBox4)
.addComponent(askL)
.addComponent(numOfQTF)
.addGroup(selectQPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(viewB)
.addComponent(startB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Add Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
addQP = new JPanel();
add(addQP);
GroupLayout addQPLayout = new GroupLayout(addQP);
addQP.setLayout(addQPLayout);
addQPLayout.setAutoCreateGaps(true);
addQPLayout.setAutoCreateContainerGaps(true);
instructionsL = new JLabel("Please enter the name of the file:");
txtL = new JLabel(".txt");
infoL = new JLabel("You will be logged out after the questions have been added.");
appendB = new JButton("Append Questions");
overwriteB = new JButton("Overwrite Questions");
pathTF = new JTextField("", 100);
appendB.addActionListener(new appendH());
overwriteB.addActionListener(new overwriteH());
addQPLayout.setHorizontalGroup(addQPLayout.createSequentialGroup()
.addGroup(addQPLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(instructionsL)
.addGroup(addQPLayout.createSequentialGroup()
.addComponent(pathTF)
.addComponent(txtL))
.addComponent(infoL)
.addGroup(addQPLayout.createSequentialGroup()
.addComponent(appendB)
.addComponent(overwriteB)))
);
addQPLayout.setVerticalGroup(addQPLayout.createSequentialGroup()
.addComponent(instructionsL)
.addGroup(addQPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(pathTF)
.addComponent(txtL))
.addComponent(infoL)
.addGroup(addQPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(appendB)
.addComponent(overwriteB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
qNumL = new JLabel("Question Number: " + qNumber);
groupL = new JLabel("Group: " + group);
questionL = new JLabel(question);
opt1L = new JLabel(opt1);
opt2L = new JLabel(opt2);
opt3L = new JLabel(opt3);
opt4L = new JLabel(opt4);
opt1B = new JButton("A");
opt2B = new JButton("B");
opt3B = new JButton("C");
opt4B = new JButton("D");
questionP = new JPanel();
add(questionP);
GroupLayout questionPLayout = new GroupLayout(questionP);
questionP.setLayout(questionPLayout);
questionPLayout.setAutoCreateGaps(true);
questionPLayout.setAutoCreateContainerGaps(true);
optH handler = new optH();
opt1B.addActionListener(handler);
//opt2B.addActionListener(handler);
//opt3B.addActionListener(handler);
//opt4B.addActionListener(handler);
questionPLayout.setHorizontalGroup(questionPLayout.createSequentialGroup()
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(qNumL)
.addComponent(questionL)
.addComponent(opt1B)
.addComponent(opt2B)
.addComponent(opt3B)
.addComponent(opt4B))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(opt1L)
.addComponent(opt2L)
.addComponent(opt3L)
.addComponent(opt4L))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(groupL))
);
questionPLayout.setVerticalGroup(questionPLayout.createSequentialGroup()
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(qNumL)
.addComponent(groupL))
.addComponent(questionL)
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(opt1B)
.addComponent(opt1L))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(opt2B)
.addComponent(opt2L))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(opt3B)
.addComponent(opt3L))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(opt4B)
.addComponent(opt4L))
);
showLoginP();
System.out.println("Im here");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Viewer Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
qNumL = new JLabel("Question Number: " + qNumber);
groupL = new JLabel("Group: " + group);
questionL = new JLabel(question);
aL = new JLabel("A");
bL = new JLabel("B");
cL = new JLabel("C");
dL = new JLabel("D");
opt1L = new JLabel(opt1);
opt2L = new JLabel(opt2);
opt3L = new JLabel(opt3);
opt4L = new JLabel(opt4);
nextB = new JButton("Next");
closeB = new JButton("Close");
viewerP = new JPanel();
add(viewerP);
GroupLayout viewerPLayout = new GroupLayout(viewerP);
viewerP.setLayout(viewerPLayout);
viewerPLayout.setAutoCreateGaps(true);
viewerPLayout.setAutoCreateContainerGaps(true);
viewerPLayout.setHorizontalGroup(viewerPLayout.createSequentialGroup()
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(qNumL)
.addComponent(questionL)
.addComponent(aL)
.addComponent(bL)
.addComponent(cL)
.addComponent(dL))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(opt1L)
.addComponent(opt2L)
.addComponent(opt3L)
.addComponent(opt4L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(groupL)
.addGroup(viewerPLayout.createSequentialGroup()
.addComponent(nextB)
.addComponent(closeB)))
);
viewerPLayout.setVerticalGroup(viewerPLayout.createSequentialGroup()
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(qNumL)
.addComponent(groupL))
.addComponent(questionL)
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(aL)
.addComponent(opt1L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bL)
.addComponent(opt2L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(cL)
.addComponent(opt3L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(dL)
.addComponent(opt4L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(nextB)
.addComponent(closeB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mark Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
markP = new JPanel();
add(markP);
GroupLayout markPLayout = new GroupLayout(markP);
markP.setLayout(markPLayout);
markPLayout.setAutoCreateGaps(true);
markPLayout.setAutoCreateContainerGaps(true);
int percentage = 90;
int correct = 9;
int total = 10;
percentageL = new JLabel("You scored: " + percentage + "%");
outOfL = new JLabel("You have " + correct + " corret answers out of a possible " + total);
backB = new JButton("Back to Group Selection");
logOutB = new JButton("Log Out");
backB.addActionListener(new backH());
logOutB.addActionListener(new logOutH());
markPLayout.setHorizontalGroup(markPLayout.createParallelGroup()
.addComponent(percentageL)
.addComponent(outOfL)
.addGroup(markPLayout.createSequentialGroup()
.addComponent(backB)
.addComponent(logOutB))
);
markPLayout.setVerticalGroup(markPLayout.createSequentialGroup()
.addComponent(percentageL)
.addComponent(outOfL)
.addGroup(markPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(backB)
.addComponent(logOutB))
);
}
showLoginP();
System.out.println("Im here");
/*#################################################################################################################################################################
*#####################################################################Action Listeners############################################################################
*###############################################################################################################################################################*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Login Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class studentH implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
Student stu = new Student();
String username = usernameTF.getText();
String password = passwordTF.getText();
boolean correct = stu.Student(username, password);
if(correct == true)
{
showSelectQP();
}
else
{
JOptionPane.showMessageDialog(null, "You have entered incorect details. Please try again", "Incorrect Details", JOptionPane.ERROR_MESSAGE);
usernameTF.setText("");
passwordTF.setText("");
}
}
}
private class lecturerH implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
Lecturer lect = new Lecturer();
String username = usernameTF.getText();
String password = passwordTF.getText();
boolean correct = lect.Lecturer(username, password);
if(correct == true)
{
showAddQP();
}
else
{
JOptionPane.showMessageDialog(null, "You have entered incorect details. Please try again", "Incorrect Details", JOptionPane.ERROR_MESSAGE);
usernameTF.setText("");
passwordTF.setText("");
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Add Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class appendH implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
//Append appen = new Append();
String path = pathTF.getText();
//appen.Append(path);
}
}
private class overwriteH implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
Overwrite over = new Overwrite();
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class optH implements ActionListener
{
#Override
public void actionPerformed( ActionEvent event )
{
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Select Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class viewH implements ActionListener
{
#Override
public void actionPerformed( ActionEvent event )
{
}
}
private class startH implements ActionListener
{
#Override
public void actionPerformed( ActionEvent event )
{
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mark Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class backH implements ActionListener
{
#Override
public void actionPerformed( ActionEvent event )
{
}
}
private class logOutH implements ActionListener
{
#Override
public void actionPerformed( ActionEvent event )
{
}
}
public void showLoginP()
{
addQP.setVisible(false);
questionP.setVisible(false);
viewerP.setVisible(false);
markP.setVisible(false);
selectQP.setVisible(false);
loginP.setVisible(true);
revalidate();
repaint();
}
public void showAddQP()
{
questionP.setVisible(false);
viewerP.setVisible(false);
markP.setVisible(false);
selectQP.setVisible(false);
loginP.setVisible(false);
addQP.setVisible(true);
}
public void showQuestionP()
{
addQP.setVisible(false);
viewerP.setVisible(false);
markP.setVisible(false);
selectQP.setVisible(false);
loginP.setVisible(false);
questionP.setVisible(true);
}
public void showViewerP()
{
addQP.setVisible(false);
questionP.setVisible(false);
markP.setVisible(false);
selectQP.setVisible(false);
loginP.setVisible(false);
viewerP.setVisible(true);
}
public void showMarkP()
{
addQP.setVisible(false);
questionP.setVisible(false);
viewerP.setVisible(false);
selectQP.setVisible(false);
loginP.setVisible(false);
markP.setVisible(true);
}
public void showSelectQP()
{
addQP.setVisible(false);
//questionP.setVisible(false);
viewerP.setVisible(false);
markP.setVisible(false);
loginP.setVisible(false);
selectQP.setVisible(true);
}
}
This won't answer your question, but there's so much going on here I'm going to take it one part at a time. First of all, don't put the main method in another class, there's really no reason to. Add this to your existing GUI class and delete the other class:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI gui = new GUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(600, 400);
gui.setResizable(true);
gui.setVisible(true);
}
});
}
I suggest doing so just above your constructor so it's easy to find.
EDIT: Here's a version that uses cardlayout. You're welcome.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class GUI extends JFrame {
JComboBox<String> comboBox;
private JPanel cardPanel;
/*#################################################################################################################################################################
*########################################################################Constructors#############################################################################
*###############################################################################################################################################################*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Login Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel loginP;
private JLabel titleL;
private JLabel instructL;
private JLabel usernameL;
private JLabel passwordL;
private JLabel loginL;
private JButton studentB;
private JButton lecturerB;
private JTextField usernameTF;
private JTextField passwordTF;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Add Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ private JPanel addQP;
private JPanel addQP;
private JLabel instructionsL;
private JLabel txtL;
private JLabel infoL;
private JButton appendB;
private JButton overwriteB;
private JTextField pathTF;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel questionP;
private JLabel qNumL;
private JLabel groupL;
private JLabel questionL;
private JLabel opt1L;
private JLabel opt2L;
private JLabel opt3L;
private JLabel opt4L;
private JButton opt1B;
private JButton opt2B;
private JButton opt3B;
private JButton opt4B;
String qNumber = "3";
String group = "JDBC";
String question = "This is the question";
String opt1 = "This is option 1";
String opt2 = "This is option 2";
String opt3 = "This is option 3";
String opt4 = "This is option 4";
String a = "a.";
String b = "b.";
String c = "c.";
String d = "d.";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Viewer Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel viewerP;
private JLabel aL;
private JLabel bL;
private JLabel cL;
private JLabel dL;
private JButton nextB;
private JButton closeB;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Select Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel selectQP;
private JLabel instruct1L;
private JLabel askL;
private JCheckBox checkBox1;
private JCheckBox checkBox2;
private JCheckBox checkBox3;
private JCheckBox checkBox4;
private JButton viewB;
private JButton startB;
private JTextField numOfQTF;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mark Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private JPanel markP;
private JLabel percentageL;
private JLabel outOfL;
private JButton backB;
private JButton logOutB;
Connection con;
Statement stmt;
ResultSet rs;
/*#################################################################################################################################################################
*#########################################################################Panels##################################################################################
*###############################################################################################################################################################*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Login Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI gui = new GUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(600, 400);
gui.setResizable(true);
gui.setVisible(true);
}
});
}
public GUI() {
super("Tester");
loginP = new JPanel();
GroupLayout loginPLayout = new GroupLayout(loginP);
loginP.setLayout(loginPLayout);
loginPLayout.setAutoCreateGaps(true);
loginPLayout.setAutoCreateContainerGaps(true);
Font font = new Font("Freestyle Script", Font.PLAIN,80);
titleL = new JLabel("Tester");
titleL.setFont(font);
instructL = new JLabel("Please eneter your name and password and select your login type to login.");
usernameL = new JLabel("Username:");
passwordL = new JLabel("Password:");
loginL = new JLabel("Login as");
studentB = new JButton("Student");
lecturerB = new JButton("Lecturer");
usernameTF = new JTextField("", 100);
passwordTF = new JTextField("", 100);
studentB.addActionListener(new studentH());
lecturerB.addActionListener(new lecturerH());
loginPLayout.setHorizontalGroup(loginPLayout.createSequentialGroup()
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(usernameL)
.addComponent(passwordL))
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(titleL)
.addComponent(instructL)
.addComponent(usernameTF)
.addComponent(passwordTF)
.addComponent(loginL)
.addGroup(loginPLayout.createSequentialGroup()
.addComponent(studentB)
.addComponent(lecturerB)))
);
loginPLayout.setVerticalGroup(loginPLayout.createSequentialGroup()
.addComponent(titleL)
.addComponent(instructL)
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(usernameL)
.addComponent(usernameTF))
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(passwordL)
.addComponent(passwordTF))
.addComponent(loginL)
.addGroup(loginPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(studentB)
.addComponent(lecturerB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Select Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
selectQP = new JPanel();
GroupLayout selectQPLayout = new GroupLayout(selectQP);
selectQP.setLayout(selectQPLayout);
selectQPLayout.setAutoCreateGaps(true);
selectQPLayout.setAutoCreateContainerGaps(true);
String cat1 = "Collections";
String cat2 = "Multithreading";
String cat3 = "Networking";
String cat4 = "JDBC";
instruct1L = new JLabel("Select the groups of questions you would like to be tested on");
askL = new JLabel("How many questions would you like?");
checkBox1 = new JCheckBox(cat1);
checkBox2 = new JCheckBox(cat2);
checkBox3 = new JCheckBox(cat3);
checkBox4 = new JCheckBox(cat4);
viewB = new JButton("View Questions");
startB = new JButton("Start Test");
numOfQTF = new JTextField("", 100);
viewB.addActionListener(new viewH());
startB.addActionListener(new startH());
selectQPLayout.setHorizontalGroup(selectQPLayout.createParallelGroup()
.addComponent(instruct1L)
.addComponent(checkBox1)
.addComponent(checkBox2)
.addComponent(checkBox3)
.addComponent(checkBox4)
.addComponent(askL)
.addComponent(numOfQTF)
.addGroup(selectQPLayout.createSequentialGroup()
.addComponent(viewB)
.addComponent(startB))
);
selectQPLayout.setVerticalGroup(selectQPLayout.createSequentialGroup()
.addComponent(instruct1L)
.addComponent(checkBox1)
.addComponent(checkBox2)
.addComponent(checkBox3)
.addComponent(checkBox4)
.addComponent(askL)
.addComponent(numOfQTF)
.addGroup(selectQPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(viewB)
.addComponent(startB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Add Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
addQP = new JPanel();
GroupLayout addQPLayout = new GroupLayout(addQP);
addQP.setLayout(addQPLayout);
addQPLayout.setAutoCreateGaps(true);
addQPLayout.setAutoCreateContainerGaps(true);
instructionsL = new JLabel("Please enter the name of the file:");
txtL = new JLabel(".txt");
infoL = new JLabel("You will be logged out after the questions have been added.");
appendB = new JButton("Append Questions");
overwriteB = new JButton("Overwrite Questions");
pathTF = new JTextField("", 100);
appendB.addActionListener(new appendH());
overwriteB.addActionListener(new overwriteH());
addQPLayout.setHorizontalGroup(addQPLayout.createSequentialGroup()
.addGroup(addQPLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(instructionsL)
.addGroup(addQPLayout.createSequentialGroup()
.addComponent(pathTF)
.addComponent(txtL))
.addComponent(infoL)
.addGroup(addQPLayout.createSequentialGroup()
.addComponent(appendB)
.addComponent(overwriteB)))
);
addQPLayout.setVerticalGroup(addQPLayout.createSequentialGroup()
.addComponent(instructionsL)
.addGroup(addQPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(pathTF)
.addComponent(txtL))
.addComponent(infoL)
.addGroup(addQPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(appendB)
.addComponent(overwriteB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
qNumL = new JLabel("Question Number: " + qNumber);
groupL = new JLabel("Group: " + group);
questionL = new JLabel(question);
opt1L = new JLabel(opt1);
opt2L = new JLabel(opt2);
opt3L = new JLabel(opt3);
opt4L = new JLabel(opt4);
opt1B = new JButton("A");
opt2B = new JButton("B");
opt3B = new JButton("C");
opt4B = new JButton("D");
questionP = new JPanel();
// add(questionP);
GroupLayout questionPLayout = new GroupLayout(questionP);
questionP.setLayout(questionPLayout);
questionPLayout.setAutoCreateGaps(true);
questionPLayout.setAutoCreateContainerGaps(true);
optH handler = new optH();
opt1B.addActionListener(handler);
//opt2B.addActionListener(handler);
//opt3B.addActionListener(handler);
//opt4B.addActionListener(handler);
questionPLayout.setHorizontalGroup(questionPLayout.createSequentialGroup()
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(qNumL)
.addComponent(questionL)
.addComponent(opt1B)
.addComponent(opt2B)
.addComponent(opt3B)
.addComponent(opt4B))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(opt1L)
.addComponent(opt2L)
.addComponent(opt3L)
.addComponent(opt4L))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(groupL))
);
questionPLayout.setVerticalGroup(questionPLayout.createSequentialGroup()
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(qNumL)
.addComponent(groupL))
.addComponent(questionL)
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(opt1B)
.addComponent(opt1L))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(opt2B)
.addComponent(opt2L))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(opt3B)
.addComponent(opt3L))
.addGroup(questionPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(opt4B)
.addComponent(opt4L))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Viewer Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
qNumL = new JLabel("Question Number: " + qNumber);
groupL = new JLabel("Group: " + group);
questionL = new JLabel(question);
aL = new JLabel("A");
bL = new JLabel("B");
cL = new JLabel("C");
dL = new JLabel("D");
opt1L = new JLabel(opt1);
opt2L = new JLabel(opt2);
opt3L = new JLabel(opt3);
opt4L = new JLabel(opt4);
nextB = new JButton("Next");
closeB = new JButton("Close");
viewerP = new JPanel();
GroupLayout viewerPLayout = new GroupLayout(viewerP);
viewerP.setLayout(viewerPLayout);
viewerPLayout.setAutoCreateGaps(true);
viewerPLayout.setAutoCreateContainerGaps(true);
viewerPLayout.setHorizontalGroup(viewerPLayout.createSequentialGroup()
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(qNumL)
.addComponent(questionL)
.addComponent(aL)
.addComponent(bL)
.addComponent(cL)
.addComponent(dL))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(opt1L)
.addComponent(opt2L)
.addComponent(opt3L)
.addComponent(opt4L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(groupL)
.addGroup(viewerPLayout.createSequentialGroup()
.addComponent(nextB)
.addComponent(closeB)))
);
viewerPLayout.setVerticalGroup(viewerPLayout.createSequentialGroup()
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(qNumL)
.addComponent(groupL))
.addComponent(questionL)
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(aL)
.addComponent(opt1L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bL)
.addComponent(opt2L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(cL)
.addComponent(opt3L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(dL)
.addComponent(opt4L))
.addGroup(viewerPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(nextB)
.addComponent(closeB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mark Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
markP = new JPanel();
GroupLayout markPLayout = new GroupLayout(markP);
markP.setLayout(markPLayout);
markPLayout.setAutoCreateGaps(true);
markPLayout.setAutoCreateContainerGaps(true);
int percentage = 90;
int correct = 9;
int total = 10;
percentageL = new JLabel("You scored: " + percentage + "%");
outOfL = new JLabel("You have " + correct + " corret answers out of a possible " + total);
backB = new JButton("Back to Group Selection");
logOutB = new JButton("Log Out");
backB.addActionListener(new backH());
logOutB.addActionListener(new logOutH());
markPLayout.setHorizontalGroup(markPLayout.createParallelGroup()
.addComponent(percentageL)
.addComponent(outOfL)
.addGroup(markPLayout.createSequentialGroup()
.addComponent(backB)
.addComponent(logOutB))
);
markPLayout.setVerticalGroup(markPLayout.createSequentialGroup()
.addComponent(percentageL)
.addComponent(outOfL)
.addGroup(markPLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(backB)
.addComponent(logOutB))
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Card Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cardPanel = new JPanel(new CardLayout(0,0));
JPanel[] cards = new JPanel[6];
String[] titles = new String[6];
cards[0] = loginP;
cards[1] = selectQP;
cards[2] = addQP;
cards[3] = questionP;
cards[4] = viewerP;
cards[5] = markP;
titles[0] = "loginP";
titles[1] = "selectQP";
titles[2] = "addQP";
titles[3] = "questionP";
titles[4] = "viewerP";
titles[5] = "markP";
for(int i = 0; i < cards.length; i++) {
cardPanel.add(cards[i], titles[i]);
}
//You can remove this once you are satisfied card layout works with your buttons - this is just for the combobox I added
setLayout(new BorderLayout());
add(cardPanel, BorderLayout.CENTER);
comboBox = new JComboBox<>(titles);
comboBox.addActionListener(new CardListener());
add(comboBox, BorderLayout.NORTH);
//Add this back in once you remove the rest
// add(cardPanel);
pack();
}
//You can remove this once you are satisfied card layout works with your buttons - this is just for the combobox I added
private class CardListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout c1 = (CardLayout)(cardPanel.getLayout());
c1.show(cardPanel, (String)comboBox.getSelectedItem());
}
}
/*#################################################################################################################################################################
*#####################################################################Action Listeners############################################################################
*###############################################################################################################################################################*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Login Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class studentH implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
Student stu = new Student();
String username = usernameTF.getText();
String password = passwordTF.getText();
boolean correct = stu.Student(username, password);
if(correct == true) {
changeCard("selectQP");
}
else {
JOptionPane.showMessageDialog(null, "You have entered incorect details. Please try again", "Incorrect Details", JOptionPane.ERROR_MESSAGE);
usernameTF.setText("");
passwordTF.setText("");
}
}
}
private class lecturerH implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
Lecturer lect = new Lecturer();
String username = usernameTF.getText();
String password = passwordTF.getText();
boolean correct = lect.Lecturer(username, password);
if(correct == true) {
changeCard("addQP");
}
else {
JOptionPane.showMessageDialog(null, "You have entered incorect details. Please try again", "Incorrect Details", JOptionPane.ERROR_MESSAGE);
usernameTF.setText("");
passwordTF.setText("");
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Add Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class appendH implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
//Append appen = new Append();
String path = pathTF.getText();
//appen.Append(path);
}
}
private class overwriteH implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
// Overwrite over = new Overwrite();
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class optH implements ActionListener {
#Override
public void actionPerformed( ActionEvent event ) {
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Select Question Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class viewH implements ActionListener {
#Override
public void actionPerformed( ActionEvent event ) {
}
}
private class startH implements ActionListener {
#Override
public void actionPerformed( ActionEvent event ) {
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mark Panel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private class backH implements ActionListener {
#Override
public void actionPerformed( ActionEvent event ) {
}
}
private class logOutH implements ActionListener {
#Override
public void actionPerformed( ActionEvent event ) {
}
}
private void changeCard(String newCardName) {
CardLayout c1 = (CardLayout)(cardPanel.getLayout());
c1.show(cardPanel, newCardName);
}
}

Message to JList [duplicate]

This question already has an answer here:
Gui JList ActionListener
(1 answer)
Closed 9 years ago.
hey all goodevening i have a problem about my second button named "Submit" because i cant transfer all information i entered to my null JList in the frame here is my code so far my problem is if i clicked submit my all information will appear in my Message area in frame it needs to be list. thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class vin extends JFrame
{
JLabel lab = new JLabel("Enter Your Name :");
JLabel lab2 = new JLabel("Enter Your Birthday :");
JLabel lab3 = new JLabel("Enter Your Age:");
JLabel lab4 = new JLabel("Enter Your HomeTown:");
JLabel lab5 = new JLabel("Choose Your Department:");
JButton b1 = new JButton("Exit");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextField t3 = new JTextField(15);
JTextField t4 = new JTextField(15);
JButton b2 = new JButton("Submit");
JButton b3 = new JButton("Clear");
JLabel lab6 = new JLabel("Message :");
JList list = new JList();
JPanel panel = new JPanel();
JLabel brief;
public vin()
{
setLocation(500,280);
panel.setLayout(null);
lab.setBounds(10,10,150,20);
t1.setBounds(130,10,150,20);
lab5.setBounds(10,40,150,20);
lab2.setBounds(10,140,150,20);
t2.setBounds(130,140,150,20);
lab3.setBounds(10,170,150,20);
t3.setBounds(110,170,150,20);
lab4.setBounds(10,200,150,20);
t4.setBounds(150,200,150,20);
lab6.setBounds(10,240,150,20);
list.setBounds(50,270,150,20);
list.setSize(250,150);
b1.setBounds(250,470,150,20);
b2.setBounds(60,470,150,20);
b3.setBounds(160,470,150,20);
b1.setSize(60,30);
b2.setSize(75,30);
b3.setSize(65,30);
panel.add(lab);
panel.add(t1);
panel.add(lab5);
panel.add(lab2);
panel.add(t2);
panel.add(t3);
panel.add(t4);
panel.add(lab4);
panel.add(lab3);
panel.add(lab6);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(list);
brief = new JLabel("Goodmorning "+t1+" Today is "+t2+" its your birthday You are now"+t3+" of age You are From"+t4);
getContentPane().add(panel);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b1)
{
System.exit(0);
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b2)
{
list = new JList();
}
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b3)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
}
}
});
}
public static void main(String args [])
{
vin w = new vin();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(400,600);
w.setVisible(true);
}
}
I modified your code so that your list is backed by a Vector which you update when you press the Submit button.
public class Frame extends JFrame
{
JLabel lab = new JLabel("Enter Your Name :");
JLabel lab2 = new JLabel("Enter Your Birthday :");
JLabel lab3 = new JLabel("Enter Your Age:");
JLabel lab4 = new JLabel("Enter Your HomeTown:");
JLabel lab5 = new JLabel("Choose Your Department:");
JButton b1 = new JButton("Exit");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextField t3 = new JTextField(15);
JTextField t4 = new JTextField(15);
JButton b2 = new JButton("Submit");
JButton b3 = new JButton("Clear");
JLabel lab6 = new JLabel("Message :");
Vector vector = new Vector();
JList list = new JList(vector);
JPanel panel = new JPanel();
JLabel brief;
public Frame()
{
setLocation(500,280);
panel.setLayout(null);
lab.setBounds(10,10,150,20);
t1.setBounds(130,10,150,20);
lab5.setBounds(10,40,150,20);
lab2.setBounds(10,140,150,20);
t2.setBounds(130,140,150,20);
lab3.setBounds(10,170,150,20);
t3.setBounds(110,170,150,20);
lab4.setBounds(10,200,150,20);
t4.setBounds(150,200,150,20);
lab6.setBounds(10,240,150,20);
list.setBounds(50,270,150,20);
list.setSize(250,150);
b1.setBounds(250,470,150,20);
b2.setBounds(60,470,150,20);
b3.setBounds(160,470,150,20);
b1.setSize(60,30);
b2.setSize(75,30);
b3.setSize(65,30);
panel.add(lab);
panel.add(t1);
panel.add(lab5);
panel.add(lab2);
panel.add(t2);
panel.add(t3);
panel.add(t4);
panel.add(lab4);
panel.add(lab3);
panel.add(lab6);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(list);
brief = new JLabel("Goodmorning "+t1+" Today is "+t2+" its your birthday You are now"+t3+" of age You are From"+t4);
getContentPane().add(panel);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b1)
{
System.exit(0);
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b2)
{
vector.add(t1.getText() + "-" + t2.getText() + "-" + t3.getText() + "-" + t4.getText());
list.setListData(vector);
list.revalidate();
list.repaint();
}
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b3)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
}
}
});
}
public static void main(String args [])
{
Frame w = new Frame();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(400,600);
w.setVisible(true);
}
}

Confused with Inner Classes, simple actions

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);
}
}
}
}
}
}

Categories

Resources