本文介绍了Java Swing 按钮冻结程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Swing 编写了一个简单的应用程序,用于将文本写入文件.这是我的主要课程:

I wrote a simple application in Swing that writes text to a file. Here is my main class:

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class WritingTextToFileApp {

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new MainFrame("Application");

            frame.setSize(500, 400);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            }
        });

    }
}

这是另一个类:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class MainFrame extends JFrame {

public MainFrame(String title) {
    super(title);
    //Set Layout Manager
    setLayout(new BorderLayout());
    //Create Swing Components
    JTextArea textArea = new JTextArea();
    JButton button = new JButton("Add");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Scanner scanner = new Scanner(System.in);
            String input = scanner.nextLine();
             File file = new File("C:\\Users\\Vincent Wen\\Desktop\\Test.txt");
            try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
                br.write(input);
                br.newLine();
            } catch (IOException ex) {
                System.out.println("Unable to write to file:" + file.toString());
            }
        }

    });
    //Add Swing components to conent pane
    Container c = getContentPane();
    c.add(textArea, BorderLayout.CENTER);
    c.add(button, BorderLayout.SOUTH);
}

}

每当我按下按钮时,程序就会冻结,什么也没有发生.代码有问题吗?我是 Swing 的新手,因此不胜感激.

Whenever I press the button, the program freezes and nothing happens. Is there something wrong with the code? I am new to Swing so any help would be appreciated.

推荐答案

Swing 在处理 GUI 输入和渲染的同一线程中同步运行这些操作.这意味着当您单击按钮时,它会等待动作侦听器完成运行,然后再返回处理输入和绘制 GUI.在这种情况下,它会有效地阻止 GUI 运行,直到您在控制台中键入内容为止.

Swing runs the actions synchronously in the same thread that's handling the GUI input and rendering. That means that when you click the button, it waits for the action listener to complete running before it goes back to handling input and drawing the GUI. In this case, it's effectively stopping the GUI from running until you type something into the console.

您可以使用 SwingWorker 来运行它是异步的,以便在运行操作时继续运行 GUI.

You can use SwingWorker to run it asynchronously so that it continues running the GUI while it runs the action.

这篇关于Java Swing 按钮冻结程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:22