简体   繁体   English

在ActionListener中连续设置JTextArea文本

[英]Continually set JTextArea text within ActionListener

I am trying to create a button that, when pressed, will display text in a JTextArea , continually updating every time a step in the loop is run after a wait period. 我试图创建一个按钮,当按下该按钮时,它将在JTextArea显示文本,每次在等待时间后运行循环中的某个步骤时,该按钮都会不断更新。 The code I have now prints what it would look look like on the first step of the loop, then stops. 现在,我所拥有的代码将在循环的第一步中显示其外观,然后停止。 The action I am referring to is at the bottom under //Actions . 我所指的动作位于//Actions的底部。

public class MainWindow {

    private JFrame frmMcakennaAntivirus;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainWindow window = new MainWindow();
                    window.frmMcakennaAntivirus.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public MainWindow() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmMcakennaAntivirus = new JFrame();
        frmMcakennaAntivirus.setResizable(false);
        frmMcakennaAntivirus.setTitle("McAkenna Anti-Virus");
        frmMcakennaAntivirus.setAlwaysOnTop(true);
        frmMcakennaAntivirus.setBounds(100, 100, 303, 197);
        frmMcakennaAntivirus.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWidths = new int[]{0, 149, 135, 0, 0};
        gridBagLayout.rowHeights = new int[]{0, 14, 0, 24, 45, 0, 0};
        gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
        gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
        frmMcakennaAntivirus.getContentPane().setLayout(gridBagLayout);

        JSeparator separator = new JSeparator();
        GridBagConstraints gbc_separator = new GridBagConstraints();
        gbc_separator.insets = new Insets(0, 0, 5, 5);
        gbc_separator.gridx = 1;
        gbc_separator.gridy = 0;
        frmMcakennaAntivirus.getContentPane().add(separator, gbc_separator);

        JSeparator separator_1 = new JSeparator();
        GridBagConstraints gbc_separator_1 = new GridBagConstraints();
        gbc_separator_1.insets = new Insets(0, 0, 5, 5);
        gbc_separator_1.gridx = 0;
        gbc_separator_1.gridy = 1;
        frmMcakennaAntivirus.getContentPane().add(separator_1, gbc_separator_1);

        JButton btnBeginScan = new JButton("Begin Scan");
        btnBeginScan.setFont(new Font("Tahoma", Font.BOLD, 11));
        btnBeginScan.setForeground(new Color(0, 0, 0));
        btnBeginScan.setBackground(new Color(124, 252, 0));
        GridBagConstraints gbc_btnBeginScan = new GridBagConstraints();
        gbc_btnBeginScan.insets = new Insets(0, 0, 5, 5);
        gbc_btnBeginScan.gridx = 1;
        gbc_btnBeginScan.gridy = 1;
        frmMcakennaAntivirus.getContentPane().add(btnBeginScan, gbc_btnBeginScan);

        JButton btnFixProblems = new JButton("Fix Problems");
        btnFixProblems.setBackground(new Color(127, 255, 0));
        GridBagConstraints gbc_btnFixProblems = new GridBagConstraints();
        gbc_btnFixProblems.insets = new Insets(0, 0, 5, 5);
        gbc_btnFixProblems.gridx = 2;
        gbc_btnFixProblems.gridy = 1;
        frmMcakennaAntivirus.getContentPane().add(btnFixProblems, gbc_btnFixProblems);

        JSeparator separator_2 = new JSeparator();
        GridBagConstraints gbc_separator_2 = new GridBagConstraints();
        gbc_separator_2.insets = new Insets(0, 0, 5, 0);
        gbc_separator_2.gridx = 3;
        gbc_separator_2.gridy = 1;
        frmMcakennaAntivirus.getContentPane().add(separator_2, gbc_separator_2);

        Choice choice = new Choice();
        choice.setBackground(SystemColor.scrollbar);
        GridBagConstraints gbc_choice = new GridBagConstraints();
        gbc_choice.insets = new Insets(0, 0, 5, 5);
        gbc_choice.fill = GridBagConstraints.HORIZONTAL;
        gbc_choice.gridx = 1;
        gbc_choice.gridy = 2;
        frmMcakennaAntivirus.getContentPane().add(choice, gbc_choice);
        choice.add("Full System Scan");
        choice.add("Quick Scan");

        JProgressBar progressBar = new JProgressBar();
        GridBagConstraints gbc_progressBar = new GridBagConstraints();
        gbc_progressBar.fill = GridBagConstraints.BOTH;
        gbc_progressBar.insets = new Insets(0, 0, 5, 5);
        gbc_progressBar.gridx = 1;
        gbc_progressBar.gridy = 3;
        frmMcakennaAntivirus.getContentPane().add(progressBar, gbc_progressBar);

        final JTextArea textArea = new JTextArea();
        textArea.setLineWrap(true);
        textArea.setFont(new Font("Source Sans Pro Light", Font.PLAIN, 12));
        textArea.setEditable(false);
        textArea.setBackground(SystemColor.inactiveCaption);
        GridBagConstraints gbc_textArea = new GridBagConstraints();
        gbc_textArea.insets = new Insets(0, 0, 5, 5);
        gbc_textArea.fill = GridBagConstraints.BOTH;
        gbc_textArea.gridx = 1;
        gbc_textArea.gridy = 4;
        frmMcakennaAntivirus.getContentPane().add(textArea, gbc_textArea);

        JButton btnCancelScan = new JButton("Cancel Scan");
        btnCancelScan.setBackground(new Color(255, 0, 0));
        GridBagConstraints gbc_btnCancelScan = new GridBagConstraints();
        gbc_btnCancelScan.insets = new Insets(0, 0, 0, 5);
        gbc_btnCancelScan.gridx = 1;
        gbc_btnCancelScan.gridy = 5;
        frmMcakennaAntivirus.getContentPane().add(btnCancelScan, gbc_btnCancelScan);



        //Actions

        btnBeginScan.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                for (int x= 1; x < 6735; x++){
                    textArea.setText("Files scanned: " + x + "\nViruses found: " + x/350);
                    try {
                        Thread.sleep(randInt(90, 200));
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        });

    }

    public static int randInt(int min, int max) {

        Random rand = null;

        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }

}

You're blocking the Event Dispatching Thread, which is responsible for, among other things, processing repaint requests. 您正在阻止事件调度线程,该线程负责处理重绘请求。

Swing is a single threaded frame, you should never run long running or blocking operations from within the context of the EDT. Swing是一个单线程框架,切勿在EDT上下文中长时间运行或阻止操作。

See Concurrency in Swing for more details 有关更多详细信息,请参见Swing中的并发。

Use a SwingWorker or Swing Timer instead. 请改用SwingWorker或Swing Timer

See Worker Threads and SwingWorker and How to use Swing Timers for more details 有关更多详细信息,请参见工作线程和SwingWorker以及如何使用Swing计时器

As a side note, you're also going to encounter a NullPointerException ... 附带说明,您还将遇到NullPointerException ...

Random rand = null;
int randomNum = rand.nextInt((max - min) + 1) + min;

When using Random , you should create a single instance and re-use for as long as you need it. 使用Random ,您应该创建一个实例并在需要时重复使用。 This will ensure that the values you get from it are properly (as best as it can) randomised, otherwise you may end up with repeating values in a very short period of time 这将确保您从中获得的值正确(尽其所能)是随机的,否则最终可能会在很短的时间内重复出现这些值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM