I have values set for each of the car buying options but when I click the button I keep getting 0. I can't get fP to update after I declare it. Here is my code:
public class CarOptions extends JFrame {
//All the Buttons needed
private JComboBox colorOptions;
private JRadioButton leatherInt;
private JRadioButton touchScreen;
private JRadioButton premiumSound;
private JRadioButton bodyKit;
//Car prices
int cP = 1000;
int eng1 = 6000;
int eng2 = 8000;
int eng3 = 12000;
int acc1 = 600;
int acc2 = 800;
int acc3 = 3000;
int acc4 = 1200;
int fP;
public CarOptions(){
createControlPanel();
}
public void createControlPanel(){
//Panel for all the options
JPanel colorOptions1 = createComboBox();
JPanel sportsOptions = createCheckBoxes();
JPanel accOptions = createRadioButtons();
JPanel finalPrice1 = createButton();
//Line up the panels
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(4,1));
controlPanel.add(colorOptions1);
controlPanel.add(sportsOptions);
controlPanel.add(accOptions);
controlPanel.add(finalPrice1);
add(controlPanel, BorderLayout.SOUTH);
}
public JPanel createComboBox(){
colorOptions = new JComboBox();
colorOptions.addItem("Black");
colorOptions.addItem("Yellow");
colorOptions.addItem("Blue");
colorOptions.addItem("Red");
JPanel panel = new JPanel();
panel.add(colorOptions);
return panel;
}
public JPanel createCheckBoxes(){
ButtonGroup group = new ButtonGroup();
AbstractButton hybrid = new JCheckBox("Hybrid");
AbstractButton base = new JCheckBox("Base Model");
AbstractButton sport = new JCheckBox("Sport");
group.add(hybrid);
group.add(base);
group.add(sport);
if (hybrid.isSelected()){
fP = fP + eng1;
}
else if (base.isSelected()){
fP = fP + eng2;
}
else if (sport.isSelected()){
fP = fP + eng3;
}
JPanel panel = new JPanel();
panel.add(hybrid);
panel.add(base);
panel.add(sport);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Engine Package"));
return panel;
}
public JPanel createRadioButtons(){
leatherInt = new JRadioButton("Leather Interior");
touchScreen = new JRadioButton("Touchscreen Radio");
premiumSound = new JRadioButton("Premium Sound System");
bodyKit = new JRadioButton("Body Kit");
if (leatherInt.isSelected()){
fP = cP + acc1;
}
else if (touchScreen.isSelected()){
fP = cP + acc2;
}
else if (premiumSound.isSelected()){
fP = cP + acc3;
}
else if (bodyKit.isSelected()){
fP = cP + acc4;
}
JPanel panel = new JPanel();
panel.add(leatherInt);
panel.add(touchScreen);
panel.add(premiumSound);
panel.add(bodyKit);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Accesories"));
return panel;
}
public JPanel createButton(){
JButton finalPrice = new JButton("Final Price");
finalPrice.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFrame fPFrame = new JFrame();
fPFrame.setSize(200,100);
fPFrame.setTitle("Final Price");
fPFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
fPFrame.setVisible(true);
JLabel fPLabel = new JLabel("Your final price is: $" + fP);
JPanel fPPanel = new JPanel();
fPPanel.add(fPLabel);
fPFrame.add(fPPanel);
}
});
JPanel panel = new JPanel();
panel.add(finalPrice);
return panel;
}
}
You get 0, because to don't calculate the price "when the button is clicked".
You are trying to calculate the price when you create the buttons. The problem is the user hasn't done anything yet. The price can only be calculated in response to an event.
So all your price calculation code needs to be moved to the ActionListener
You did the calculation only once, based on empty controls Here's a fix:
//All the Buttons needed
private JComboBox<String> colorOptions;
private JRadioButton leatherInt;
private JRadioButton touchScreen;
private JRadioButton premiumSound;
private JRadioButton bodyKit;
//Car prices
int cP = 1000;
int eng1 = 6000;
int eng2 = 8000;
int eng3 = 12000;
int acc1 = 600;
int acc2 = 800;
int acc3 = 3000;
int acc4 = 1200;
int fP;
public CarOptions(){
createControlPanel();
}
public void createControlPanel(){
//Panel for all the options
JPanel colorOptions1 = createComboBox();
JPanel sportsOptions = createCheckBoxes();
JPanel accOptions = createRadioButtons();
JPanel finalPrice1 = createButton();
//Line up the panels
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(4,1));
controlPanel.add(colorOptions1);
controlPanel.add(sportsOptions);
controlPanel.add(accOptions);
controlPanel.add(finalPrice1);
add(controlPanel, BorderLayout.SOUTH);
}
public JPanel createComboBox(){
colorOptions = new JComboBox<>();
colorOptions.addItem("Black");
colorOptions.addItem("Yellow");
colorOptions.addItem("Blue");
colorOptions.addItem("Red");
JPanel panel = new JPanel();
panel.add(colorOptions);
return panel;
}
public JPanel createCheckBoxes(){
ButtonGroup group = new ButtonGroup();
AbstractButton hybrid = new JCheckBox("Hybrid");
AbstractButton base = new JCheckBox("Base Model");
AbstractButton sport = new JCheckBox("Sport");
group.add(hybrid);
group.add(base);
group.add(sport);
if (hybrid.isSelected()){
fP = fP + eng1;
}
else if (base.isSelected()){
fP = fP + eng2;
}
else if (sport.isSelected()){
fP = fP + eng3;
}
JPanel panel = new JPanel();
panel.add(hybrid);
panel.add(base);
panel.add(sport);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Engine Package"));
return panel;
}
public JPanel createRadioButtons(){
leatherInt = new JRadioButton("Leather Interior");
touchScreen = new JRadioButton("Touchscreen Radio");
premiumSound = new JRadioButton("Premium Sound System");
bodyKit = new JRadioButton("Body Kit");
recalculate();
JPanel panel = new JPanel();
panel.add(leatherInt);
panel.add(touchScreen);
panel.add(premiumSound);
panel.add(bodyKit);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Accesories"));
return panel;
}
public JPanel createButton(){
JButton finalPrice = new JButton("Final Price");
finalPrice.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
recalculate();
JFrame fPFrame = new JFrame();
fPFrame.setSize(200,100);
fPFrame.setTitle("Final Price");
fPFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
fPFrame.setVisible(true);
JLabel fPLabel = new JLabel("Your final price is: $" + fP);
JPanel fPPanel = new JPanel();
fPPanel.add(fPLabel);
fPFrame.add(fPPanel);
}
});
JPanel panel = new JPanel();
panel.add(finalPrice);
return panel;
}
private void recalculate() {
if (leatherInt.isSelected()){
fP = cP + acc1;
}
else if (touchScreen.isSelected()){
fP = cP + acc2;
}
else if (premiumSound.isSelected()){
fP = cP + acc3;
}
else if (bodyKit.isSelected()){
fP = cP + acc4;
}
}
Related
my GUI program is about writing a psychology quiz for my class. It uses swing but I am getting two errors on terminal and I'm not sure what the problem is. Can I know what my error is?
MyGuiProject.java:78: error: ';' expected
int JLabel scoreK = new JLabel("Your score is " + score + ".");
^
MyGuiProject.java:78: error: <identifier> expected
int JLabel scoreK = new JLabel("Your score is " + score + ".");
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyGuiProject
extends JFrame implements ActionListener
{
//instance variables
//JFrame
private JFrame frame1 = new JFrame("Psychology Quiz");
private JFrame frame2 = new JFrame("Solutions");
//JPanel (p1 = panel 1)
private JPanel p1 = new JPanel();
private JPanel p2 = new JPanel();
private JPanel p3 = new JPanel();
//Fonts (f1 = font 1)
private Font f1 = new Font("Times New Roman", Font.BOLD, 30);
private Font f2 = new Font("Arial", Font.ITALIC, 30);
//Description (d1 = description)
private JLabel d1 = new JLabel("Psychology - Classical Conditioning");
//questions (q1 = question 1)
private JLabel q1 = new JLabel("Any behavior or action is...");
private JLabel q2 = new JLabel(
"All mental process associated with thinking, knowing, and remembering is...");
private JLabel q3 = new JLabel("American psychologist and founder of behaviorism is...");
//answers (a1 = answer 1)
private JButton a1 = new JButton("response");
private JButton a2 = new JButton("reaction");
private JButton a3 = new JButton("stimulus");
private JButton b1 = new JButton("recognition");
private JButton b2 = new JButton("cognition");
private JButton b3 = new JButton("classical conditioning");
private JButton c1 = new JButton("John B. Watson");
private JButton c2 = new JButton("Mr. Morgan");
private JButton c3 = new JButton("Mr. Ansari");
//Images
private ImageIcon image1 = new ImageIcon("ang.jpg");
private ImageIcon image2 = new ImageIcon("psych.jpg");
//JMenu
private JMenuBar ppap = new JMenuBar();
private JMenu menu1 = new JMenu("Questions");
private JMenuItem item1 = new JMenuItem("1");
private JMenuItem item2 = new JMenuItem("2");
private JMenuItem item3 = new JMenuItem("3");
//Solutions (s1 = solution 1)
private JLabel s1 = new JLabel(
"Answers: 1) response || 2) cognition || 3) John B. Watson (unfortunately)");
//Another program for adding points and label for adding points
int score = 0;
int JLabel scoreK = new JLabel("Your score is " + score + ".");
ScoreKeeper ang1 = new ScoreKeeper();
public void angWindow()
{
//setting frame
frame1.setBounds(0, 0, 300, 400);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//addActionListener for JButton and JMenuItem
a1.addActionListener(this);
a2.addActionListener(this);
a3.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
item1.addActionListener(this);
item2.addActionListener(this);
item3.addActionListener(this);
//setting font
d1.setFont(f1);
scoreK.setFont(f2);
//JPanel for questions
p1.add(a1);
p1.add(a2);
p1.add(a3);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p3.add(c1);
p3.add(c2);
p3.add(c3);
//JMenu on JMenuBar
ppap.add(menu1);
//setting frame again
frame1.setJMenuBar(ppap);
frame1.add(q1, BorderLayout.SOUTH);
frame1.add(p1, BorderLayout.NORTH);
frame1.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command.equals("response"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q1);
frame1.remove(p1);
frame1.add(p2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("reaction"))
{
frame1.remove(p1);
frame1.remove(q1);
frame1.add(p2, BorderLayout.NORTH);
frame1.add(q2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("stimulus"))
{
frame1.remove(p1);
frame1.remove(q1);
frame1.add(p2, BorderLayout.NORTH);
frame1.add(q2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("recognition"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q2);
frame1.remove(p2);
frame1.add(p3, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("cognition"))
{
frame1.add(q3, BorderLayout.NORTH);
frame1.remove(q2);
frame1.add(p3, BorderLayout.SOUTH);
frame1.validate();
frame1.repaint();
}
if(command.equals("classical conditioning"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q2);
frame1.remove(p2);
frame1.add(p3, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("John B. Watson"))
{
frame1.remove(q3);
frame1.remove(p3);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
frame2.setVisible(true);
}
if(command.equals("..."))
{
frame1.remove(p3);
frame1.remove(q3);
frame1.validate();
frame1.repaint();
score = ang1.trackScore(score);
frame2.setVisible(true);
}
if(command.equals("..."))
{
frame1.remove(p3);
frame1.remove(q3);
frame1.validate();
frame1.repaint();
score = ang1.trackScore(score);
frame2.setVisible(true);
}
frame1.remove(scoreK);
scoreK.setText("Your score is " + score + ".");
frame1.add(scoreK, BorderLayout.CENTER);
}
public static void main(String[] args)
{
MyGuiProject angBaby = new MyGuiProject();
angBaby.setWindow();
}
}
public class ScoreKeeper
{
public int trackScore(int score)
{
score = score + 2;
return score;
}
}
Is this an int or a JLabel ?
int JLabel scoreK = new JLabel("Your score is " + score + ".");
try
JLabel scoreK = new JLabel("Your score is " + score + ".");
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
How can I set a button to link to a completely different grid pane? If I click the JButton "More options" for example, I want it to link me to a new page with more JButton options. Right now, everything is static.
The program right now just calculates the area of a rectangle given an length and width when you press "Calculate." The grid layout is 4 x 2, denoted by JLabel, JTextField, and JButton listed below.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private JButton calculateB, exitB;
//Button handlers:
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public RectangleProgram()
{
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
//SPecify handlers for each button and add (register) ActionListeners to each button.
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Sample Title: Area of a Rectangle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}
}
You can use CardLayout. It allows the two or more components share the same display space.
Here is a simple example
public class RectangleProgram {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Area of a Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField lengthField = new JTextField(10);
JTextField widthField = new JTextField(10);
JTextField areaField = new JTextField(10);
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
final JPanel content = new JPanel(new CardLayout());
JButton optionsButton = new JButton("More Options");
optionsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) content.getLayout();
cardLayout.next(content);
}
});
JPanel panel = new JPanel(new GridLayout(0, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
};
panel.add(new JLabel("Enter the length: ", JLabel.RIGHT));
panel.add(lengthField);
panel.add(new JLabel("Enter the width: ", JLabel.RIGHT));
panel.add(widthField);
panel.add(new JLabel("Area: ", JLabel.RIGHT));
panel.add(areaField);
panel.add(calculateButton);
panel.add(exitButton);
JPanel optionsPanel = new JPanel();
optionsPanel.add(new JLabel("Options", JLabel.CENTER));
content.add(panel, "Card1");
content.add(optionsPanel, "Card2");
frame.add(content);
frame.add(optionsButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
Read How to Use CardLayout
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class filecabinet extends JFrame implements ActionListener {
private String folder = "";
//create buttons
private JButton a = new JButton("A");
private JButton b = new JButton("B");
private JButton c = new JButton("C");
private JButton d = new JButton("D");
private JButton e = new JButton("E");
private JButton f = new JButton("F");
private JButton g = new JButton("G");
private JButton h = new JButton("H");
private JButton i = new JButton("I");
private JButton j = new JButton("J");
private JButton k = new JButton("K");
private JButton l = new JButton("L");
private JButton m = new JButton("M");
private JButton n = new JButton("N");
private JButton o = new JButton("O");
private JButton p = new JButton("P");
private JButton q = new JButton("Q");
private JButton r = new JButton("R");
private JButton s = new JButton("S");
private JButton t = new JButton("T");
private JButton u = new JButton("U");
private JButton v = new JButton("V");
private JButton w = new JButton("W");
private JButton x = new JButton("X");
private JButton y = new JButton("Y");
private JButton z = new JButton("Z");
//create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane(){
//set buttons to panels
aF.add(a);
aF.add(b);
aF.add(c);
aF.add(d);
aF.add(e);
aF.add(f);
//set layout of panels
aF.setLayout(new GridLayout(2,3));
gL.add(g);
gL.add(h);
gL.add(i);
gL.add(j);
gL.add(k);
gL.add(l);
gL.setLayout(new GridLayout(2,3));
mR.add(m);
mR.add(n);
mR.add(o);
mR.add(p);
mR.add(q);
mR.add(r);
mR.setLayout(new GridLayout(2,3));
sX.add(s);
sX.add(t);
sX.add(u);
sX.add(v);
sX.add(w);
sX.add(x);
sX.setLayout(new GridLayout(2,3));
yZ.add(y);
yZ.add(z);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2,3));
}
public filecabinet(){
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5,1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
addActionListener();
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
}
public void addActionListener(){
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
f.addActionListener(this);
g.addActionListener(this);
h.addActionListener(this);
i.addActionListener(this);
j.addActionListener(this);
k.addActionListener(this);
l.addActionListener(this);
m.addActionListener(this);
n.addActionListener(this);
o.addActionListener(this);
p.addActionListener(this);
q.addActionListener(this);
r.addActionListener(this);
s.addActionListener(this);
t.addActionListener(this);
u.addActionListener(this);
v.addActionListener(this);
w.addActionListener(this);
x.addActionListener(this);
y.addActionListener(this);
z.addActionListener(this);
}
public static void main(String[]args){
filecabinet frame = new filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
}
I would prefer not to have to write out a listener for every button
and I was wandering if I could just get the text contained in the button.
such as "You have selected foler X", X is the button chosen.
Again, either use arrays and/or a for loop to consolidate your code getting rid of code redundancy. For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class FileCabinet2 extends JPanel {
public static final char FIRST_LETTER = 'A';
public static final char LAST_LETTER = 'Z';
private static final float lARGE_FONT_POINTS = 32f;
private static final int GRID_COLS = 3;
private JLabel chosenLabel = new JLabel();
public FileCabinet2() {
JPanel letterPanel = new JPanel(new GridLayout(0, GRID_COLS));
ActionListener btnListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
chosenLabel.setText(evt.getActionCommand());
}
};
for (char c = FIRST_LETTER; c <= LAST_LETTER; c++) {
String buttonTitle = String.valueOf(c);
JButton button = new JButton(buttonTitle);
setFontPoints(button, lARGE_FONT_POINTS);
letterPanel.add(button);
button.addActionListener(btnListener);
}
JLabel selectionLabel = new JLabel("Selection: ", SwingConstants.RIGHT);
setFontPoints(selectionLabel, lARGE_FONT_POINTS);
setFontPoints(chosenLabel, lARGE_FONT_POINTS);
JPanel bottomPanel = new JPanel(new GridLayout(1, 0));
bottomPanel.add(selectionLabel);
bottomPanel.add(chosenLabel);
bottomPanel.setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
add(letterPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private void setFontPoints(JComponent jComp, float points) {
jComp.setFont(jComp.getFont().deriveFont(points));
}
private static void createAndShowGui() {
FileCabinet2 mainPanel = new FileCabinet2();
JFrame frame = new JFrame("File Cabinet");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Now if you want to change how many button columns there are, all you need to do is change one constant, GRID_COLS, and the same for the size of the font, just change LARGE_FONT_POINTS.
For this:
would prefer not to have to write out a listener for every button
Create a method that accept the JPanel as the parameter and then iterate to each component in JPanel, add the action listener if the component is JButton
This one:
I was wandering if I could just get the text contained in the button.
Just set the value in the JLabel. You already get the button content right?
So, the full code is:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class filecabinet extends JFrame implements ActionListener {
private String folder = "";
// create buttons
private JButton a = new JButton("A");
private JButton b = new JButton("B");
private JButton c = new JButton("C");
private JButton d = new JButton("D");
private JButton e = new JButton("E");
private JButton f = new JButton("F");
private JButton g = new JButton("G");
private JButton h = new JButton("H");
private JButton i = new JButton("I");
private JButton j = new JButton("J");
private JButton k = new JButton("K");
private JButton l = new JButton("L");
private JButton m = new JButton("M");
private JButton n = new JButton("N");
private JButton o = new JButton("O");
private JButton p = new JButton("P");
private JButton q = new JButton("Q");
private JButton r = new JButton("R");
private JButton s = new JButton("S");
private JButton t = new JButton("T");
private JButton u = new JButton("U");
private JButton v = new JButton("V");
private JButton w = new JButton("W");
private JButton x = new JButton("X");
private JButton y = new JButton("Y");
private JButton z = new JButton("Z");
// create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane() {
// set buttons to panels
aF.add(a);
aF.add(b);
aF.add(c);
aF.add(d);
aF.add(e);
aF.add(f);
// set layout of panels
aF.setLayout(new GridLayout(2, 3));
gL.add(g);
gL.add(h);
gL.add(i);
gL.add(j);
gL.add(k);
gL.add(l);
gL.setLayout(new GridLayout(2, 3));
mR.add(m);
mR.add(n);
mR.add(o);
mR.add(p);
mR.add(q);
mR.add(r);
mR.setLayout(new GridLayout(2, 3));
sX.add(s);
sX.add(t);
sX.add(u);
sX.add(v);
sX.add(w);
sX.add(x);
sX.setLayout(new GridLayout(2, 3));
yZ.add(y);
yZ.add(z);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2, 3));
}
public filecabinet() {
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
addActionListener(aF);
addActionListener(gL);
addActionListener(mR);
addActionListener(sX);
addActionListener(yZ);
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
// set the label with folder value
notify.setText("You have selected folder " + folder);
}
// Attach event handler to each JButton in JPanel
public void addActionListener(JPanel panel) {
Component[] components = panel.getComponents();
for (Component component : components) {
if (component instanceof JButton) {
((JButton) component).addActionListener(this);
}
}
}
public static void main(String[] args) {
filecabinet frame = new filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
}
A quick review of your code, brought your code down to this length.
Imagine, what you can achieve if you give it a bit more insight.
Furthermore, when you see that in your code, you are repeating some
lines again and again for the same thingy, you can indeed think of a
pattern that can accomplish that for you in a rightful manner, with
fewer keystrokes.
Try this modified code of yours :-)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class Filecabinet extends JFrame implements ActionListener {
private String folder = "";
//create buttons
private JButton[] button = new JButton[26];
//create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane(){
init_Buttons(button);
//set buttons to panels
for (int i = 0; i < 6; i++)
aF.add(button[i]);
//set layout of panels
aF.setLayout(new GridLayout(2,3));
for (int i = 6; i < 12; i++)
gL.add(button[i]);
gL.setLayout(new GridLayout(2,3));
for (int i = 12; i < 18; i++)
mR.add(button[i]);
mR.setLayout(new GridLayout(2,3));
for (int i = 18; i < 24; i++)
sX.add(button[i]);
sX.setLayout(new GridLayout(2,3));
for (int i = 24; i < 26; i++)
yZ.add(button[i]);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2,3));
}
private void init_Buttons(JButton[] button)
{
int value = 65;
for (int i = 0; i < button.length; i++)
{
button[i] = new JButton(Character.toString((char) value++));
button[i].addActionListener(this);
}
}
public Filecabinet(){
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5,1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
notify.setText(folder);
}
public static void main(String[]args){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
Filecabinet frame = new Filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
//frame.setSize(WIDTH, HEIGHT);
frame.pack();
frame.setVisible(true);
}
});
}
}
You can subclass JButton and write a constructor for the subclass that takes in as a parameter a reference to the action listener, your JFrame.
For instance, your subclass could simply be:
public class YourButton extends JButton {
public YourButton(String title, ActionListener listener) {
super(title);
this.addActionListener(listener);
}
}
So instead of:
private JButton a = new JButton("A");
You would call:
private YourButton a = new YourButton("A", this);
Additionally, as others have suggested, your actionPerformed(ActionEvent e) method requires you to update your notify JLabel instance to reflect the selected button's title.
Hope that helps!
I wanted to ask that if an exception occurs, then display a certain String in the textfield. When I try using a try, catch IOException, it gives me an error that cannot have a catch in the same body as a try. This should probably be done in the action performed method.
GUI:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
try{
if (text.equals("="))
{
doMath math = new doMath();
b = b.replaceAll("\\s+", " ");
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
b+=" ";
display.setText(b);
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else if (text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/"))
{
b += (" "+(text)+ " ");
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
}
catch(IOException o)
{display.setText(b);}
}
}
When I try using a try, catch IOException, it gives me an error that
cannot have a catch in the same body as a try
The error is self-explanatory. The following code is illegal:
try{
catch(Exception ex){
}
}
You want this:
try{
//stuff i need to do
} //close the try
catch(IOException ioex)
{
//log and recover
}
=UPDATE
Based on the code block below (the same that OP is talking about in case it is changed later) The actual error message that is being displayed is this:
Unreachable catch block for IOException. This exception is never
thrown from the try statement body GUI.java
The reason this occurs is that there is nothing that generates an IOException in your code, the only exception you can define without an explicit throw from one of your functions is the top level Exception.
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
try{
if (text.equals("="))
{
doMath math = new doMath();
b = b.replaceAll("\\s+", " ");
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
b+=" ";
display.setText(b);
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else if (text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/"))
{
b += (" "+(text)+ " ");
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
}
catch(IOException o)
{display.setText(b);}
}
}