1

So I am trying to code a jeopardy game, but the catch is that I am only trying to assign my buttons to 1 action listener so that all buttons function on their own yet work from 1 action listener.

I've tried a lot, nothing works! package jep;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
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, 5));
    frame.setVisible(true);
    for (int r = 0; r < 6; r++) {
        for (int c = 0; c < 5; 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) {
    // TODO Auto-generated method stub

}

I am trying to get it so that i can click multiple buttons using only 1 action listener but all i can get is a grid

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    So, what exactly doesn't work for you? What happens when you press any button in your grid? Add log statement to your actionPerformed method and see if it is executed when you press a button? – Sergei Sirik Mar 26 '19 at 17:59
  • I'm really new to coding so i dont know what a log statement is but I will go learn about it – Carl O'Neil Mar 26 '19 at 18:05
  • 1
    Please, first fix compilation errors in your code, and follow java code convention for class name at least - it has to start from a capital letter. – Sergei Sirik Mar 26 '19 at 18:21

2 Answers2

1

Here is the corrected code with print to console on button press. Please, check the comments in the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Jep implements ActionListener { // class name has to start with a capital letter

    int i = 6;
    int j = 5;

    public JButton[][] t = new JButton[i][j];

    public static void main(String[] args) {
        new Jep();
    }

    static int n = 100;

    public Jep() {
        JFrame frame = new JFrame("Jeopardy");

        JPanel[][] panelHolder = new JPanel[i][j]; // use panels to add you buttons, check this for details:
        // https://stackoverflow.com/questions/2510159/can-i-add-a-component-to-a-specific-grid-cell-when-a-gridlayout-is-used

        frame.setLayout(new GridLayout(i, j));
        frame.setVisible(true);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1920, 1080);


        frame.setVisible(true);
        for (int r = 0; r < 6; r++) {
            for (int c = 0; c < 5; c++) {
                String vakue = String.valueOf(n);
                t[r][c] = new JButton(vakue);
                t[r][c].setBackground(Color.BLUE);
                t[r][c].setForeground(Color.BLACK);
                t[r][c].addActionListener(this);

                panelHolder[r][c] = new JPanel();

                panelHolder[r][c].add(t[r][c]);

                frame.add(panelHolder[r][c]);

                n = n + 300;
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        System.out.println("press, value = " + arg0.getActionCommand()); // here is a simple system out log statement
    }
}

Output(when you press several buttons):

press, value = 100
press, value = 400
press, value = 700
press, value = 1000
press, value = 1300
press, value = 1600

App Winodow: enter image description here

Hope this will help.

Sergei Sirik
  • 1,249
  • 1
  • 13
  • 28
  • This really hleps me learn what I am going for, however would you know if it is possible to have it where every button displays a different message? I will try to see if I can find out a soloution however I never know where to look for all this information so its all trial and error. So if you know how to do that, that information would be helpful, however thank you for what you have done for me :) – Carl O'Neil Mar 27 '19 at 00:14
  • Just move this line `n = n + 300;` into inner loop, and you will have all the buttons with different labels: 100, 400, 700... – Sergei Sirik Mar 27 '19 at 18:06
  • Updated the answer with this. – Sergei Sirik Mar 27 '19 at 18:10
  • I prefered the version where it was in order however i really appreciate your help. I made some modifications to my code and im currently really happy with what I have going on here. Would you know if theres any way to make it so that every button you click opens a new uer input joption pane message [JOptionPane.showInputDialog(null, "message");]. For example a question for every button you click! If you do not know how then no worries I'll keep looking. – Carl O'Neil Mar 27 '19 at 23:48
  • 1
    I would suggest you to try it yourself and if it doesn't work post another question on this - it is just how stackoverflow works - one post per question. Also, take a look at this to come up with the good question: [mcve]. – Sergei Sirik Mar 28 '19 at 18:47
  • Also, if your current question is addressed, please, mark one of the answers as accepted to close the question. – Sergei Sirik Mar 28 '19 at 19:35
0

You can use AbstractButton (superclass of JButton).setActionCommand, and then in your listener using action command you can figure out your row and column

Instead of creating a 6 x 6 array of JButtons, you ought to use JTable, set the renderer to render your cells values as buttons (or something else) and as recommended here add a listSelectionListener to the tablemodel to get the row and the column values on click. As recommended here: Get position of Click JTable while using Cell renderer

Learning JTable and how to use renders etc can take a little time. But I assume that for this question you are in a learning environment anyway, that this is not something being done for business, or? So I would recommend you take the time to learn JTable. You will end up being much happier with your final product I promise you.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • Thanks for the information! Any good sources to learn JTable? – Carl O'Neil Mar 26 '19 at 18:05
  • @CarlO'Neil I have updated my answer to answer the question you asked directly: "How to use 1 actionlistener for multiple buttons". Also, there is a jTable tutorial here: http://www.java2s.com/Tutorial/Java/0240__Swing/1000__JTable.htm – ControlAltDel Mar 26 '19 at 18:07
  • @CarlO'Neil The reason (which I forgot to mention) I suggested JTable versus JButtons is that you should use MVC for this (search for MVC on the internet if you don't know what this is). At the heart of it, your model is your Jeopardy game. Thus you should build that separately, and apply a View (i.e. JTable) and a controller (i.e. the listSelectionListener) once the model is set. – ControlAltDel Mar 26 '19 at 18:14
  • I will take time to learn jTable, thank you for the tip as I haven't heard about jTable, so I am happy to know about another possible learning command – Carl O'Neil Mar 27 '19 at 00:15