我已经创建了一个简单的图形用户界面JFrame,它有一个文本字段和按钮,以及它们给定的操作侦听器。但我正在尝试将文本字段连接到按钮,以便每当我在文本字段中输入一系列数字并按下按钮时,我的代码都会将这一系列数字存储到稍后将使用的变量中。我如何将这两者联系起来?
我看过其他的stackoverflow帖子,但我似乎找不到解决方案。
//textfield
id = new JTextField(7);// accepts up to 7 characters
//buttons
go = new JButton("Go");
go.setBounds(100, 150, 140, 40);
CL = new JButton("Cheap Lock");
CL.setBounds(100,300,140,40);
//JLabel that shows button has stored the input
go1 = new JLabel();
go1.setBounds(10, 160, 200, 100);
//button action listener
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
go1.setText("Student ID has been submitted.");
}
});
//textfield actionlistener
id.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
id.getText();
}
});
}发布于 2019-04-11 01:31:02
您的按钮上有一个ActionListener,这是一个很好的开始。您应该编写一些逻辑来从JTextField中获取文本,根据需要对其进行解析,并将其存储在数据结构(例如ArrayList)中。
您现在似乎不需要JTextField ActionListener -将id.getText()调用移到JButton ActionListener中并将其存储在一个变量中。
//textfield
id = new JTextField(7);// accepts up to 7 characters
//buttons
go = new JButton("Go");
go.setBounds(100, 150, 140, 40);
CL = new JButton("Cheap Lock");
CL.setBounds(100,300,140,40);
//JLabel that shows button has stored the input
go1 = new JLabel();
go1.setBounds(10, 160, 200, 100);
//button action listener
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
go1.setText("Student ID has been submitted.");
String value = id.getText();
// logic here - e.g. Integer.parseInt();
}
});https://stackoverflow.com/questions/55618258
复制相似问题