Java:我不能多次运行JTextArea? [英] Java: I can't run JTextArea multiple times?

查看:87
本文介绍了Java:我不能多次运行JTextArea?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,欢迎大家,这是我的第一个问题,所以我希望它是一个好问题。我正在探索swing API,我遇到了一个突然出现的问题。我基本上问自己,我是否可以构建一个可以使用 while()循环的程序,并在控制台中显示多个JTextArea,就像这样:

Hello and welcome everyone, this is my first question so I hope that it is a good one. I was exploring the swing API and I came across a question that popped in my head. I basically asked my self if I could build a program that could use a while() loop and display multiple JTextArea's like you could in the console like this:

while(x<100){
    System.out.println("This is the number: " + x)
    x++;
}

我希望这个在JFrame中打印输入代码,但我不能似乎弄明白了。我正在尝试使用JTextArea,但我真的不认为这是正确的方法。我试过标签,但根本不起作用。这是源代码。

I want this to print in the JFrame enter code here but I can't seem to figure out how. I'm attempting to use JTextArea's but I really don't think that is the right approach to it. I tried labels but that did not work at all. Here is the source code.

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;

public class MainFrame extends JFrame{

    public static int x=0;
    public static int y = 0;
    MainFrame(String title){
        super(title);   
        // Set Layout
        setLayout(new BorderLayout());

        while(x<100){
            y++;
            x++;
            System.out.println(x);
            Container pane= getContentPane();
            JTextArea x = new TextArea("Wateva" + y);
            JButton button= new JButton("Wateva man");
            pane.add(button, BorderLayout.SOUTH);
            pane.add(x);
        }
    }
}

在控制台x中显示每次递增1,表示循环正确运行。我作为初学者编写的唯一解释是,它创建了JTextArea,但后来它意识到x已经更新,所以它用新的覆盖旧的JTextArea,它为每个数字执行此操作,直到达到100我认为我使用了错误的JComponent类型,但这就是我在这里的原因。因此,如果有人可以给我提示或解决方法如何解决,这将非常感激。

In the console x is shown incrementing by 1 each time, meaning the loop runs correctly. The only explanation that I can make out as a beginner programer is that it creates the JTextArea but then it realizes that x has been updated and so it overrides the old JTextArea with a new one and it does this for every number until it gets to 100. I think I am using the wrong type of JComponent but that is why I'm here. So if anyone can give me tips or a solution on how to fix, this would be much appreciated.

推荐答案

欢迎阻止事件派遣线程。

Welcome to blocking the Event Dispatching Thread.

除其他事项外,EDT负责处理重新绘制请求。你永远不应该执行任何阻止EDT的操作,相反,你应该使用类似 SwingWorker

The EDT is responsible, for among other things, processing repainting requests. You should never performing any operations that block the EDT, instead, you should using something like a SwingWorker

拿一个请查看 Swing中的并发了解更多详情

Take a look at Concurrency in Swing for more details

更新为示例

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTextArea03 {

    public static void main(String[] args) {
        new TestTextArea03();
    }

    public TestTextArea03() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JTextArea textArea;

        private TestPane() {
            setLayout(new BorderLayout());
            textArea = new JTextArea(10, 10);
            add(new JScrollPane(textArea));

            new TextWorker().execute();
        }

        public class TextWorker extends SwingWorker<Void, String> {

            @Override
            protected void process(List<String> chunks) {
                for (String text : chunks) {
                    textArea.append(text + "\n");
                }
            }

            @Override
            protected Void doInBackground() throws Exception {
                Thread.sleep(1000);
                for (int x = 0; x < 10; x++) {
                    publish(String.valueOf(x));
                    Thread.sleep(250);
                }
                return null;
            }

        }

    }

}

或摇摆计时器

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTextArea03 {

    public static void main(String[] args) {
        new TestTextArea03();
    }

    public TestTextArea03() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JTextArea textArea;
        private int x;

        private TestPane() {
            setLayout(new BorderLayout());
            textArea = new JTextArea(10, 10);
            add(new JScrollPane(textArea));

            Timer timer = new Timer(250, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    x++;
                    textArea.append(String.valueOf(x) + "\n");
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();
        }        
    }    
}

这篇关于Java:我不能多次运行JTextArea?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆