Setting functions to individual buttons - java

I have a soundboard program I am designing for school. I'm actually permitted to write whatever program that I want. I have a code written for it, as shown here:
package soundboard;
import javax.swing.*;
import java.awt.event.*;
public class Soundboard implements ActionListener{
JButton loadButton;
JButton clearButton;
JButton Button1;
JButton Button2;
JButton Button3;
JButton Button4;
JPanel mainsPanel;
int load;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
loadButton = new JButton("Load...");
loadButton.setSize(80, 30);
loadButton.setLocation(4, 4);
loadButton.addActionListener(this);
clearButton = new JButton("Clear");
clearButton.setSize(80, 30);
clearButton.setLocation(92, 4);
clearButton.addActionListener(this);
Button1 = new JButton("1");
Button1.setSize(80, 80);
Button1.setLocation(4, 45);
Button1.addActionListener(this);
Button2 = new JButton("2");
Button2.setSize(80, 80);
Button2.setLocation(92, 45);
Button2.addActionListener(this);
Button3 = new JButton("3");
Button3.setSize(80, 80);
Button3.setLocation(4, 133);
Button3.addActionListener(this);
Button4 = new JButton("4");
Button4.setSize(80, 80);
Button4.setLocation(92, 133);
Button4.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(loadButton);
frame.add(clearButton);
frame.add(Button1);
frame.add(Button2);
frame.add(Button3);
frame.add(Button4);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent event){
load += 1;
System.out.println(load);
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}
}
In this example, every single button does the exact same thing. How, using this base code, ca I set it so the buttons do their own individual thing? I plan on designing it so hitting the "load" button and then a number-button loads a sound to that said button. Hitting a number-button without hitting load first plays the previously designated sound. Hitting "clear" unloads all buttons.

Instead of
ButtonX.addActionListener(this);
write
ButtonX.addActionListener(e -> {
//do stuff here
});
The -> signifies that this is a lambda expression, which basically creates an anonymous class from a functional interface and passes it as an argument. For more on lambda expressions, you can read my guide here, or the official (but long) tutorial here.
After you make all the lambda expressions, you can remove the
#Override
public void actionPerformed(ActionEvent event){
load += 1;
System.out.println(load);
}
and
implements ActionListener
from your class.

You need to attach different action performed to seperate button an e.g. on how to do it is below for load and clear button
import javax.swing.*;
import java.awt.event.*;
public class Soundboard implements ActionListener{
JButton loadButton;
JButton clearButton;
JButton Button1;
JButton Button2;
JButton Button3;
JButton Button4;
JPanel mainsPanel;
int load;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
loadButton = new JButton("Load...");
loadButton.setSize(80, 30);
loadButton.setLocation(4, 4);
loadButton.addActionListener(e -> System.out.println("load action"));
clearButton = new JButton("Clear");
clearButton.setSize(80, 30);
clearButton.setLocation(92, 4);
clearButton.addActionListener(e -> System.out.println("Clear action"));
Button1 = new JButton("1");
Button1.setSize(80, 80);
Button1.setLocation(4, 45);
Button1.addActionListener(this);
Button2 = new JButton("2");
Button2.setSize(80, 80);
Button2.setLocation(92, 45);
Button2.addActionListener(this);
Button3 = new JButton("3");
Button3.setSize(80, 80);
Button3.setLocation(4, 133);
Button3.addActionListener(this);
Button4 = new JButton("4");
Button4.setSize(80, 80);
Button4.setLocation(92, 133);
Button4.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(loadButton);
frame.add(clearButton);
frame.add(Button1);
frame.add(Button2);
frame.add(Button3);
frame.add(Button4);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent event){
load += 1;
System.out.println(load);
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}
}

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.

addActionListener not working

I followed a tutorial on how to do this - Here's the code I used:
package soundboard;
import javax.swing.*;
import java.awt.event.*;
public class Soundboard {
JButton Button1;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
Button1 = new JButton("1");
Button1.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(Button1);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent event){
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}
}
The code seems to not be working. Could anyone explain why?
The JPanel is used as a background. The problem is in Button1.addActionListener(this); , as it says that "this" is not convertible to ActionListener or something like so.
If you want to add your class as an Onclicklistener:
Button1.addActionListener(this);
then your class must implement the appropriate interface ActionListener like this:
public class Soundboard implements ActionListener{
//...
#Override
public void actionPerformed(ActionEvent e){
//...
}
}
EDIT
If you have multiple buttons, that need separated implementation, you could f.e. use anonymous classes:
mybutton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//does something, that probably interests only mybutton
//declare mybutton as **final** if you must use it
}
});
You need to implement the ActionListener interface if you want to override the actionPerformed method:
public class Soundboard implements ActionListener {
You can only add ActionListeners to a Component with addActionListener().
Your class has to implement ActionListener e.g.
public class Soundboard implements ActionListener {
I got it working. Here's how I implemented it, the other buttons don't do a thing quite yet.
All the code is in a class called Soundboard, which implements ActionListener, while javax.swing* and
java.awt.event* are also imported.
JButton loadButton;
JButton clearButton;
JButton Button1;
JButton Button2;
JButton Button3;
JButton Button4;
JPanel mainsPanel;
int times;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
loadButton = new JButton("Load...");
loadButton.setSize(80, 30);
loadButton.setLocation(4, 4);
clearButton = new JButton("Clear");
clearButton.setSize(80, 30);
clearButton.setLocation(92, 4);
Button1 = new JButton("1");
Button1.setSize(80, 80);
Button1.setLocation(4, 45);
Button2 = new JButton("2");
Button2.setSize(80, 80);
Button2.setLocation(92, 45);
Button3 = new JButton("3");
Button3.setSize(80, 80);
Button3.setLocation(4, 133);
Button4 = new JButton("4");
Button4.setSize(80, 80);
Button4.setLocation(92, 133);
loadButton.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(loadButton);
frame.add(clearButton);
frame.add(Button1);
frame.add(Button2);
frame.add(Button3);
frame.add(Button4);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent event){
times += 1;
System.out.println("Test successful - this was the #"
+ times + " press");
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}

RE-enable a button after closing a frame java

so im making a program for my project.
and when i clicked a button it must open anohter frame and make the button unclickable. and when you closed the popup frame the button must re enable. so this is
my main frame
package Option2;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainMenu {
int intCtr1 = 0;
JFrame frame1 = new JFrame("EXD LAN PARTY");
JButton Button1 = new JButton();
JButton Button2 = new JButton();
JButton Button3 = new JButton();
JButton Button4 = new JButton();
JLabel Label1 = new JLabel();
public void MainMenu(){
//BUTTON1
Button1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PI2.jpg")));
Button1.setBackground(Color.white);
Button1.setBounds(50, 350, 150, 150);
Button1.setToolTipText("Personal Info");
//BUTTON1 END
//BUTTON2
Button2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PC.jpg")));
Button2.setBackground(Color.white);
Button2.setBounds(250, 350, 150, 150);
Button2.setToolTipText("PC INFO");
//BUTTON2 END
//BUTTON3
Button3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Games.jpg")));
Button3.setBackground(Color.white);
Button3.setBounds(450, 350, 150, 150);
Button3.setToolTipText("Games");
//BUTTON3 END
//BUTTON4 END
Button4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Players.jpg")));
Button4.setBackground(Color.white);
Button4.setBounds(650, 350, 150, 150);
Button3.setToolTipText("Players");
//BUTTON4 END
//LABEL1
Label1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/EXD.jpg")));
Label1.setBounds(50, 50, 800, 250);
//LABEL1 END
//Frame1
frame1.getContentPane().setBackground(Color.black);
frame1.setResizable(false);
frame1.setLayout(null);
frame1.setSize(870,650);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(Label1);
frame1.add(Button1);
frame1.add(Button2);
frame1.add(Button3);
frame1.add(Button4);
//Frame1 END
Button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PersonalInfo objPI = new PersonalInfo();
objPI.Menu1();
Button1.setEnabled(false);
}
});
Button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PCInfo objPCI = new PCInfo();
objPCI.Menu2();
}
});
Button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
Games objGames = new Games();
objGames.Menu3();
}
});
Button4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
Players objPlayers = new Players();
objPlayers.Menu4();
}
});
}
public void dim1(){
if(intCtr1 == 1){
MainMenu objMM = new MainMenu();
objMM.Button1.setEnabled(true);
System.out.println("SD");
}
}
}
**and this is my sub frame**
package Option2;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PersonalInfo {
String[] arrSex = {"Male","Female"};
JFrame frame1 = new JFrame("Personal Info");
JLabel label1 = new JLabel("ID");
JLabel label2 = new JLabel("Last Name");
JLabel label3 = new JLabel("First Name");
JLabel label4 = new JLabel("Middle Name");
JLabel label5 = new JLabel("SEX");
JLabel label6 = new JLabel();
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JTextField tf3 = new JTextField();
JTextField tf4 = new JTextField();
JComboBox CB1 = new JComboBox(arrSex);
JButton Button1 = new JButton("NEW");
JButton Button2 = new JButton("SAVE");
JButton Button3 = new JButton("EDIT");
JButton Button4 = new JButton("CANCEL");
JButton Button5 = new JButton();
JButton Button6 = new JButton();
JButton Button7 = new JButton();
JButton Button8 = new JButton();
public void Menu1(){
//Frame1
frame1.add(label6);
frame1.add(label1);
frame1.add(tf1);
frame1.add(label2);
frame1.add(tf2);
frame1.add(label3);
frame1.add(tf3);
frame1.add(label4);
frame1.add(tf4);
frame1.add(label5);
frame1.add(CB1);
frame1.add(Button1);
frame1.add(Button2);
frame1.add(Button3);
frame1.add(Button4);
frame1.add(Button5);
frame1.add(Button6);
frame1.add(Button7);
frame1.add(Button8);
frame1.setVisible(true);
frame1.getContentPane().setBackground(Color.black);
frame1.setSize(600,600);
frame1.setResizable(false);
frame1.setLayout(null);
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
MainMenu objMM = new MainMenu();
objMM.intCtr1=1;
objMM.dim1();
}
});
//Frame1 End
//LABEL6
label6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PI.jpg")));
label6.setBounds(30, 5, 800, 250);
//LABEL6 END
//LABEl1
label1.setBounds(100, 220, 50,50);
label1.setForeground(Color.white);
label1.setFont(new Font("Serif", Font.BOLD, 18));
//Label1 end
//Tf
tf1.setBounds(130, 230, 400,30);
tf1.setEnabled(false);
SmartC objSMC = new SmartC();
tf1.setText(objSMC.SmartCounter("ABC123415XYZS"));
//tf end
//label2
label2.setBounds(35, 255, 120,50);
label2.setForeground(Color.white);
label2.setFont(new Font("Serif", Font.BOLD, 18));
//label2 end
//Tf2
tf2.setBounds(130, 270, 400,30);
//tf2 end
//label3
label3.setBounds(35, 295, 120,50);
label3.setForeground(Color.white);
label3.setFont(new Font("Serif", Font.BOLD, 18));
//label3 end
//Tf3
tf3.setBounds(130, 310 , 400, 30);
//tf3 end
//label4
label4.setBounds(15, 335, 120,50);
label4.setForeground(Color.white);
label4.setFont(new Font("Serif", Font.BOLD, 18));
//label4 end
//Tf4
tf4.setBounds(130, 350 , 400, 30);
//tf4 end
//label4
label5.setBounds(85, 375, 120,50);
label5.setForeground(Color.white);
label5.setFont(new Font("Serif", Font.BOLD, 18));
//label4 end
//cb1
CB1.setBounds(130, 390, 100, 30);
CB1.setBackground(Color.white);
//cb1 end
//button1
Button1.setBounds(35, 450, 100, 30);
Button1.setBackground(Color.white);
//
//
Button2.setBounds(150, 450, 100, 30);
Button2.setBackground(Color.white);
//
//
Button3.setBounds(335, 450, 100, 30);
Button3.setBackground(Color.white);
//
//
Button4.setBounds(450, 450, 100, 30);
Button4.setBackground(Color.white);
//
//
Button5.setBounds(35, 500, 100, 50);
Button5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/First.jpg")));
Button5.setBackground(Color.white);
//
//
Button6.setBounds(150, 500, 100, 50);
Button6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Previous.jpg")));
Button6.setBackground(Color.white);
//
//
Button7.setBounds(335, 500, 100, 50);
Button7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Next.jpg")));
Button7.setBackground(Color.white);
//
//
Button8.setBounds(450, 500, 100, 50);
Button8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Last.jpg")));
Button8.setBackground(Color.white);
//
//
}
}
Any Suggestions about my coding is accepted. Sorry Still learning about Java :)
and when i clicked a button it must open anohter frame
You should NOT be creating another JFrame.
Instead you should be creating a modal JDialog. The dialog will not allow you to click on the frame until the dialog is closed.
Any Suggestions about my coding is accepted
Follow Java naming conventions. Variable names should NOT start with an upper case character. Sometimes you follow this guideline and sometimes you don't. Be consistent!
Don't use setBounds(...). Swing was designed to be used with layout managers!
First, please read Java naming conventions.
You need to pass the reference of MainMenu to PersonalInfo in order to achieve what you need, here:
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PersonalInfo objPI = new PersonalInfo(this);
objPI.menu1();
button1.setEnabled(false);
}
});
And you need to add a constructor to PersonalInfo:
private MainMenu m;
public PersonalInfo(MainMenu m) {
this.m = m;
}
Add a public method to MainMenu:
public void enableMyButton() {
button1.setEnabled(true);
}
Now you can add an event listener to PersonalInfo to enable the button of the MainMenu frame:
frame1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
this.m.enableMyButton();
}
});

Java swing, out of scope variable and usage of buttons

I am trying to make an actionlistener, for the buttons I have created and display each one a textfield much like a calculator upon each entry of a number.
However under the actionPerformed method, it seems like button1 and all of them seem to be out of scope, I can't declare a button static now can I?
I need to overcome the out of scope issue any takers?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import layout.TableLayout;
public class example extends JFrame implements ActionListener
{
public static void main (String args[])
{
new example();
}
public example ()
{
super("The Power of Preferred Sizes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
double size[][] = {{75, 75, 75, 75, 75}, // Columns
{75, 75, 75, 75, 75,75}}; // Rows
pane.setLayout(new TableLayout(size));
TableLayout layout = new TableLayout(size);
pane.setLayout (layout);
// Create all controls
String label[] = {"1", "2", "3", "4", "5","6","7", "8","9","0","PLS","RES"};
JButton button[] = new JButton[label.length];
JTextField upperText = new JTextField();
JTextField bottomText = new JTextField();
// textfieldName.setSize(10, 10);
pane.add(upperText, "0, 0, 4, 0");
pane.add(bottomText, "0, 5, 4, 0");
JButton button1 = new JButton(label[0]);
JButton button2 = new JButton(label[1]);
JButton button3 = new JButton(label[2]);
JButton button4 = new JButton(label[3]);
JButton button5 = new JButton(label[4]);
JButton button6 = new JButton(label[5]);
JButton button7 = new JButton(label[6]);
JButton button8 = new JButton(label[7]);
JButton button9 = new JButton(label[8]);
JButton button10 = new JButton(label[9]);
JButton button11= new JButton(label[10]);
JButton button12 = new JButton(label[11]);
pane.add(button1, "1,1");//1
pane.add(button2, "2,1");//2
pane.add(button3, "3,1");//3
pane.add(button4, "1,2");//
pane.add(button5, "2,2");
pane.add(button6, "3,2");
pane.add(button7, "1,3");
pane.add(button8, "2,3");
pane.add(button9, "3,3");
pane.add(button10, "1,4");
pane.add(button11, "2,4");
pane.add(button12, "3,4");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);
button10.addActionListener(this);
button11.addActionListener(this);
button12.addActionListener(this);
pack();
setResizable(false);
show();
}
public void actionPerformed(ActionEvent e) {
//code that reacts to the action...
Object source = e.getSource();
if(source == button1){
upperText.append("1");
}
}
}
You can declare them as class fields, so they will be accessible within the whole class:
public class example extends JFrame implements ActionListener {
JButton button1;
JButton button2;
JButton button3;
JButton button4;
JButton button5;
JButton button6;
JButton button7;
JButton button8;
JButton button9;
JButton button10:
JButton button11;
JButton button12;
// Constructor
// Methods
}
Also you should consider using an array to hold the 12 buttons.

JButton - How to connect?

I found this code online and modified it and it stopped working. I'm thinking it has something to do with when I added the Jpanel but what I am doing works best with a JPanel. How do I make it that the events in the action performed if statements work?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class GUI extends JFrame implements ActionListener {
static JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1));
public GUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setSize(100, 100);
//setLocation(100, 100);
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(this);
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(this);
panel.add(button2);
//Button 3
JButton button3 = new JButton("3");
button3.addActionListener(this);
panel.add(button3);
//Button 2
JButton button4 = new JButton("4");
button4.addActionListener(this);
panel.add(button4);
//Button 2
JButton button5 = new JButton("5");
button5.addActionListener(this);
panel.add(button5);
//Button 2
JButton button6 = new JButton("6");
button6.addActionListener(this);
panel.add(button6);
//Button 2
JButton button7 = new JButton("7");
button7.addActionListener(this);
panel.add(button7);
//Button 2
JButton button8 = new JButton("8");
button8.addActionListener(this);
panel.add(button8);
//Button 2
JButton button9 = new JButton("9");
button9.addActionListener(this);
panel.add(button9);
panel.setVisible(true);
}
public static void main(String[] args) {
new GUI();
JFrame f = new JFrame("Calc");
f.setContentPane(panel);
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
ArrayList numbers = new ArrayList();
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("button1")) {
numbers.add(2);
System.out.println("2");
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}
You need to change the part actionPerformed as:
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("2")) {
numbers.add(2);
System.out.println("2");
}
}
Here, when a button is clicked, your e.getActionCommand() will give the constructor string. i.e. "1", "2" ,"3" and so on
reference
I put comments in code, but the first thing you should do is to read official tutorials. How to use Buttons
public class GUI /*extends JFrame implements ActionListener*/ {
//don't extend JFrame is you don't have too neither implement ActionListener in top-container classes that breaks single responsability principle
private JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1)); // why static??
public JPanel getPanel(){
return panel;
}
public GUI() {
//i use anonymous classes for this, then you don't have to use if-else
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
myMethod();
numbers.add(1);
System.out.println("1");
}
});
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//put here logic for button2
}
});
panel.add(button2);
//and goo on with other buttons
//panel.setVisible(true); you don't need to call this!!
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI gui = new GUI();
frame.add(gui.getPanel());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private List<Integer> numbers = new ArrayList<>();//use generics!
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}

Categories