使用TimerTask移动JPanels [英] Moving JPanels using TimerTask

查看:109
本文介绍了使用TimerTask移动JPanels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经建立了一个Java GUI,如下图所示(为令人毛骨悚然的娱乐活动道歉):

So I have set up a Java GUI like the one pictured below (apologies for horribly painted recreation):

Java GUI的布局

Layout for Java GUI

所有JPanel的大小均相等(未在图中很好地显示).我正在尝试做的是,使之在进度条中执行某些操作(即读取一些文本文件)时,JPanel会循环执行.正如红色中的一个将到达底部,橙色中的一个将到达顶部,因此在此循环中继续进行.我希望它们每半秒更改一次,并在程序打开后等待2秒钟才能开始移动.我也希望它们在进度条之一达到100%时停止.

All of the JPanels are equal size (not shown well in the drawing). What I'm trying to do is make it so that when I am doing something with the progress bars (I.E reading some text files in), the JPanels will cycle through. As in the red one will go to the bottom, the orange one will go to the top, and thus keep going in this cycle. I'd like them to change every half second and wait 2 seconds after the program is open to start moving. I'd also like them to stop when one of the progress bars reaches 100%.

经过阅读后,我认为Java TimerTask类将非常适合此操作,但是我没有使用它的经验,并且不确定如何使用它来做类似的事情.

After doing some reading I think the Java TimerTask class would be a good fit for this, but I have no experience with it and am not really sure how I would go about doing something like this with it.

任何有关如何实现此目标的提示或想法将不胜感激!

Any hints or ideas at how to go about this would be greatly appreciated!

推荐答案

保留颜色模型(如果用户看到的是"Red JPanel",则为文本)会容易得多.只需更改现有面板的BG颜色,使其适合于用作这些color(/text)组合数组的索引的计数器即可.

It would be far simpler to keep a model of colors (and text, if 'Red JPanel' is part of what the user sees) & simply change the BG colors of the existing panels appropriate to a counter used as an index to an array of those color(/text) combos.

如@MadProgrammer所述,Swing Timer更合​​适,因为Swing计时器可确保在EDT上进行更新.或更确切地说,是两个计时器.第一个将是单发计时器,以延迟两秒钟.第二个将循环颜色.

As mentioned by @MadProgrammer, A Swing Timer would be more appropriate, as the Swing timer ensures updates are made on the EDT. Or rather two timers. The 1st would be a single shot timer to delay two seconds. The 2nd would cycle the colors.

喜欢这个(调整颜色和数字以适应需要):

Like this (adjust colors and numbers to need):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class ColorCycler {

    private JComponent ui = null;
    Color[] colors = {
        Color.RED,
        Color.ORANGE,
        Color.YELLOW,
        Color.GREEN,
        Color.CYAN.darker(),
        Color.MAGENTA.darker(),
        Color.MAGENTA.darker().darker()
    };
    int counter = 0;
    JPanel[] panels = new JPanel[colors.length];

    ColorCycler() {
        initUI();
    }

    public void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));
        ui.setBackground(Color.CYAN);

        ui.add(new JLabel(
                "Clock", SwingConstants.CENTER), BorderLayout.PAGE_START);
        ui.add(new JLabel(
                "Progress Bars", SwingConstants.CENTER), BorderLayout.PAGE_END);

        JPanel colorPanel = new JPanel(new GridLayout(0, 1));
        Border border = new EmptyBorder(new Insets(10, 200, 10, 200));
        for (int ii=0; ii<colors.length; ii++) {
            JPanel p = new JPanel();
            p.setBorder(border);
            panels[ii] = p;
            colorPanel.add(p);
        }
        ui.add(colorPanel, BorderLayout.CENTER);

        ActionListener colorListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                counter++;
                setColors();
            }
        };
        final Timer colorCycleTimer = new Timer(50, colorListener);

        ActionListener delayListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                colorCycleTimer.start();
            }
        };
        Timer delayTimer = new Timer(2000, delayListener);
        delayTimer.setRepeats(false);
        delayTimer.start();

        setColors();
    }

    private void setColors() {
        for (int ii=0; ii<colors.length; ii++) {
            panels[(counter+ii)%colors.length].setBackground(colors[ii]);
        }
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                ColorCycler o = new ColorCycler();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

这篇关于使用TimerTask移动JPanels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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