簡體   English   中英

如何直接在Java中返回輸入?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM