【问题标题】:JAVA Action Performed not working执行的 JAVA 操作不起作用
【发布时间】:2013-09-19 18:19:02
【问题描述】:

我正在为此创建按钮,当我点击他时..没有发生任何事情...当我点击 btn 时,没有调用函数 btnActionPerformed...如何使其工作?

private void btButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here
    int[] ret = new int[SQL.freetables().size()];
    Iterator<Integer> iterator = SQL.freetables().iterator();
    for (int i = 0; i < ret.length; i++)
    {
    ret[i] = iterator.next().intValue();
    int num=SQL.freetables().size() + 1;
    this.btn = new JButton();
    this.btn.setText("" + ret[i]);
    this.btn.setSize(60,20);
    int x = 100+(80*i);
    this.btn.setLocation(x, 140);
    this.btn.setVisible(true);
    this.add(btn);     
   // }

    }
    this.revalidate();
    this.repaint();
}          

private void btnActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    System.out.print("\b Test: " + btn.getText());
} 

【问题讨论】:

    标签: java swing jframe jbutton buttonclick


    【解决方案1】:

    您需要注册到actionPreformed

    this.btn.addActionListener(this);
    

    你的代码应该是:

    bt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
           // TODO add your handling code here
           int[] ret = new int[SQL.freetables().size()];
           Iterator<Integer> iterator = SQL.freetables().iterator();
           for (int i = 0; i < ret.length; i++)
           {
              ret[i] = iterator.next().intValue();
              int num=SQL.freetables().size() + 1;
              this.btn = new JButton();
              this.btn.setText("" + ret[i]);
              this.btn.setSize(60,20);
              int x = 100+(80*i);
              this.btn.setLocation(x, 140);
              this.btn.setVisible(true);
              this.add(btn);   
              btn.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent ae) { 
                   // TODO add your handling code here:
                   System.out.print("\b Test: " + btn.getText());
                 } 
              }
    
              this.revalidate();
              this.repaint();
           }
        }
    });
    

    【讨论】:

    • 它工作... :).. 但我还有一个问题,如果我将 ActionPerformed 放在 for 中,当我得到 btn 的文本时,将永远是最后一个空闲表。 ..如果我有两个空闲表,当我点击时,1 和 3,每次我都会得到“3”......所以,这是我试图退出 for 循环的原因......
    【解决方案2】:

    您必须实现ActionListener 接口。这些方法都不匹配我可以看到的所需签名。

    http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html

    方法是actionPerformed。侦听器必须附加到JButton。我在你的代码中都没有看到。

    您似乎急需Swing tutorial

    【讨论】:

    • 嗯...谢谢你,我会看到这个教程来学习更多的摇摆...我在 Android 上工作,所以我不需要摇摆风格,但现在我确定布局样式不同.. 并且会阅读关于摇摆...
    猜你喜欢
    • 1970-01-01
    • 2013-05-20
    • 2016-05-12
    • 2016-06-15
    • 1970-01-01
    • 2021-07-19
    • 2012-12-08
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多