【发布时间】:2016-03-14 05:58:32
【问题描述】:
我是这个动作命令和动作监听器(鼠标按下)事件的新手。我在我的代码中使用了这个:
// This is the single event handler for all the buttons
public void actionPerformed(ActionEvent e) {
JButton selectedBtn = (JButton) e.getSource();
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons[row].length; col++) {
if (buttons[row][col] == selectedBtn) {
moves++; //incrementing the moves
System.out.printf("moves: %d%n", moves);
System.out.printf("Selected row: %d%n", row+1);
System.out.printf("Selected column: %d%n", col+1);
}
}
}
这段代码显示了正确按下的按钮的行和列。但我想要做的是我试图在我的 Jlabels 前面显示这些信息。
即如果一个按钮被按下并且它位于第 2 行和第 4 列,它应该显示如下:
相反,它在输出控制台中显示如下:
moves: 1
Selected row: 3
Selected column: 4
关于如何修改这些 Jlabel 以便在其上显示此信息的任何想法?
这些是我的 Jlabels
//labels
JLabel label1 = new JLabel("COL: ");
label1.setLocation(10,260);
label1.setSize(100,100);
add(label1);
JLabel label2 = new JLabel("ROW: ");
label2.setLocation(10,280);
label2.setSize(100,100);
add(label2);
任何帮助将不胜感激:)
【问题讨论】:
-
不清楚您的确切要求。如果您只需要在框架中显示这些值,您可以为这些值使用单独的 JLabels,然后在 actionPerformed 事件中更新这些值,或者使用不可编辑的 JTextFields同样。
-
JLabel#setText,您可能还想看看How to Use Labels。请记住,您可能需要将标签作为类实例字段才能修改它们 -
@Arsal Abbas 你问如何在 JLabels 上显示文本?