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.
Related
I'm doing coding for Food Ordering GUI. I would like to ask few questions. I would like to ask that how should I declare variable to hold value for tfPrice1, tfPrice2, tfPrice3? What should I do to make the "Place Order" button so that when it is pressed it will sum up the values contained in the JTextFields? Below is my code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FoodOrder1 extends JFrame
{
JButton riceBtn,noodleBtn,soupBtn;
JTextField display,total,tfPrice1,tfPrice2,tfPrice3;
JPanel mp,p1,p2,p3,p4,p5,p6,p7,p8;
JLabel dsp,ttl,rLbl,nLbl,sLbl,prc1,prc2,prc3;
int rice=3 , noodle=3 , soup=4;
int Total , price1=Integer.parseInt(tfPrice1), price2=Integer.parseInt(tfPrice2) , price3=Integer.parseInt(tfPrice3);
public FoodOrder1()
{
Container pane = getContentPane();
mp = new JPanel();
mp.setLayout(new GridLayout(14,1));
pane.add(mp);
p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
rLbl = new JLabel("Rice");
rLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
riceBtn = new JButton("Fried Rice " + "RM3");
p1.add(riceBtn);
riceBtn.addActionListener(new MyAction());
p1.add(rLbl);
p1.add(riceBtn);
p2 = new JPanel();
p2.setLayout(new GridLayout(1,2));
nLbl = new JLabel("Noodle");
nLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
noodleBtn = new JButton("Tomato Noodle " + "RM3");
noodleBtn.addActionListener(new MyAction());
p2.add(nLbl);
p2.add(noodleBtn);
p3 = new JPanel();
p3.setLayout(new GridLayout(1,2));
sLbl = new JLabel("Soup");
sLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
soupBtn = new JButton("Tomyam Soup " + "RM4");
soupBtn.addActionListener(new MyAction());
p3.add(sLbl);
p3.add(soupBtn);
p4 = new JPanel();
p4.setLayout(new GridLayout(1,2));
prc1 = new JLabel("Price of Fried Rice");
prc1.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice1 = new JTextField(10);
p4.add(prc1);
p4.add(tfPrice1);
tfPrice1.setEditable(false);
p5 = new JPanel();
p5.setLayout(new GridLayout(1,2));
prc2 = new JLabel("Price of Tomato Noodle");
prc2.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice2 = new JTextField(10);
p5.add(prc2);
p5.add(tfPrice2);
tfPrice2.setEditable(false);
p6 = new JPanel();
p6.setLayout(new GridLayout(1,2));
prc3 = new JLabel("Price of Tomyam Soup");
prc3.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice3 = new JTextField(10);
p6.add(prc3);
p6.add(tfPrice3);
tfPrice3.setEditable(false);
p7 = new JPanel();
p7.setLayout(new FlowLayout());
poBtn = new JButton("Place Order");
poBtn.setFont(new Font("Myraid Pro",Font.PLAIN,14));
poBtn.addActionListener(new MyAction2());
rstBtn = new JButton("Reset");
rstBtn.setFont(new Font("Myraid Pro",Font.PLAIN,14));
rstBtn.addActionListener(new MyAction3());
p7.add(poBtn);
p7.add(rstBtn);
p8 = new JPanel();
p8.setLayout(new GridLayout(1,2));
ttl = new JLabel("Total (RM)");
ttl.setFont(new Font("Myraid Pro",Font.BOLD,14));
total = new JTextField(10);
p8.add(ttl);
p8.add(total);
total.setEditable(false);
mp.add(p1);
mp.add(p2);
mp.add(p3);
mp.add(p4);
mp.add(p5);
mp.add(p6);
mp.add(p7);
mp.add(p8);
}
public class MyAction implements ActionListener
{
int counter=0;
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == riceBtn)
{
counter++;
tfPrice1.setText("RM" + String.valueOf(counter*rice));
}
if (e.getSource() == noodleBtn)
{
counter++;
tfPrice2.setText("RM" + String.valueOf(counter*noodle));
}
if (e.getSource() == soupBtn)
{
counter++;
tfPrice3.setText("RM" + String.valueOf(counter*soup));
}
}
}
public class MyAction2 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
price1.setText(String.valueOf(tfPrice1));
price2.setText(String.valueOf(tfPrice2));
price3.setText(String.valueOf(tfPrice3));
Total = price1+price2+price3;
total.setText(String.valueOf(Total));
}
}
public class MyAction3 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == rstBtn)
{
tfPrice1.setText("");
tfPrice2.setText("");
tfPrice3.setText("");
total.setText("");
}
}
}
public static void main(String [] args)
{
FoodOrder1 f = new FoodOrder1();
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(1000,800);
}
}
You don't need a variable to hold the value. Just extract the text from the text boxes whenever you need the value.
double totalPrice = 0.0;
totalPrice += Double.parseDouble(tfPrice1.getText());
totalPrice += Double.parseDouble(tfPrice2.getText());
totalPrice += Double.parseDouble(tfPrice3.getText());
total.setText(String.valueOf(totalPrice));
here is code to hold textfield value to some string
String data = txtdata.getText();
Take data entered to txtdata jTextField into data which is of string datatype
For class I'm supposed to be creating an application that first lets you choose which value you'd like to calculate, then asks to enter the appropriate info. Then when you click "calculate", it SHOULD display the answer. For some reason my JLabel that should be displaying the answer isn't showing up. I've been searching for a solution, but every thing I do, nothing appears after you click "calculate". I am a novice, please help :(
package decay.application;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DecayApplication implements ActionListener {
JFrame frame;
JPanel content;
JLabel prompt1, prompt2, prompt3, prompt4, displayFinal, displayIntitial, displayConstant, choose;
JTextField enterFinal, enterInitial, enterConstant, enterElapsed;
JButton finButton, inButton, conButton, calculate1, calculate2, calculate3;
public DecayApplication(){
frame = new JFrame("Decay Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new JPanel();
content.setLayout(new GridLayout(0, 2, 10, 5));
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
choose = new JLabel("Which would you like to calculate?");
content.add(choose);
finButton = new JButton("Final Amount");
finButton.setActionCommand("finalAmount");
finButton.addActionListener(this);
content.add(finButton);
inButton = new JButton("Initial Amount");
inButton.setActionCommand("initialAmount");
inButton.addActionListener(this);
content.add(inButton);
conButton = new JButton("Constant");
conButton.setActionCommand("constant");
conButton.addActionListener(this);
content.add(conButton);
frame.setContentPane(content);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){new DecayApplication();}
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}
}
}
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
DecayApplication decay = new DecayApplication();
}
}
Here's your method actionPerformed:
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
//here should the if-loop end, because here is the end of instructions which should be called after clicking on the button
}
//and here the second if-loop
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}
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);
}
}
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();
}
});
}
}
I want to round the output to the hundredth place but have failed to do so.
Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment2Part2 extends JFrame{
//window
private static final int WIDTH = 550;
private static final int HEIGHT = 400;
private JLabel firstNameL, lastNameL, milesL, costL, mpgL, dailycostL;//labels for all the variables
private JTextField firstNameTF, lastNameTF, milesTF, costTF, mpgTF, dailycostTF;//text fields for all the variables
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public Assignment2Part2 ()
{
setTitle("Find your daily cost of driving");
//labels
firstNameL = new JLabel("First Name ", SwingConstants.CENTER);
lastNameL = new JLabel("Last Name ",SwingConstants.CENTER);
milesL = new JLabel("Total miles driven per day ",SwingConstants.CENTER);
costL = new JLabel("Cost per gallon of gas ",SwingConstants.CENTER);
mpgL = new JLabel("Average MPG ",SwingConstants.CENTER);
dailycostL = new JLabel("Daily cost of driving is: ",SwingConstants.CENTER);
//text fields
firstNameTF = new JTextField();
lastNameTF = new JTextField();
milesTF = new JTextField();
costTF = new JTextField();
mpgTF = new JTextField();
dailycostTF = new JTextField();
//find button
calculateB = new JButton("Find");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
//exit button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
Container pane = getContentPane();
pane.setLayout(new GridLayout(8, 4));
//panes
pane.add(firstNameL);
pane.add(firstNameTF);
pane.add(lastNameL);
pane.add(lastNameTF);
pane.add(milesL);
pane.add(milesTF);
pane.add(costL);
pane.add(costTF);
pane.add(mpgL);
pane.add(mpgTF);
pane.add(dailycostL);
pane.add(dailycostTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
//find button
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//variables
double first, last, total, cost, averagempg, dailycost;
//strings to doubles
total = Double.parseDouble(milesTF.getText());
cost = Double.parseDouble(costTF.getText());
averagempg = Double.parseDouble(mpgTF.getText());
//calculates cost
dailycost = (total * cost)/averagempg;
//outputs text
dailycostTF.setText("$" + dailycost);
}
}
//exit button
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
public static void main(String[] args){
Assignment2Part2 rectObject = new Assignment2Part2();
}
}
the output line being
dailycostTF.setText("$" + dailycost);
Any help would be great! I am completely new to Java.
An easy way is to use either the number format or decimal format class.
NumberFormat dollars = new NumberFormat.getCurrencyInstance();
Then you can format numbers into dollars quite easily. No clunky "$" needed.
DecimalFormat df = new DecimalFormat("#.##");
dailyCost = Double.valueOf(df.format(dailyCost));