【发布时间】:2020-05-29 19:16:41
【问题描述】:
我是 java 新手,我正在自己尝试一个小项目,我想从 sql 数据库中列出用户的名字和姓氏(这一切都很好,但我不只是想列出它们
我想用删除按钮在 GUI 中列出所有用户,这个删除按钮自然会动态生成,我想将按钮的用户 ID 传递给执行的操作。 像这样:
John Doe 'Delete button'
Jane Doe 'Delete button'
在我下面的代码中,我只是动态生成 16 个按钮(没有用户表)而不是传递用户 ID 我试图传递 for 循环的 'i' 值,但我的代码似乎不起作用
代码
public class UsersView implements ActionListener {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
public UsersView() {
//Create the 16 buttons.
for (int i=0; i<16; i++) {
Button button = new Button("Click "+i);
button.setId(i); //this gives me and error 'Symbol not find' on the 'setId'
panel.add(button);
button.addActionListener(this);
}
panel.setBorder(BorderFactory.createBevelBorder(0, Color.lightGray, Color.yellow));
//panel.setBorder(BorderFactory.createEmptyBorder(300, 300, 100, 300));
panel.setLayout(new GridLayout(4,4)); //Rows Cols
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("App GUI");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// TODO code application logic here
new UsersView();
}
//On button click.
@Override
public void actionPerformed(ActionEvent e) {
//I know i have nothing here (yet) that is because the 'setId' gives me an error.
}
}
【问题讨论】:
-
你的按钮是什么?为什么要有
setId方法? -
目前我的按钮什么也不做,但稍后当单击按钮时,我想获取用户的 ID(当前是 for 循环的 int i)并删除记录。我想在 setId() 中传递值,然后在执行 getId() 的操作上传递。
-
这看起来像是
JTable或 example 的工作。并且可以通过签名e.getSource()获取触发事件的按钮,参见How to use Buttons教程,对于example -
这能回答你的问题吗? Is there a way to store data in a JButton?
-
您使用的是 Swing 还是 JavaFX?对于 Swing,您需要一个 JButton;对于 AWT(较旧的框架)一个 Button,并且只有 Button 具有 setId() 方法。您可能不应该将 Button 放入 JPanel。