Java获取按钮内的文本for

时间:2013-09-15 16:37:45

标签: java swing onclick jframe jbutton

当我点击按钮时,我需要做什么,他给我按钮内的文字?因为在这段代码中,如果我点击按钮返回我的最后一个“i”var值......在这种情况下,他给了我“5”。

for(int i; i < 5; i++) {
      JButton button = new JButton();
      button.setText("" + i);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
           // TODO add your handling code here:
           System.out.print("\n Test: " + button.getText());

         } 
      });
      button.setSize(60,20);
      button.setLocation(100, 140);
      button.setVisible(true);
      this.add(button);
      this.revalidate();
      this.repaint();
  }

2 个答案:

答案 0 :(得分:3)

变化:

System.out.print("\n Test: " + button.getText());

System.out.print("\n Test: " + ae.getActionCommand());

答案 1 :(得分:2)

您没有发布原始代码。由于发布它不会编译,所以我认为button是您班级中的一个字段。

发布的代码可以进行一些小修改:

for (int i; i < 5; i++) {
    // Notice the "final"
    final JButton button = new JButton();
    ...

即使您遵循Hovercraft从动作事件中获取字符串的好建议,您也应该这样做,因为button字段没用。

从动作事件中获取字符串,您还可以为所有按钮重用一个侦听器:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent ae) { 
      System.out.print("\n Test: " + ae.getActionCommand());
    } 
};

for (int i; i < 5; i++) {
    final JButton button = new JButton();
    button.setText(Integer.toString(i));
    button.addActionListener(listener);
    // the rest as before
    ...
}