该代码在新的jframe中打印输入数字,但是我无法在input的变量getText()中存储任何内容。请告诉我我在做什么错。

我的代码:

  import javax.swing.*;

  import java.awt.*;
  import java.awt.event.*;

  public class MainFrame extends JFrame implements ActionListener
   {
static boolean a=false;

 public MainFrame()
{
    setTitle("Square's Root Finder");
    setSize(350,100);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLookAndFeel();

    setLayout(new FlowLayout());
    JButton but1 = new JButton("Calculate");
    JLabel label1= new JLabel("Enter the number:", JLabel.RIGHT);
    JTextField t = new JTextField(20);


    if (a==true)

    {
        String input = t.getText();

        System.out.print(input);
        JLabel label2=new JLabel(input);
        add(label2);
    }

    add(but1);
    add(label1);
    add(t);
    but1.addActionListener(this);

}


 public static void main(String[] args)
   {
      new MainFrame().setVisible(true);

   }

public void actionPerformed(ActionEvent arg0)
           {

    String cmd = arg0.getActionCommand();
    if(cmd.equals("Calculate"))
    {
        a=true;
        new MainFrame().setVisible(true);
    }

}
       }

最佳答案

每次按MainFrame都会创建一个新的but1,因此每次t都会在清空之前被清空。

new MainFrame().setVisible(true); //calls MainFrame() while creating new object instance
...
JTextField t = new JTextField(20); //creates an empty text field
...
if (a==true)
{
  String input = t.getText(); //t has just been created so it is empty
  System.out.print(input); //t is empty so input is empty
  ...
}

关于java - getText()无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20496439/

10-13 05:00