如何为不同的单击按钮显示不同的消息? [英] How can I display a different message for a different clicked button?
问题描述
首先,我希望对编码非常了解。我希望我的代码能够为单击的每个按钮产生不同的JOptionPane消息
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尝试过包含t [1] [1] = JOptionPane(null,消息)(每个按钮的位置),但出现错误,提示您无法将Jbutton转换为字符串。
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...
推荐答案
此有效答案的另一种替代方法:
您可以更改操作侦听器以识别
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);
}
旁注:请勿 frame.setSize(1920 ,1080);
而是设置首选大小,并让
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.
这篇关于如何为不同的单击按钮显示不同的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!