ActionListener not working on JButton - java

I have written a code to display three buttons in three panels on a
frame with grid layout.
The objective is to
- change color of button when the button is clicked
- initially all 3 of them are black
The code runs perfectly except for the color of button doesn't change on
click.
Can anyone please point out the problem or debug it.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class gui extends JFrame implements ActionListener {
JPanel p1, p2, p3;
JButton b1, b2, b3;
public gui() {
setLayout(new GridLayout(3, 1));
JPanel p1 = new JPanel(new GridLayout(1, 1));
JPanel p2 = new JPanel(new GridLayout(1, 1));
JPanel p3 = new JPanel(new GridLayout(1, 1));
JButton b1 = new JButton();
JButton b2 = new JButton();
JButton b3 = new JButton();
b1.setBackground(Color.BLACK);
b2.setBackground(Color.BLACK);
b3.setBackground(Color.BLACK);
b1.addActionListener(this);
p1.add(b1);
b2.addActionListener(this);
p2.add(b2);
b3.addActionListener(this);
p3.add(b3);
add(p1);
add(p2);
add(p3);
}
public void actionPerformed(ActionEvent e) //function to handle click
{
if (e.getSource() == b1) {
b1.setBackground(Color.RED);
} else if (e.getSource() == b2) {
b1.setBackground(Color.YELLOW);
} else if (e.getSource() == b3) {
b3.setBackground(Color.BLUE);
}
}
public static void main(String[] args) {
gui ob1 = new gui();
ob1.setSize(1000, 500);
ob1.setLocation(100, 100);
ob1.setVisible(true);
ob1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

You have to initialize the buttons using[Same applied to panels as well]
b1 = new JButton();
b2 = new JButton();
b3 = new JButton();
because you are creating local variables which hides the global variables
JButton b1 = new JButton();//local variables
JButton b2 = new JButton();
JButton b3 = new JButton();
In the second if condition you have to change the color of b2 not b1
else if(e.getSource()==b2){
//b1.setBackground(Color.YELLOW);
b2.setBackground(Color.YELLOW);
}
Always use .equals() instead of == to compare objects
e.getSource().equals(b1)

Related

Can I use a for loop to create objects in java?

Can I initialize multiple objects in a single loop?
Here's what a snippet of my code looks like. As you can see, it becomes hard to look at from a glance and takes up too much space.
I'd like to be able to create the buttons in one for loop and then modify in another for loop.
public class MyFrame extends JFrame {
MyFrame() {
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
JButton button4 = new JButton();
JButton button5 = new JButton();
JButton button6 = new JButton();
JButton button7 = new JButton();
JButton button8 = new JButton();
JButton button9 = new JButton();
JButton button0 = new JButton();
button1.setBounds(60, 60, 50, 50);
button2.setBounds(120,60,50,50);
button3.setBounds(180,60,50,50);
button4.setBounds(60,120,50,50);
button5.setBounds(120,120,50,50);
button6.setBounds(180,120,50,50);
button7.setBounds(60,180,50,50);
button8.setBounds(120,180,50,50);
button9.setBounds(180,180,50,50);
button0.setBounds(120,240,50,50);
}
}
Yes, you can use a for loop to create the buttons.
Here's a GUI I created.
It's not a good idea to use absolute positioning (setBounds) when creating a GUI. You should use the Swing layout managers.
I used a GridLayout to position the buttons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TenButtonGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TenButtonGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("Ten Button GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
for (int i = 0; i < 11; i++) {
if (i == 9) {
JLabel label = new JLabel(" ");
panel.add(label);
} else {
JButton button = new JButton();
button.setPreferredSize(new Dimension(50, 50));
panel.add(button);
}
}
return panel;
}
}
You could do something like this:
List<JButton> buttons = new ArrayList<>();
int[][] bounds = {{60, 60, 50, 50}, {120,60,50,50}}; //add more bound quadruplets
// iterating over the values in the bounds array
Arrays.asList(bounds).forEach(v -> {
JButton button = new JButton();
button.setBounds(v[0], v[1], v[2], v[3]);
buttons.add(button);
});
In the end you will find your buttons in the buttons List.

Java GUI How to make an event when I press a JButton?

I want to make a keyboard. If I press the button it has to come up at 2.(pic). I think it's a similar way to make a calculator. Can I have some advice?
Actually I don't even know if this right. Am I OK making a JButton like that?
This is my code.
package assignment;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Random extends JFrame {
Random() {
setTitle("보안 키보드");
setLayout(new BorderLayout(10, 10));
showNorth();
showCenter();
showSouth();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(450,500);// 창크기를 정한다
setVisible(true);}
void showNorth() {
JTextField area1 = new JTextField();
JTextField area2 = new JTextField();
JPanel panel = new JPanel(new GridLayout(2, 0));
}
area2.setText("보안문자를 입력하세요.");
area1.setHorizontalAlignment(JTextField.CENTER);
area2.setHorizontalAlignment(JTextField.CENTER);
area1.setEditable(false);
area2.setEditable(false);
panel.add(area1);
panel.add(area2);
add(panel, BorderLayout.NORTH);
}
void showCenter() {
JPanel p3 = new JPanel(new GridLayout(4, 4));
p3.setLayout(new GridLayout(5, 5, 5, 5));
// 버튼 생성하기
JButton ba = new JButton("");
JButton bb = new JButton("");
JButton bc = new JButton("");
JButton bd = new JButton("");
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton er1 = new JButton("하나\n지움");
JButton erall = new JButton("전체\n지움");
p3.add(ba);// 버튼을 패널에 부착시킨다
p3.add(bb);
p3.add(bc);
p3.add(bd);
p3.add(b0);
p3.add(b1);
p3.add(b2);
p3.add(b3);
p3.add(b4);
p3.add(b5);
p3.add(b6);
p3.add(b7);
p3.add(b8);
p3.add(b9);
p3.add(er1);
p3.add(erall);
add(p3, BorderLayout.CENTER); // 패널을 프레임의 중앙에 추가한다.
}
void showSouth() {
JPanel p4 = new JPanel();
JButton complete = new JButton("입력완료"); // 입력완료 버튼 생성
p4.add(complete);
p4.setLayout((LayoutManager) new FlowLayout(FlowLayout.TRAILING));
add(p4, BorderLayout.SOUTH);
}
public static void main(String[] args) {
new Random();
}
}
First of all, the code needs extreme refactor. But as you the OOP beginner, lets dive into your problem. Your class called Random needs to implement ActionListener interface and override actionPerformed method:
#Override
public void actionPerformed(ActionEvent e) {
}
Then, what you want to do is to add action listeners and set action commands for the buttons, for instance:
button.addActionListener(this);
button.addActionCommand("button")
Now you can know which button was clicked and represent something on your JTextField:
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("button")){
textField.setText("button was clicked");
}
}

How to get an Image when JComboBox is selected?

I want to display an Image, when a JComboxBox is selected.
When I select "Tesla Model S" from the combo box I want to display an Image above the combo.
Adding the Price into the JTextField works fine. I'm writing a Program where I can select a Car and accessories.
After I had selected the two Items, the price will show up in both text fields and I can add them.
Unfortunately I can't post any picture to show you my example.
I'm sorry if there is a lot of mess in my code. I tried different things but none of them worked
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Auto extends JFrame implements ActionListener, ItemListener {
JTextField AutoFeld;
JTextField AussFeld;
JTextField GesamtFeld;
JButton ResButton;
JButton ClearButton;
JCheckBox displayButton;
ImageIcon image1;
ImageIcon image2;
ImageIcon image3;
JLabel label1;
JLabel label2;
JLabel label3;
JLabel Ergebnis;
JLabel GesamtLabel;
JPanel panel0;
StringBuffer choices;
public Auto() {
this.setTitle("Auto");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
this.setLayout(new GridLayout(0, 10));
/*image1 = new ImageIcon(getClass().getResource("AMGgt.jpg"));
image2 = new ImageIcon(getClass().getResource("AudiA7.jpg"));
image3 = new ImageIcon(getClass().getResource("TeslaS.jpg"));
*/
GesamtLabel = new JLabel("Gesamt");
image1 = new ImageIcon(getClass().getResource("AMGgt.jpg"));
label1 = new JLabel(image1);
image2 = new ImageIcon(getClass().getResource("AudiA7.jpg"));
label2 = new JLabel(image2);
image3 = new ImageIcon(getClass().getResource("TeslaS.jpg"));
label3 = new JLabel(image3);
AutoFeld = new JTextField("0", 10);
AutoFeld.setEditable(true);
AussFeld = new JTextField("0", 10);
AussFeld.setEditable(true);
GesamtFeld = new JTextField("0", 15);
GesamtFeld.setEditable(false);
ResButton = new JButton("Ergebnis");
//ResButton.addActionListener(this);
ResButton.addActionListener(e -> {
Object source = e.getSource();
String s1 = AutoFeld.getText();
String s2 = AussFeld.getText();
int o1 = Integer.parseInt(s1);
int o2 = Integer.parseInt(s2);
if (source == ResButton) {
GesamtFeld.setText("" + (o1 + o2));
}
});
ClearButton = new JButton("Clear");
//ClearButton.addActionListener(this);
ClearButton.addActionListener(e -> {
Object source = e.getSource();
if (source == ClearButton) {
AutoFeld.setText("0");
AussFeld.setText("0");
GesamtFeld.setText("0");
}
});
displayButton = new JCheckBox("Helles Display");
displayButton.setSelected(true);
JPanel panel0 = new JPanel();
panel0.add(label1);
panel0.add(label2);
panel0.add(label3);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3, 2));
String[] Autos = {"---Bitte Model auswählen---", "Tesla Model S", "Mercedes-AMG GT", "Audi A7"};
JComboBox AutoList = new JComboBox(Autos);
AutoList.addActionListener(e -> {
Object source = e.getSource();
JComboBox selectedChoice = (JComboBox) e.getSource();
if ("Tesla Model S".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("108420");
label1.getIcon();
} else if ("Mercedes-AMG GT".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("134351");
label2.getIcon();
} else if ("Audi A7".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("58350");
//label3.getIcon();
}
});
panel1.add(AutoList);
AutoList.setSelectedIndex(0);
//AutoList.addActionListener(this);
panel1.add(AutoFeld);
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(3, 2));
String[] Ausstattung = {"---Bitte Ausstattung auswählen---", "Sportsitze", "Navigationsgerät", "Kaffeehalter"};
JComboBox AussList = new JComboBox(Ausstattung);
panel2.add(AussList);
AussList.setSelectedIndex(0);
AussList.addActionListener(e -> {
JComboBox selectedChoice = (JComboBox) e.getSource();
if ("Sportsitze".equals(selectedChoice.getSelectedItem())) {
AussFeld.setText("1679");
} else if ("Navigationsgerät".equals(selectedChoice.getSelectedItem())) {
AussFeld.setText("90");
} else if ("Kaffeehalter".equals(selectedChoice.getSelectedItem())) {
AussFeld.setText("20");
}
});
panel2.add(AussFeld);
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(3, 2));
panel3.add(GesamtLabel);
panel3.add(GesamtFeld);
JPanel panel4 = new JPanel();
panel4.add(ResButton);
panel4.add(ClearButton);
JPanel panel5 = new JPanel();
panel5.add(displayButton);
displayButton.setSelected(true);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(panel0);
panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
panel.add(panel4);
panel.add(panel5);
panel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
setContentPane(panel);
pack();
setResizable(true);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
//JComboBox selectedChoice = (JComboBox) e.getSource();
Object source = e.getSource();
JComboBox selectedChoice = (JComboBox) e.getSource();
String s1 = AutoFeld.getText();
String s2 = AussFeld.getText();
double o1 = Double.valueOf(s1);
double o2 = Double.valueOf(s2);
/*if(source == ClearButton) {
AutoFeld.setText("0");
AussFeld.setText("0");
GesamtFeld.setText("0");
} */
}
public static void main(String[] args) {
JFrame myApplication = new Auto();
myApplication.setVisible(true);
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
}
}
If you want to display one image, you only need one JLabel, so remove label2 and label3.
Initialize label1 with out any icon : label1 = new JLabel();
and have the action listener set the icon:
AutoList.addActionListener(e -> {
Object source = e.getSource();
JComboBox selectedChoice = (JComboBox) e.getSource();
if ("Tesla Model S".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("108420");
label1.setIcon(image1);
} else if ("Mercedes-AMG GT".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("134351");
label1.setIcon(image2);
} else if ("Audi A7".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("58350");
label1.setIcon(image3);
}
});
You will also need to change the code of the clear button.

getActionCommand not working in code (watching tutorial series)

I'm watching a youtube tutorial series by mybringback. (38th video in the series). At the very bottom of the code, I have e.getactioncommand. When I click on the radio button, I want it to say something in the text field. For instance when I hit radio button 1, it should say "you selected radio button 1" in the text field. I followed the tutorial exactly, but I can't figure out what's wrong.
I have the driver class as well. that i didn't post here.
Here;s the video https://www.youtube.com/watch?v=pjS_IiNp008&list=SPDAA5DE54FB5215EC
package ActionCommandnActionListeners;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class FirstWindow extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
String s;
JCheckBox cb, cb2;
JTextField textField;
JLabel label;
JRadioButton b1, b2, b3, b4;
ButtonGroup group;
JTextArea tb;
public FirstWindow() {
super("Your Computer is very special");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel(new GridBagLayout());
JPanel p4 = new JPanel();
b1 = new JRadioButton("Choice 1");
b1.setActionCommand("you selected num1");
b1.addActionListener(this);
b2 = new JRadioButton("Choice 2");
b2.setActionCommand("you selected num2");
b2.addActionListener(this);
b3 = new JRadioButton("Choice 3");
b3.setActionCommand("you selected num3");
b3.addActionListener(this);
b4 = new JRadioButton("Choice 4");
b4.setActionCommand("you selected num4");
b4.addActionListener(this);
group = new ButtonGroup();
group.add(b1);
group.add(b2);
group.add(b3);
group.add(b4);
p4.add(b1);
p4.add(b2);
p4.add(b3);
p4.add(b4);
JButton b = new JButton("Button 1");
JButton c = new JButton("Button 2");
p.add(b);
p.add(c);
cb = new JCheckBox("Do you LOVE bacon?");
cb2 = new JCheckBox("Do you LOVE cheese?");
p2.add(cb);
p2.add(cb2);
label = new JLabel("This is a label");
JTextArea tb = new JTextArea("This is a text area");
textField = new JTextField("text field");
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s2 = textField.getText();
label.setText(s2);
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.gridx = 0;
gbc.gridy = 0;
p3.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
p3.add(tb, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
p3.add(textField, gbc);
add(p, BorderLayout.SOUTH);
add(p2, BorderLayout.NORTH);
add(p3, BorderLayout.CENTER);
add(p4, BorderLayout.WEST);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
s = "Good job kid, you harvested your corn! \n";
if (cb.isSelected()) {
s += " And of course you love bacon! \n";
}
if (cb2.isSelected()) {
s += " Most naturally you love cheese! \n";
}
JOptionPane.showMessageDialog(null, s);
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
tb.setText(e.getActionCommand());
}
}
JTextArea tb = new JTextArea("This is a text area");
You are shadowing your variables. You defined the "tb" variable as an instance variable and a local variable. You don't want the local variable because your actionPerformed() method can't reference local variables.
So the code should be:
//JTextArea tb = new JTextArea("This is a text area");
tb = new JTextArea("This is a text area");
I'm watching a youtube tutorial series by mybringback
I've never quite figured out why people use youtube for tutorials.
I would start with the Swing tutorial. This way not only can you read the tutorial at your pace but you can actually download the code and compile and test and change the code. So you start with working code and then you customize it to do what you want.

JButton Layout Issue

I'm putting together the basic layout for a contacts book, and I want to know how I can make the 3 test buttons span from edge to edge just as the arrow buttons do.
private static class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Code Placeholder");
}
}
public static void main(String[] args) {
//down button
ImageIcon downArrow = new ImageIcon("down.png");
JButton downButton = new JButton(downArrow);
ButtonHandler downListener = new ButtonHandler();
downButton.addActionListener(downListener);
//up button
ImageIcon upArrow = new ImageIcon("up.png");
JButton upButton = new JButton(upArrow);
ButtonHandler upListener = new ButtonHandler();
upButton.addActionListener(upListener);
//contacts
JButton test1Button = new JButton("Code Placeholder");
JButton test2Button = new JButton("Code Placeholder");
JButton test3Button = new JButton("Code Placeholder");
Box box = Box.createVerticalBox();
box.add(test1Button);
box.add(test2Button);
box.add(test3Button);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(box, BorderLayout.CENTER);
content.add(downButton, BorderLayout.SOUTH);
content.add(upButton, BorderLayout.NORTH);
JFrame window = new JFrame("Contacts");
window.setContentPane(content);
window.setSize(400, 600);
window.setLocation(100, 100);
window.setVisible(true);
}
Following up on #kloffy's suggestion:
package playground.tests;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import junit.framework.TestCase;
public class ButtonTest extends TestCase {
public void testThreeButtons() throws Exception {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
JButton button1 = new JButton("A");
JButton button2 = new JButton("B");
JButton button3 = new JButton("C");
panel.add(button1);
panel.add(button2);
panel.add(button3);
JFrame window = new JFrame("Contacts");
window.setContentPane(panel);
window.setSize(300, 600);
window.pack();
window.setVisible(true);
int width = button1.getWidth();
assertEquals(width, button2.getWidth());
assertEquals(width, button3.getWidth());
}
}

Categories