我想从循环创建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"
。
每个按钮的文本区域都在工作
你在getName()
上调用this
,这不是按钮,这是你的背景,这是你的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
,然后将其转换为新的局部变量,然后获取此文本。