![](/img/trans.png)
[英]How can I make an instance return the String of a field directly in Java as I could do in Python with __radd__?
[英]How can I return the input directly in java?
用户在文本字段中输入数字并单击按钮后,我想在另一个文本字段中返回值,我不确定我需要哪个类,请问有什么提示吗? 非常感谢,这是我的代码:
private void newNumber(Container container){
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraint = new GridBagConstraints();
//add the new number
labelname = new JLabel("Enter the number: ");
constraint.gridx = 0;
constraint.gridy = 0;
panel.add(labelname, constraint);
number= new JTextField(10);
constraint.gridx = 1;
constraint.gridy = 0;
panel.add(number, constraint);
addnumber = new JButton("Add number");
constraint.gridx = 0;
constraint.gridy = 3;
panel.add(addnumber, constraint);
container.add(panel,"North");
}
我知道它应该有一个关于ActionListener的方法,但我仍在弄清楚:)
基本上,您为按钮分配了一个ActionListener以便对click事件做出反应。 在此侦听器中,您将获取文本字段的值并将其分配给其他字段。
JButton yourButton= new JButton("Click me");
JTextField textField = new JTextField("Some initial value Textfield 1");
JTextField textField2 = new JTextField("Some initial value Textfield 2");
yourButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Get value of textfield 1
String currValue = textField.getText();
// Set value for textfield 2
textField2.setText(currValue);
}
});
public class FramTest extends JFrame{
public static void main(String[] args){
FramTest framTest = new FramTest();
JPanel panel = new JPanel(new GridBagLayout());
//add the new number
JLabel labelname = new JLabel("Enter the number: ");
panel.add(labelname);
final JTextField number= new JTextField(10);
panel.add(number);
JButton addnumber = new JButton("Add number");
panel.add(addnumber);
final JTextField numberright= new JTextField(10);
addnumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
numberright.setText(number.getText());
}
});
panel.add(numberright);
framTest.add(panel);
framTest.show();
}
}
您必须在按钮上添加一个ActionListener,然后在侦听器中可以添加对新方法的调用以执行所需的操作。 我假设您想从文本字段“ number”中获取文本,并且要在另一个名为“ secondTextfield”的文本字段中写入值。
// Add the lister to the button
addnumber.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// Call a function to perform the action
setTheText(evt);
}
});
// Function to set the text
private void setTheText(java.awt.event.ActionEvent evt) {
secondTextfield.set(number.getText());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.