[英]How can I connect my JButton to my JTextField to store the int I input into the JTextField?
I have created a simple GUI JFrame that has a textfield and button with their given action listeners. 我创建了一个简单的GUI JFrame,其中包含带有给定动作侦听器的文本字段和按钮。 But I am trying to connect the textfield to the button so that whenever I have inputted a series of numbers into the text field and press the button, my code stores the series of numbers to a variable that I will use later on.
但是我试图将文本字段连接到按钮,以便每当我在文本字段中输入一系列数字并按下按钮时,我的代码就会将一系列数字存储到一个变量中,稍后我将使用它。 How do I connect the two to start off with?
如何将两者连接起来?
I have looked at other stackoverflow posts, but I cannot seem to find a solution. 我看过其他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();
}
});
}
You've got an ActionListener
on your button, which is a good start. 您的按钮上有一个
ActionListener
,这是一个很好的开始。 You should write some logic to grab the text from the JTextField
, parse it as you want and store it in a data structure (eg an ArrayList). 您应该编写一些逻辑以从
JTextField
获取文本,根据需要对其进行解析并将其存储在数据结构(例如ArrayList)中。
You don't seem to need the JTextField
ActionListener
right now - move the id.getText()
call into the JButton
ActionListener
and store it in a variable. 您似乎现在不需要
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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.