所以我正在尝试编写一个危险游戏,但问题是我只是尝试将我的按钮分配给 1 个 Action 监听器,以便所有按钮都可以独立运行,但可以从 1 个 Action 监听器工作。
我试了很多方法,还是没有效果! 封装 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
}
我正在尝试获取它,以便我可以仅使用 1 个操作监听器单击多个按钮,但我所能得到的只是一个网格
最佳答案
这是更正后的代码,按下按钮时会打印到控制台。请检查代码中的注释:
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
}
}
输出(当您按下多个按钮时):
press, value = 100
press, value = 400
press, value = 700
press, value = 1000
press, value = 1300
press, value = 1600
希望这会有所帮助。
关于java - 尝试对多个按钮使用 1 个 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55363394/