如何从 JButton 检索数据?

How to retrieve data from JButton?

我希望从循环中创建 JButton 控件,然后使用事件处理程序提取相关信息并使用 SQL 命令进一步操作。

但是我无法访问创建的按钮对象的组件名称或组件文本字段。

try {
    String SQL = "SELECT * FROM Products";
    ResultSet rs = GetDB.AccessDatabse(SQL);

    while(rs.next()){
        JButton btn = new JButton();
        btn.setText(rs.getString("ProductName"));
        btn.setName(rs.getString("ProductName"));
        System.out.println(btn.getName()); 
        btn.addActionListener(this);
        add(btn);
                    }
    }   
 catch (SQLException ex) {System.out.println("GUI Creation Error");}    
}

    @Override
    public void actionPerformed(ActionEvent ae){
        System.out.println(this.getName()); 
    }

我希望将按钮名称设置为 SQL 查询结果,但是当尝试打印结果时,它会为每个按钮显示 "frame0"

每个按钮的文本区域正常工作

您正在 this 上调用 getName(),这不是按钮,而是您的 this-context,也就是您的 JFrame

您需要解析 ActionEvent 的来源。

这里我制作了一些可以做你想做的快速代码:

actionPerformed(ActionEvent e) { 
  if(e.getSource() instanceof JButton) {
    //Casting here is safe after the if condition
    JButton b = (JButton) e.getSource();
    System.out.println(b.getText());
  } else {
    System.out.println("Something other than a JButton was clicked");
  }
}  

我做什么:我检查动作源是否是 JButton,然后将其转换为一个新的局部变量,然后获取它的文本。