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);
}
}
Related
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.
I am writing an eJuice Calculator. Its nowhere near finished as you will see below. My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
This is a rough draft of code.
package ejuicecalculatorv2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EJuiceCalculatorV2 extends JFrame {
//Form Controls
private JCheckBox isPGbasedNic_CB = new JCheckBox("PG Based NIC");
private JCheckBox isPGbasedFlavor_CB = new JCheckBox("PG Based Flavor");
private JCheckBox isVGbasedNic_CB = new JCheckBox("VG Based NIC");
private JCheckBox isVGbasedFlavor_CB = new JCheckBox("VG Based Flavor");
private JTextField batchSize_TF = new JTextField(5);
private JLabel batchSize_LB = new JLabel("Batch Size:");
private JTextField baseNicStrength_TF = new JTextField(5);
private JLabel baseNicStrength_LB = new JLabel("Base NIC Strength:");
private JTextField targetNicStrength_TF = new JTextField(5);
private JLabel targetNicStrength_LB = new JLabel("Target NIC Strength:");
private JTextField totalNic_TF = new JTextField(5);
private JLabel totalNic_LB = new JLabel("Total NIC:");
private JTextField flavorStrength_TF = new JTextField(5);
private JLabel flavorStrength_LB = new JLabel("Flavoring Strength:");
private JTextField totalFlavor_TF = new JTextField(5);
private JLabel totalFlavor_LB = new JLabel("Total Flavoring:");
private JTextField vgRatio_TF = new JTextField(5);
private JLabel vgRatio_LB = new JLabel("VG Ratio:");
private JTextField pgRatio_TF = new JTextField(5);
private JLabel pgRatio_LB = new JLabel("PG Ratio:");
private JTextField additionalVG_TF = new JTextField(5);
private JLabel additionalVG_LB = new JLabel("Additional VG:");
private JTextField additionalPG_TF = new JTextField(5);
private JLabel additionalPG_LB = new JLabel("Additional PG:");
private JTextField totalVG_TF = new JTextField(5);
private JLabel totalVG_LB = new JLabel("Total VG:");
private JTextField totalPG_TF = new JTextField(5);
private JLabel totalPG_LB = new JLabel("Total PG:");
private JTextField vgBasedIng_TF = new JTextField(5);
private JLabel vgBasedIng_LB = new JLabel("Total VG Ingredients:");
private JTextField pgBasedIng_TF = new JTextField(5);
private JLabel pgBasedIng_LB = new JLabel("Total PG Ingredients:");
//Variables
private boolean _PGnicFlag;
private boolean _VGnicFlag;
private boolean _PGflavorFlag;
private boolean _VGflavorFlag;
private double baseNic;
private double targetNic;
private double totalNic;
private double flavorStrength;
private double totalFlavor;
private double batchSize;
private double totalPG;
private double totalVG;
private double additionalVG;
private double additionalPG;
private double pgBasedIng;
private double vgBasedIng;
private double pgRatio;
private double vgRatio;
public EJuiceCalculatorV2() {
super("EJuice Calculator V2");
setLayout(new FlowLayout());
//Add CheckBoxes
add(isPGbasedNic_CB);
add(isPGbasedFlavor_CB);
add(isVGbasedNic_CB);
add(isVGbasedFlavor_CB);
//Add TextFields and Labels
add(batchSize_LB);
add(batchSize_TF);
add(vgRatio_LB);
add(vgRatio_TF);
add(pgRatio_LB);
add(pgRatio_TF);
add(baseNicStrength_LB);
add(baseNicStrength_TF);
add(targetNicStrength_LB);
add(targetNicStrength_TF);
add(flavorStrength_LB);
add(flavorStrength_TF);
//Add ActionListeners
ActionListener actionListener = new ActionHandler();
isPGbasedNic_CB.addActionListener(actionListener);
isPGbasedFlavor_CB.addActionListener(actionListener);
isVGbasedNic_CB.addActionListener(actionListener);
isVGbasedFlavor_CB.addActionListener(actionListener);
batchSize_TF.addActionListener(actionListener);
vgRatio_TF.addActionListener(actionListener);
pgRatio_TF.addActionListener(actionListener);
baseNicStrength_TF.addActionListener(actionListener);
targetNicStrength_TF.addActionListener(actionListener);
flavorStrength_TF.addActionListener(actionListener);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event){
//if event.getSource() == JCheckBox then execute the following code.
if(checkBox.isSelected()){
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = true;
_VGnicFlag = false;
checkBox = isVGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = true;
_PGnicFlag = false;
checkBox = isPGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = true;
_PGflavorFlag = false;
checkBox = isPGbasedFlavor_CB;
checkBox.setSelected(false);
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = true;
_VGflavorFlag = false;
checkBox = isVGbasedFlavor_CB;
checkBox.setSelected(false);
}
}
else{
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = false;
_VGnicFlag = true;
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = false;
_PGnicFlag = true;
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = false;
_PGflavorFlag = true;
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = false;
_VGflavorFlag = true;
}
}
}
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run (){
new EJuiceCalculatorV2().setVisible(true);
}
});
}
}
My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
You have a bunch of control components, but none appear ones that would initiate an action from the GUI. Rather all of them, the JCheckBoxes and the JTextFields are there to get input, and you appear to be missing one final component, such as a JButton. I would add this component to your GUi, and I would add a single ActionListener to it and it alone. And then when pressed, it would check the state of the check boxes and the text components and then based on their state, give the user the appropriate response.
Also some, if not most or all of the JTextFields, I'd change to either JComboBoxes or JSpinners, to limit the input that the user can enter to something that is allowable since you don't want the user entering "yes" into the "Batch Size" JTextField.
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.JSpinner.DefaultEditor;
#SuppressWarnings("serial")
public class JuiceTwo extends JPanel {
private static final String[] FLAVORS = {"Flavor 1", "Flavor 2", "Flavor 3", "Flavor 4"};
private static final Integer[] ALLOWABLE_BATCH_SIZES = {1, 2, 5, 10, 15, 20};
private static final String[] ALLOWABLE_VG_RATIOS = {"1/4", "1/3", "1/2", "1/1", "2/1", "3/1", "4/1", "8/1", "16/1"};
private List<JCheckBox> flavorBoxes = new ArrayList<>();
private JComboBox<Integer> batchSizeCombo;
private JSpinner vgRatioSpinner;
public JuiceTwo() {
// JPanel to hold the flavor JCheckBoxes
JPanel flavorPanel = new JPanel(new GridLayout(0, 1)); // hold them in vertical grid
flavorPanel.setBorder(BorderFactory.createTitledBorder("Flavors"));
for (String flavor : FLAVORS) {
JCheckBox flavorBox = new JCheckBox(flavor);
flavorBox.setActionCommand(flavor);
flavorPanel.add(flavorBox);
flavorBoxes.add(flavorBox);
}
batchSizeCombo = new JComboBox<>(ALLOWABLE_BATCH_SIZES);
SpinnerListModel vgRatioModel = new SpinnerListModel(ALLOWABLE_VG_RATIOS);
vgRatioSpinner = new JSpinner(vgRatioModel);
JComponent editor = vgRatioSpinner.getEditor();
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setColumns(4);
}
JButton getSelectionButton = new JButton("Get Selection");
getSelectionButton.setMnemonic(KeyEvent.VK_S);
getSelectionButton.addActionListener(new SelectionActionListener());
add(flavorPanel);
add(Box.createHorizontalStrut(20));
add(new JLabel("Batch Size:"));
add(batchSizeCombo);
add(Box.createHorizontalStrut(20));
add(new JLabel("VG Ratio:"));
add(vgRatioSpinner);
add(Box.createHorizontalStrut(20));
add(getSelectionButton);
}
private class SelectionActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox flavorBox : flavorBoxes) {
System.out.printf("%s selected: %b%n", flavorBox.getActionCommand(), flavorBox.isSelected());
}
System.out.println("Batch Size: " + batchSizeCombo.getSelectedItem());
System.out.println("VG Ration: " + vgRatioSpinner.getValue());
System.out.println();
}
}
private static void createAndShowGui() {
JuiceTwo mainPanel = new JuiceTwo();
JFrame frame = new JFrame("JuiceTwo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
I am in the process of building a Geometric Calculator, but am having difficult implementing the ActionListener. I found some sample code on the Oracle site and modified to fit the visual concept I am trying to do.
I combed through my code looking for typos and incorrect punctuation and either corrected it or did not find anything that stuck out to me. I looked at similar questions on Stack Overflow and in text books, and my code looks similar in structure to what is being done in the examples. I have pasted the relevant section of the code below.
Eclipse gives me this error message: Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
CalcButtonListenerA cannot be resolved to a type I don't understand why this is happening. I thought these lines would take care of resolving the type:
`calcButton1 = new JButton("Calculate");
calcButton1.addActionListener(new CalcButtonListenerA());`
The other relevant code is below...
package layout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GeometryCalculator implements ItemListener {
JPanel calcTools;
final static String CIRCLEPANEL = "Circle Calculator";
final static String RECTANGLEPANEL = "Rectangle Calculator";
final static String TRIANGLEPANEL = "Triangle Calculator";
private JLabel messageLabel1;
private JLabel messageLabel2;
private JLabel messageLabel3;
private JLabel radiusLabel;
private JLabel baseLabel;
private JLabel heightLabel;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel circleAreaLabel;
private JLabel circumferenceLabel;
private JLabel rectanglePerimeterLabel;
private JLabel rectangleAreaLabel;
private JLabel triangleAreaLabel;
private JTextField choiceTextField;
private JTextField radiusTextField;
private JTextField baseTextField;
private JTextField heightTextField;
private JTextField lengthTextField;
private JTextField widthTextField;
private JButton calcButton1;
private JButton calcButton2;
private JButton calcButton3;
JTextField rectanglePerimeterField = new JTextField(15);
JTextField rectangleAreaField = new JTextField(15);
JTextField triangleAreaField = new JTextField(15);
public void addComponentToPane(Container pane) {
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = { CIRCLEPANEL, RECTANGLEPANEL, TRIANGLEPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
//Create the "calcTools".
JPanel calcTool1 = new JPanel();
radiusLabel = new JLabel("Radius");
circumferenceLabel = new JLabel("Circumference");
circleAreaLabel = new JLabel("Area");
radiusTextField= new JTextField(10);
messageLabel1 = new JLabel("Let's make some circle calculations.");
final JTextField circumferenceField = new JTextField(15);
circumferenceField.setEditable(false);
final JTextField circleAreaField = new JTextField(15);
circleAreaField.setEditable(false);
calcButton1 = new JButton("Calculate");
calcButton1.addActionListener(new CalcButtonListenerA());
calcTool1.add(messageLabel1);
calcTool1.add(radiusLabel);
calcTool1.add(radiusTextField);
calcTool1.add(circumferenceLabel);
calcTool1.add(circumferenceField);
calcTool1.add(circleAreaLabel);
calcTool1.add(circleAreaField);
calcTool1.add(calcButton1);
class CalcButtonListenerA implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String radius;
double circumference;
double circleArea;
radius = radiusTextField.getText();
circumference = 2*Double.parseDouble(radius)*Math.PI;
String circ = String.valueOf(circumference);
circleArea = Double.parseDouble(radius)* Double.parseDouble(radius)*Math.PI;
String area = String.valueOf(circleArea);
circumferenceField.setText(circ);
circleAreaField.setText(area);
}
}
JPanel calcTool2 = new JPanel();
messageLabel2 = new JLabel("Let's make some rectangle calculations.");
lengthLabel = new JLabel("Length");
widthLabel = new JLabel("Width");
lengthTextField = new JTextField(10);
widthTextField = new JTextField(10);
rectanglePerimeterLabel = new JLabel("Perimeter");
rectangleAreaLabel = new JLabel("Area");
JTextField rectanglePerimeterField = new JTextField(15);
rectanglePerimeterField.setEditable(false);
JTextField rectangleAreaField = new JTextField(15);
rectangleAreaField.setEditable(false);
JButton calcButton2 = new JButton("Calculate");
calcTool2.add(messageLabel2);
calcTool2.add(lengthLabel);
calcTool2.add(lengthTextField);
calcTool2.add(widthLabel);
calcTool2.add(widthTextField);
calcTool2.add(rectanglePerimeterLabel);
calcTool2.add(rectanglePerimeterField);
calcTool2.add(rectangleAreaLabel);
calcTool2.add(rectangleAreaField);
calcTool2.add(calcButton2);
JPanel calcTool3 = new JPanel();
messageLabel3 = new JLabel("Let's make some triangle calculations");
baseLabel = new JLabel("Base");
heightLabel = new JLabel("Height");
baseTextField = new JTextField(10);
heightTextField = new JTextField(10);
triangleAreaLabel = new JLabel("Area");
triangleAreaField = new JTextField(15);
triangleAreaField.setEditable(false);
JButton calcButton3 = new JButton("calculate");
calcTool3.add(messageLabel3);
calcTool3.add(baseLabel);
calcTool3.add(baseTextField);
calcTool3.add(heightLabel);
calcTool3.add(heightTextField);
calcTool3.add(triangleAreaLabel);
calcTool3.add(triangleAreaField);
calcTool3.add(calcButton3);
calcTools = new JPanel(new CardLayout());
calcTools.add(calcTool1, CIRCLEPANEL);
calcTools.add(calcTool2, RECTANGLEPANEL);
calcTools.add(calcTool3, TRIANGLEPANEL);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(calcTools, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(calcTools.getLayout());
cl.show(calcTools, (String)evt.getItem());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Geometry Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GeometryCalculator demo = new GeometryCalculator();
demo.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
UIManager.put("swing.boldMetal", Boolean.FALSE);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The compile error simply says that at that point the compiler does not know what CalcButtonListenerA means. You define the class CalcButtonListenerA inside the method addComponentToPane however the definition is placed after the usage so at that moment the class is not yet defined, this is somewhat equivalent to what would happen with a variable, you can't do the following:
int y = x + 5; //what is x?
int x = 10; //even if it's defined below, compiler error
You can do this properly in a few ways:
Define it in the method, as a "local class" but before the usage:
public void addComponentToPane(Container pane) {
class CalcButtonListenerA implements ActionListener
{
//...
}
//...
calcButton1.addActionListener(new CalcButtonListenerA());
}
Define it in the class GeometryCalculator not in the method:
public class GeometryCalculator implements ItemListener {
public void addComponentToPane(Container pane) {
//...
calcButton1.addActionListener(new CalcButtonListenerA());
}
private class CalcButtonListenerA implements ActionListener
{
//...
}
}
Define it as an anonymous class, this is a compact way to do it if you don't want to use that code in any other actionListener.
public void addComponentToPane(Container pane) {
//...
calcButton1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//the actionPerformed code of CalcButtonListenerA
}
});
}
If it was a very important class you could also place it in its own file and import it here.
Don't define a method inside a method.
Use an anonymous class like this (much cleaner) :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GeometryCalculator implements ItemListener {
JPanel calcTools;
final static String CIRCLEPANEL = "Circle Calculator";
final static String RECTANGLEPANEL = "Rectangle Calculator";
final static String TRIANGLEPANEL = "Triangle Calculator";
private JLabel messageLabel1;
private JLabel messageLabel2;
private JLabel messageLabel3;
private JLabel radiusLabel;
private JLabel baseLabel;
private JLabel heightLabel;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel circleAreaLabel;
private JLabel circumferenceLabel;
private JLabel rectanglePerimeterLabel;
private JLabel rectangleAreaLabel;
private JLabel triangleAreaLabel;
private JTextField choiceTextField;
private JTextField radiusTextField;
private JTextField baseTextField;
private JTextField heightTextField;
private JTextField lengthTextField;
private JTextField widthTextField;
private JButton calcButton1;
private JButton calcButton2;
private JButton calcButton3;
JTextField rectanglePerimeterField = new JTextField(15);
JTextField rectangleAreaField = new JTextField(15);
JTextField triangleAreaField = new JTextField(15);
public void addComponentToPane(Container pane) {
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = { CIRCLEPANEL, RECTANGLEPANEL, TRIANGLEPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
//Create the "calcTools".
JPanel calcTool1 = new JPanel();
radiusLabel = new JLabel("Radius");
circumferenceLabel = new JLabel("Circumference");
circleAreaLabel = new JLabel("Area");
radiusTextField= new JTextField(10);
messageLabel1 = new JLabel("Let's make some circle calculations.");
final JTextField circumferenceField = new JTextField(15);
circumferenceField.setEditable(false);
final JTextField circleAreaField = new JTextField(15);
circleAreaField.setEditable(false);
calcButton1 = new JButton("Calculate");
calcButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String radius;
double circumference;
double circleArea;
radius = radiusTextField.getText();
circumference = 2*Double.parseDouble(radius)*Math.PI;
String circ = String.valueOf(circumference);
circleArea = Double.parseDouble(radius)* Double.parseDouble(radius)*Math.PI;
String area = String.valueOf(circleArea);
circumferenceField.setText(circ);
circleAreaField.setText(area);
}
});
// class CalcButtonListenerA implements ActionListener
// {
//
// public void actionPerformed(ActionEvent e)
// {
// String radius;
// double circumference;
// double circleArea;
//
// radius = radiusTextField.getText();
// circumference = 2*Double.parseDouble(radius)*Math.PI;
// String circ = String.valueOf(circumference);
// circleArea = Double.parseDouble(radius)* Double.parseDouble(radius)*Math.PI;
// String area = String.valueOf(circleArea);
//
// circumferenceField.setText(circ);
// circleAreaField.setText(area);
//
// }
// }
calcTool1.add(messageLabel1);
calcTool1.add(radiusLabel);
calcTool1.add(radiusTextField);
calcTool1.add(circumferenceLabel);
calcTool1.add(circumferenceField);
calcTool1.add(circleAreaLabel);
calcTool1.add(circleAreaField);
calcTool1.add(calcButton1);
JPanel calcTool2 = new JPanel();
messageLabel2 = new JLabel("Let's make some rectangle calculations.");
lengthLabel = new JLabel("Length");
widthLabel = new JLabel("Width");
lengthTextField = new JTextField(10);
widthTextField = new JTextField(10);
rectanglePerimeterLabel = new JLabel("Perimeter");
rectangleAreaLabel = new JLabel("Area");
JTextField rectanglePerimeterField = new JTextField(15);
rectanglePerimeterField.setEditable(false);
JTextField rectangleAreaField = new JTextField(15);
rectangleAreaField.setEditable(false);
JButton calcButton2 = new JButton("Calculate");
calcTool2.add(messageLabel2);
calcTool2.add(lengthLabel);
calcTool2.add(lengthTextField);
calcTool2.add(widthLabel);
calcTool2.add(widthTextField);
calcTool2.add(rectanglePerimeterLabel);
calcTool2.add(rectanglePerimeterField);
calcTool2.add(rectangleAreaLabel);
calcTool2.add(rectangleAreaField);
calcTool2.add(calcButton2);
JPanel calcTool3 = new JPanel();
messageLabel3 = new JLabel("Let's make some triangle calculations");
baseLabel = new JLabel("Base");
heightLabel = new JLabel("Height");
baseTextField = new JTextField(10);
heightTextField = new JTextField(10);
triangleAreaLabel = new JLabel("Area");
triangleAreaField = new JTextField(15);
triangleAreaField.setEditable(false);
JButton calcButton3 = new JButton("calculate");
calcTool3.add(messageLabel3);
calcTool3.add(baseLabel);
calcTool3.add(baseTextField);
calcTool3.add(heightLabel);
calcTool3.add(heightTextField);
calcTool3.add(triangleAreaLabel);
calcTool3.add(triangleAreaField);
calcTool3.add(calcButton3);
calcTools = new JPanel(new CardLayout());
calcTools.add(calcTool1, CIRCLEPANEL);
calcTools.add(calcTool2, RECTANGLEPANEL);
calcTools.add(calcTool3, TRIANGLEPANEL);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(calcTools, BorderLayout.CENTER);
}
// class CalcButtonListenerA implements ActionListener
// {
//
// public void actionPerformed(ActionEvent e)
// {
// String radius;
// double circumference;
// double circleArea;
//
// radius = radiusTextField.getText();
// circumference = 2*Double.parseDouble(radius)*Math.PI;
// String circ = String.valueOf(circumference);
// circleArea = Double.parseDouble(radius)* Double.parseDouble(radius)*Math.PI;
// String area = String.valueOf(circleArea);
//
// circumferenceField.setText(circ);
// circleAreaField.setText(area);
//
// }
// }
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(calcTools.getLayout());
cl.show(calcTools, (String)evt.getItem());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Geometry Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GeometryCalculator demo = new GeometryCalculator();
demo.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
UIManager.put("swing.boldMetal", Boolean.FALSE);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Can anyone tell me why my change QTY button isnt changing the QTY?
The buttonlistener2 is supposed to change the number of items in arrayCount[x]
to the number in the count JTextfield, but its not, could use a new set of eyes.
thanks all
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ProduceInventory extends JFrame
{
ArrayList<String> arrayName = new ArrayList<String>();
ArrayList<Integer> arrayCount = new ArrayList<Integer>();
// declares panels and items
private final int WINDOW_WIDTH = 450;
private final int WINDOW_HEIGHT = 350;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JLabel messageLabel1;
private JLabel messageLabel2;
private JTextField name;
private JTextField count;
private JTextArea output;
private JButton add;
private JButton changeQTY;
private JButton delete;
private JButton clear;
private JButton report;
private JButton save;
private JButton load;
public ProduceInventory()
{
//creates Jframe
setTitle("Produce Inventory");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1(); //build panels
panel2();
panel3();
add(panel1, BorderLayout.NORTH); //add panels
add(panel2, BorderLayout.SOUTH);
add(panel3, BorderLayout.CENTER);
setVisible(true);
}
private void panel1() //builds panel 1
{
messageLabel1 = new JLabel("Name");
messageLabel2 = new JLabel("Count");
name = new JTextField(20);
count = new JTextField(5);
panel1 = new JPanel();
panel1.add(messageLabel1);
panel1.add(name);
panel1.add(messageLabel2);
panel1.add(count);
}
private void panel2() //builds panel 2
{
add = new JButton("Add");
changeQTY = new JButton("CHANGE QTY");
delete = new JButton("Delete");
clear = new JButton("Clear");
report = new JButton("Report");
save = new JButton("Save File");
load = new JButton("Load File");
add.addActionListener(new ButtonListener());
changeQTY.addActionListener(new ButtonListener2());
panel2 = new JPanel();
panel2.setLayout(new GridLayout(2,4));
panel2.add(add);
panel2.add(changeQTY);
panel2.add(delete);
panel2.add(clear);
panel2.add(report);
panel2.add(save);
panel2.add(load);
}
private void panel3() //builds panel 3
{
output = new JTextArea(10,30);
panel3 = new JPanel();
panel3.add(output);
}
private class ButtonListener implements ActionListener //add listener
{
String nameIn;
String countIn;
int number;
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
nameIn = name.getText();
arrayName.add(name.getText());
countIn = count.getText();
number = Integer.parseInt(countIn);
arrayCount.add(number);
output.setText(name.getText() + " " + count.getText() + " Item Added");
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
private class ButtonListener2 implements ActionListener //add listener
{
public void actionPerformed(ActionEvent e)
{
String nameIn;
String countIn;
int number;
String actionCommand = e.getActionCommand();
if (actionCommand.equals("CHANGE QTY"))
{
nameIn = name.getText();
countIn = count.getText();
number = Integer.parseInt(countIn);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
if(arrayName.get(x) == nameIn)
{
arrayCount.set(x, number);
}
}
output.setText("Qty is updated to: " + number);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ProduceInventory(); //runs program
}
}
In the action listener, on the line
if(arrayName.get(x) == nameIn)
you are checking if the two variables refer to the same object. Instead of that you have to check if the objects they refer to are equal:
if(nameIn.equals(arrayName.get(x)))
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class Final extends JFrame
{
private JButton calcButton, exitButton;
private JButton pcalcButton, pexitButton;
private JTextField plength, pwidth, pdepth, pvolume;
private JTextField hlength, hwidth, hdepth, hvolume;
private JLabel lengthLabel, widthLabel, depthLabel, volumeLabel;
private JRadioButton roundrButton, ovalrButton;
public Final()
{
super( "Final" );
JTabbedPane tab = new JTabbedPane();
// constructing the first panel
JPanel p1 = new JPanel(new GridLayout(5,1));
pcalcButton = new JButton("Calculate Volume");
pexitButton = new JButton("Exit");
plength = new JTextField(5);
pwidth = new JTextField(5);
pdepth = new JTextField(5);
pvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the pool's length (ft):");
widthLabel = new JLabel("Enter the pool's width (ft):");
depthLabel = new JLabel("Enter the pool's depth (ft):");
volumeLabel = new JLabel("The pool's volume (ft^3):");
p1.add(lengthLabel);
p1.add(plength);
p1.add(widthLabel);
p1.add(pwidth);
p1.add(depthLabel);
p1.add(pdepth);
p1.add(volumeLabel);
p1.add(pvolume);
p1.add(pcalcButton);
p1.add(pexitButton);
tab.addTab( "Pools", null, p1, " Panel #1" );
calcButtonHandler chandler =new calcButtonHandler();
pcalcButton.addActionListener(chandler);
exitButtonHandler ehandler =new exitButtonHandler();
pexitButton.addActionListener(ehandler);
FocusHandler fhandler =new FocusHandler();
plength.addFocusListener(fhandler);
pwidth.addFocusListener(fhandler);
pdepth.addFocusListener(fhandler);
pvolume.addFocusListener(fhandler);
// constructing the second panel
JPanel p2 = new JPanel(new GridLayout(6,1));
ButtonGroup tubtype = new ButtonGroup();
roundrButton = new JRadioButton("Round", true);
roundrButton.setActionCommand("round");
tubtype.add(roundrButton);
ovalrButton = new JRadioButton("Oval", false);
ovalrButton.setActionCommand("oval");
tubtype.add(ovalrButton);
calcButton = new JButton("Calculate Volume");
exitButton = new JButton("Exit");
hlength = new JTextField(5);
hwidth = new JTextField(5);
hdepth = new JTextField(5);
hvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the tub's length (ft):");
widthLabel = new JLabel("Enter the tub's width (ft):");
depthLabel = new JLabel("Enter the tub's depth (ft):");
volumeLabel = new JLabel("The tub's volume (ft^3):");
p2.add(roundrButton);
p2.add(ovalrButton);
p2.add(lengthLabel);
p2.add(hlength);
p2.add(widthLabel);
p2.add(hwidth);
p2.add(depthLabel);
p2.add(hdepth);
p2.add(volumeLabel);
p2.add(hvolume);
p2.add(calcButton);
p2.add(exitButton);
tab.addTab( "Hot Tubs", null, p2, " Panel #1" );
calcButtonHandler2 ihandler =new calcButtonHandler2();
calcButton.addActionListener(ihandler);
exitButtonHandler ghandler =new exitButtonHandler();
exitButton.addActionListener(ghandler);
FocusHandler hhandler =new FocusHandler();
hlength.addFocusListener(hhandler);
hwidth.addFocusListener(hhandler);
hdepth.addFocusListener(hhandler);
hvolume.addFocusListener(hhandler);
// add JTabbedPane to container
getContentPane().add( tab );
setSize( 550, 500 );
setVisible( true );
}
public class calcButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
DecimalFormat num =new DecimalFormat(",###.##");
double sLength, sWidth, sdepth, Total;
sLength = Double.parseDouble(plength.getText());
sWidth = Double.parseDouble(pwidth.getText());
sdepth = Double.parseDouble(pdepth.getText());
if(e.getSource() == pcalcButton) {
Total = sLength * sWidth * sdepth;
pvolume.setText(num.format(Total));
try{
String value=pvolume.getText();
File file = new File("output.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Length= "+sLength+", Width= "+sWidth+", Depth= "+sdepth+" so the volume of Swimming Pool is "+value);
out.newLine();
out.close();
}
catch(Exception ex){}
}
}
}
public class calcButtonHandler2 implements ActionListener {
public void actionPerformed(ActionEvent g) {
DecimalFormat num =new DecimalFormat(",###.##");
double cLength, cWidth, cdepth, Total;
cLength = Double.parseDouble(hlength.getText());
cWidth = Double.parseDouble(hwidth.getText());
cdepth = Double.parseDouble(hdepth.getText());
try
{
if(roundrButton.isSelected())//**roundrButton cannot be resolved
{
Total = Math.PI * Math.pow(cLength / 2.0, 2) * cdepth;
}
else
{
Total = Math.PI * Math.pow(cLength * cWidth, 2) * cdepth;
}
hvolume.setText(""+num.format(Total));
}
catch(Exception ex){}
}
}
}
public class exitButtonHandler implements ActionListener { //**The public type exitButtonHandler must be defined in its own file
public void actionPerformed(ActionEvent g){
System.exit(0);
}
}
public class FocusHandler implements FocusListener { //**The public type FocusHandler must be defined in its own file
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
public static void main( String args[] )
{
Final tabs = new Final();
tabs.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
I am getting 3 errors, denoted by the //** next to the lines. Please help me to figure out the problems I am having.
Change calcButtonHandler2 definition to accept a reference to roundButton from where it's defined.
public class calcButtonHandler2 implements ActionListener {
private final JRadioButton roundrButton;
public calcButtonHandler(JRadioButton roundrButton)
{
this.roundrButton= roundrButton;
}
....
}
and pass in the reference when you create an instance of calcButtonHandler2
calcButtonHandler chandler =new calcButtonHandler(roundrButton);
And as for the last two error, move the class declarations to separate files as called out by the compilation error or remove the public keyword from their definitions (I would recommend the first method).
First of all write all the classes in their separate .java files.
The JRadioButton roundrButton is declared in the class Final so it cannot be accessed from another class calcButtonHandler2 directly.
You need to use an object of the class Final to access it or you can make use of inner classes to access it.