【发布时间】:2021-04-21 08:10:30
【问题描述】:
我做了 getButtons();如果我分别做每个按钮,则创建按钮并减少不必要的行的方法。然后我在 actionPerformed 中使用了 getText();因此,每当我单击这 3 个按钮之一时,它都会给我它的文本(如果我单击按钮 1,它会打印出 1)。我现在打算做的是我想将每个按钮用于单独的事情,例如我想用按钮“1”方法 getMath();而其他 2 个按钮可以做其他事情,比如调用不同的方法。
我不知道该怎么做,所以我在这里寻求帮助。谢谢。
void getMath() {
int x = 3;
int y = 5;
System.out.println(x + y);
}
void getButtons() {
String[] buttons = { "1", "2", "3" };
int height = 250;
int gap = 65;
for (int i = 0; i < buttons.length; i++) {
JButton gameButtons = new JButton(buttons[i]);
gameButtons.setFont(new Font("Times New Roman", Font.BOLD, 19));
gameButtons.setBorder(BorderFactory.createLineBorder(Color.BLACK));
gameButtons.setBounds(394, 50 + (height + gap * i), 150, 40);
gameButtons.setForeground(Color.BLACK);
gameButtons.setBackground(Color.WHITE);
gameButtons.addActionListener(this);
frame.add(gameButtons);
}
}
public void actionPerformed(ActionEvent e) {
System.out.println(((JButton) e.getSource()).getText());
}
【问题讨论】:
-
这能回答你的问题吗? Java - Call Method via JButton
标签: java