首先,我希望大家知道我对编码非常陌生。我希望我的代码能够为每个单击的按钮生成不同的 JOptionPane 消息
我尝试过包含 t[1][1] = JOptionPane(null, "message") (每个按钮的位置),但是出现错误,提示您无法将 Jbutton 转换为字符串。
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?");
}
}
我希望每个单击的按钮都会显示其他内容...例如,如果您单击第一个按钮,它会显示“红色”,第二个按钮会显示“蓝色”等...
最佳答案
this valid answer 的另一种替代方案:
您可以更改操作监听器以识别单击了哪个按钮,并做出相应的响应:
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);
}
旁注:不要frame.setSize(1920, 1080);
而是设置首选大小并具有
frame.pack();
frame.setVisible(true);
在构造函数的末尾,添加所有组件之后。
关于java - 如何为不同的单击按钮显示不同的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55423159/