【问题标题】:receiving input from text-field从文本字段接收输入
【发布时间】:2020-06-23 05:26:56
【问题描述】:

我现在正在学习 java,我想创建一个简单的程序来获取我的文本并将其放入 txt 文件中。这是我的代码,但没有任何效果,它会创建 txt 文件,但不会从文本字段输入实际文本。

public static void main(String[] args) {

        File file = new File("information.txt");
        JPanel panel = new JPanel();
        JFrame frame = new JFrame();
        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);

        JLabel user = new JLabel("user");
        user.setBounds(10, 25, 100, 25);
        panel.add(user);
        JTextField username = new JTextField();
        username.setBounds(100, 25, 300, 25);
        panel.add(username);

        JButton button = new JButton("login");
        button.setBounds(185, 150, 100, 50);
        panel.add(button);
        String name = username.getText();
        panel.setLayout(null);
        frame.setVisible(true);
        try {
        if (button.getModel().isPressed()){
            file.createNewFile();
        }
            PrintWriter pw = new PrintWriter(file);
            pw.println(name);
           pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void actionPerformed(ActionEvent e) {

    }

【问题讨论】:

    标签: java windows text build printwriter


    【解决方案1】:

    您必须将 ActionListener 添加到您的按钮。 然后,您必须在按下此 ActionListener 中的按钮时执行您想要执行的代码。 您还必须在单击按钮时从文本框中获取文本。

      button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        try {
          file.createNewFile();
          PrintWriter pw = new PrintWriter(file);
          pw.println(username.getText());
          pw.close();
        } catch (IOException e2) {
          e2.printStackTrace();
        }
      }
    });
    

    【讨论】:

    • 嗨@Jimmy,如果这个或任何答案解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
    猜你喜欢
    • 2018-03-05
    • 2013-10-01
    • 2014-06-08
    • 2011-04-11
    • 1970-01-01
    • 2011-03-04
    • 2015-07-24
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多