如何从JButton检索数据?

问题描述 投票:2回答:1

我想从循环创建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"

每个按钮的文本区域都在工作

java swing components jbutton
1个回答
1
投票

你在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,然后将其转换为新的局部变量,然后获取此文本。

© www.soinside.com 2019 - 2024. All rights reserved.