Search code examples
javaswingjbuttonactionlistener

How can I display a different message for a different clicked button?


First I'd like it to be known im VERY new to coding. I would like to have my code be able to produce a different JOptionPane Message for every button clicked

ive tried including t[1][1] = JOptionPane(null, "message") (the location of each button) however the error came up saying you cant convert Jbutton to string.

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.JOptionPane;

public class jep implements ActionListener{

    public  JButton[][] t = new JButton[6][6];

    public static void main(String[] args) {
        new jep();
    }
    static int n = 100;

    public jep()  {

        JFrame frame = new JFrame("Jeopardy");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1920,1080);
        frame.setLayout(new GridLayout(6, 6));

        frame.setVisible(true);
        for (int r = 0; r < 5; r++) {
            for (int c = 0; c < 6; c++) {
                String vakue = String.valueOf(n);
                t[r][c] = new JButton(vakue);
                t[r][c].setBackground(Color.BLUE);
                t[r][c].setForeground(Color.YELLOW);
                t[r][c].addActionListener(this);
                frame.add(t[r][c]);
            }
            n = n +300;
        }
    }
    @Override
    public void actionPerformed(ActionEvent arg0) {
        JOptionPane.showInputDialog(null,"What's 1+1?");
    }
}

I would like it so that every button clicked says something else... For example if you click the first button it says like "RED" and the second "BLUE" etc...


Solution

  • Another alternative to this valid answer:
    You can change the action listener to identify which button was clicked, and respond accordingly:

    public void actionPerformed(ActionEvent e) {
    
        String value = e.getActionCommand();
        String message = "";
    
        switch(value){
            case "100":
                message = "RED";
                break;
            case "400":
                message = "BLUE";
                break;
            default:
                message = "Un recognized button pressed";
                break;
        }
    
        JOptionPane.showInputDialog(null,message);
    }
    

    Side notes: do not frame.setSize(1920, 1080); instead set preferred size and have

        frame.pack();
        frame.setVisible(true);
    

    at the end of the constructor, after all components have been added.