有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

执行的swing JAVA操作不起作用

我正在为他创建按钮,当我点击他的时候。。什么都没发生。。。当我点击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());
} 

共 (2) 个答案

  1. # 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();
           }
        }
    });