使用时间延迟将Swing组件中的String数组的内容显示为迭代.JAVA

Don*_*ode 1 java iteration user-interface swing

我有一个字符串数组,我试图(逐个)显示为Java Swing组件中的幻灯片.我也试图在迭代之间添加延迟时间.

我尝试使用JTextArea执行此操作,并添加了一个动作侦听器.这是我现在的代码:

private class myActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        // A BUNCH OF TEXT PROCESSING

        //NOTE: myInfo.getContents() returns an ArrayList<myType>.
        Iterator<myType> iterator = myInfo.getContents().iterator();

        int i = 0;
        while (iterator.hasNext()) {
            myTextArea.setText(iterator.next().toString());
            // to add time betweeen iterations i wanted to use the thread
            // delay method.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的代码无效,因为JTextArea没有动作侦听器.

更新 说明:许多回复声明我应该为JTextArea使用ActionListener; 但是,Eclipse没有告诉我JTextArea有一个名为addActionListener的方法.

我有点困在这里,你觉得哪个Java Swing组件最适合这种情况?

我的数组中的文本可能很长,因此一个内衬标签不是一个好选择.

我还有哪些其他选择或方法?

非常感谢,任何帮助和建议表示赞赏.

Mad*_*mer 5

这是一个基本的例子是基于@Robin发布的建议

public class TestDisplayString {

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

    public TestDisplayString() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (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 List<String> content;
        private Iterator<String> iterator;

        public TestPane() {
            readText();
            setLayout(new BorderLayout());
            textArea = new JTextArea(10, 40);
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            add(new JScrollPane(textArea));
            iterator = content.iterator();

            Timer timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (iterator.hasNext()) {
                        textArea.setText(iterator.next());
                    } else {
                        ((Timer)e.getSource()).stop();
                    }
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();
        }

        protected void readText() {
            content = new ArrayList<>(25);
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Text.txt")));
                String text = null;
                while ((text = reader.readLine()) != null) {
                    if (text.trim().length() > 0) {
                        content.add(text);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

这是"Text.txt"文件的内容.

如何使用摆动计时器

A Swing timer (an instance of javax.swing.Timer) fires one or more action events after a specified delay. Don't confuse Swing timers with the general-purpose timer facility that was added to the java.util package in release 1.3. This page describes only Swing timers.

In general, we recommend using Swing timers rather than general-purpose timers for GUI-related tasks because Swing timers all share the same, pre-existing timer thread and the GUI-related task automatically executes on the event-dispatch thread. However, you might use a general-purpose timer if you don't plan on touching the GUI from the timer, or need to perform lengthy processing.

You can use Swing timers in two ways:

To perform a task once, after a delay.
For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.
To perform a task repeatedly.
For example, you might perform animation or update a component that displays progress toward a goal.
Run Code Online (Sandbox Code Playgroud)

Swing timers are very easy to use. When you create the timer, you specify an action listener to be notified when the timer "goes off". The actionPerformed method in this listener should contain the code for whatever task you need to be performed. When you create the timer, you also specify the number of milliseconds between timer firings. If you want the timer to go off only once, you can invoke setRepeats(false) on the timer. To start the timer, call its start method. To suspend it, call stop.

Note that the Swing timer's task is performed in the event dispatch thread. This means that the task can safely manipulate components, but it also means that the task should execute quickly. If the task might take a while to execute, then consider using a SwingWorker instead of or in addition to the timer. See Concurrency in Swing for instructions about using the SwingWorker class and information on using Swing components in multi-threaded programs.

Let's look at an example of using a timer to periodically update a component. The TumbleItem applet uses a timer to update its display at regular intervals. (To see this applet running, go to How to Make Applets. This applet begins by creating and starting a timer:

timer = new Timer(speed, this); timer.setInitialDelay(pause); timer.start();

The speed and pause variables represent applet parameters; as configured on the other page, these are 100 and 1900 respectively, so that the first timer event will occur in approximately 1.9 seconds, and recur every 0.1 seconds. By specifying this as the second argument to the Timer constructor, TumbleItem specifies that it is the action listener for timer events.

After starting the timer, TumbleItem begins loading a series of images in a background thread. Meanwhile, the timer events begin to occur, causing the actionPerformed method to execute:

public void actionPerformed(ActionEvent e) { //If still loading, can't animate. if (!worker.isDone()) { return; }

loopslot++;

if (loopslot >= nimgs) {
    loopslot = 0;
    off += offset;

    if (off < 0) {
        off = width - maxWidth;
    } else if (off + maxWidth > width) {
        off = 0;
    }
}

animator.repaint();

if (loopslot == nimgs - 1) {
    timer.restart();
} }
Run Code Online (Sandbox Code Playgroud)

在加载图像之前,worker.isDone返回false,因此有效地忽略了计时器事件.事件处理代码的第一部分只是设置动画控件的paintComponent方法中使用的值:loopslot(动画中下一个图形的索引)和off(下一个图形的水平偏移).

最终,looplot将到达图像阵列的末尾并重新开始.发生这种情况时,actionPerformed末尾的代码会重新启动计时器.这样做会在动画序列再次开始之前导致短暂的延迟.