Java JProgressBar喷漆问题

Java JProgressBar喷漆问题,java,swing,jframe,jprogressbar,event-dispatch-thread,Java,Swing,Jframe,Jprogressbar,Event Dispatch Thread,当我设置JProgressBar的最小值、值和最大值时,它们不会更新,除非我关闭窗口并重新打开它 图片: 有人能给我一些见解吗?这件事让我抓狂。我进行了测试,以确保正确地完成了解析(这是正确的)。我试着直接输入数字。很明显,它是工作的,它只是没有显示第一次打开窗口(这使我认为,如果我更新值,它将只显示最后的值) *编辑* 女士们,先生们…我可以介绍…SSCE。我很抱歉发布这个,因为现在你会感觉到我的痛苦:x 您可能正在EDT(事件调度线程)中执行工作。此线程有一个事件队列,它们一次按顺序调

当我设置JProgressBar的最小值、值和最大值时,它们不会更新,除非我关闭窗口并重新打开它


图片:

有人能给我一些见解吗?这件事让我抓狂。我进行了测试,以确保正确地完成了解析(这是正确的)。我试着直接输入数字。很明显,它是工作的,它只是没有显示第一次打开窗口(这使我认为,如果我更新值,它将只显示最后的值)

*编辑*

女士们,先生们…我可以介绍…SSCE。我很抱歉发布这个,因为现在你会感觉到我的痛苦:x



您可能正在EDT(事件调度线程)中执行工作。此线程有一个事件队列,它们一次按顺序调度一个,因为AWT不是线程安全的。这允许UI更新事件并对事件做出反应(如重新绘制或调用器之类的编程事件,或鼠标和按键事件之类的用户事件)

因此,当您在EDT中工作时,您会阻止线程并阻止它分派事件,例如重新绘制、单击、按键事件等

通常解决方案是将工件移动到另一个线程中,例如使用


顺便说一句,Thread.sleep(long)是一个静态方法,因此不需要调用currentThread(),如果需要的话,只需调用Thread.sleep(…)。但同样,您应该避免在EDT中这样做,因为它会阻止它,也会阻止UI。

您可能正在EDT(事件调度线程)中执行工作。此线程有一个事件队列,它们一次按顺序调度一个,因为AWT不是线程安全的。这允许UI更新事件并对其作出反应(可以是程序事件,如重新绘制或调用器,也可以是用户事件,如鼠标和按键事件)

因此,当您在EDT中工作时,您会阻止线程并阻止它分派事件,例如重新绘制、单击、按键事件等

通常解决方案是将工件移动到另一个线程中,例如使用


顺便说一句,Thread.sleep(long)是一个静态方法,因此不需要调用currentThread(),如果需要的话,只需调用Thread.sleep(…)。但同样,您应该避免在EDT中这样做,因为它会阻止它,也会阻止UI。

这对所有
Swing JComponents
可运行的
线程睡眠(int)都有效
将准动画添加到GUI

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

public class ShakingButtonDemo implements Runnable {

    private JButton button;
    private JRadioButton radioWholeButton;
    private JRadioButton radioTextOnly;

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new ShakingButtonDemo());
    }

    @Override
    public void run() {
        radioWholeButton = new JRadioButton("The whole button");
        radioTextOnly = new JRadioButton("Button text only");
        radioWholeButton.setSelected(true);
        ButtonGroup bg = new ButtonGroup();
        bg.add(radioWholeButton);
        bg.add(radioTextOnly);
        button = new JButton("  Shake with this Button  ");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                shakeButton(radioWholeButton.isSelected());
            }
        });
        JPanel p1 = new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("Shake Options"));
        p1.setLayout(new GridLayout(0, 1));
        p1.add(radioWholeButton);
        p1.add(radioTextOnly);
        JPanel p2 = new JPanel();
        p2.setLayout(new GridLayout(0, 1));
        p2.add(button);
        JFrame frame = new JFrame();
        frame.setTitle("Shaking Button Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(p1, BorderLayout.NORTH);
        frame.add(p2, BorderLayout.SOUTH);
        frame.setSize(240, 160);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void shakeButton(final boolean shakeWholeButton) {
        final Point point = button.getLocation();
        final Insets margin = button.getMargin();
        final int delay = 75;
        Runnable r = new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 30; i++) {
                    try {
                        if (shakeWholeButton) {
                            moveButton(new Point(point.x + 5, point.y));
                            Thread.sleep(delay);
                            moveButton(point);
                            Thread.sleep(delay);
                            moveButton(new Point(point.x - 5, point.y));
                            Thread.sleep(delay);
                            moveButton(point);
                            Thread.sleep(delay);
                        } else {// text only
                            setButtonMargin(new Insets(margin.top, margin.left + 3, margin.bottom, margin.right - 2));
                            Thread.sleep(delay);
                            setButtonMargin(margin);
                            Thread.sleep(delay);
                            setButtonMargin(new Insets(margin.top, margin.left - 2, margin.bottom, margin.right + 3));
                            Thread.sleep(delay);
                            setButtonMargin(margin);
                            Thread.sleep(delay);
                        }
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        };
        Thread t = new Thread(r);
        t.start();
    }

    private void moveButton(final Point p) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                button.setLocation(p);
            }
        });
    }

    private void setButtonMargin(final Insets margin) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                button.setMargin(margin);
            }
        });
    }
}
import java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
公共类ShakingButtonDemo实现Runnable{
私人按钮;
私人JRadioButton radioWholeButton;
仅限私人JRadioButton radioTextOnly;
公共静态void main(字符串[]args)引发异常{
调用器(新的ShakingButtonDemo());
}
@凌驾
公开募捐{
radioWholeButton=新的JRadioButton(“整个按钮”);
radioTextOnly=新的JRadioButton(“仅按钮文本”);
radioWholeButton.setSelected(真);
ButtonGroup bg=新建ButtonGroup();
背景添加(无线全屏按钮);
背景添加(仅限RadioText);
按钮=新的JButton(“用此按钮摇动”);
addActionListener(新建ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
shakeButton(radioWholeButton.isSelected());
}
});
JPanel p1=新的JPanel();
p1.设置顺序(BorderFactory.createTitledBorder(“抖动选项”);
p1.设置布局(新网格布局(0,1));
p1.添加(radioWholeButton);
p1.添加(仅限无线文本);
JPanel p2=新的JPanel();
p2.设置布局(新网格布局(0,1));
p2.添加(按钮);
JFrame=新JFrame();
frame.setTitle(“抖动按钮演示”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
框架。添加(p1,边界布局。北);
框架。添加(p2,边界布局。南部);
框架设置尺寸(240160);
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
私有void shakeButton(最终布尔shakeWholeButton){
最终点=button.getLocation();
最终插入页边距=button.getMargin();
最终整数延迟=75;
Runnable r=新的Runnable(){
@凌驾
公开募捐{
对于(int i=0;i<30;i++){
试一试{
如果(晃动整个按钮){
移动按钮(新点(点x+5,点y));
睡眠(延迟);
移动按钮(点);
睡眠(延迟);
移动按钮(新点(点x-5,点y));
睡眠(延迟);
移动按钮(点);
睡眠(延迟);
}else{//仅限文本
setButtonMargin(新插图(margin.top、margin.left+3、margin.bottom、margin.right-2));
睡眠(延迟);
setButtonMargin(边缘);
睡眠(延迟);
setButtonMargin(新插图(margin.top,margin.left-2,margin.bottom,margin.right+3));
睡眠(延迟);
setButtonMargin(边缘);
睡眠(延迟);
}
}捕获(中断异常例外){
例如printStackTrace();
}
}
}
};
螺纹t=新螺纹(r);
t、 start();
}
专用无效移动按钮(终点p){
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
按钮设置位置(p);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ShakingButtonDemo implements Runnable {

    private JButton button;
    private JRadioButton radioWholeButton;
    private JRadioButton radioTextOnly;

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new ShakingButtonDemo());
    }

    @Override
    public void run() {
        radioWholeButton = new JRadioButton("The whole button");
        radioTextOnly = new JRadioButton("Button text only");
        radioWholeButton.setSelected(true);
        ButtonGroup bg = new ButtonGroup();
        bg.add(radioWholeButton);
        bg.add(radioTextOnly);
        button = new JButton("  Shake with this Button  ");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                shakeButton(radioWholeButton.isSelected());
            }
        });
        JPanel p1 = new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("Shake Options"));
        p1.setLayout(new GridLayout(0, 1));
        p1.add(radioWholeButton);
        p1.add(radioTextOnly);
        JPanel p2 = new JPanel();
        p2.setLayout(new GridLayout(0, 1));
        p2.add(button);
        JFrame frame = new JFrame();
        frame.setTitle("Shaking Button Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(p1, BorderLayout.NORTH);
        frame.add(p2, BorderLayout.SOUTH);
        frame.setSize(240, 160);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void shakeButton(final boolean shakeWholeButton) {
        final Point point = button.getLocation();
        final Insets margin = button.getMargin();
        final int delay = 75;
        Runnable r = new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 30; i++) {
                    try {
                        if (shakeWholeButton) {
                            moveButton(new Point(point.x + 5, point.y));
                            Thread.sleep(delay);
                            moveButton(point);
                            Thread.sleep(delay);
                            moveButton(new Point(point.x - 5, point.y));
                            Thread.sleep(delay);
                            moveButton(point);
                            Thread.sleep(delay);
                        } else {// text only
                            setButtonMargin(new Insets(margin.top, margin.left + 3, margin.bottom, margin.right - 2));
                            Thread.sleep(delay);
                            setButtonMargin(margin);
                            Thread.sleep(delay);
                            setButtonMargin(new Insets(margin.top, margin.left - 2, margin.bottom, margin.right + 3));
                            Thread.sleep(delay);
                            setButtonMargin(margin);
                            Thread.sleep(delay);
                        }
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        };
        Thread t = new Thread(r);
        t.start();
    }

    private void moveButton(final Point p) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                button.setLocation(p);
            }
        });
    }

    private void setButtonMargin(final Insets margin) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                button.setMargin(margin);
            }
        });
    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class SwingWorkerExample extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    private final JButton startButton, stopButton;
    private JScrollPane scrollPane = new JScrollPane();
    private JList listBox = null;
    private DefaultListModel listModel = new DefaultListModel();
    private final JProgressBar progressBar;
    private mySwingWorker swingWorker;

    public SwingWorkerExample() {
        super("SwingWorkerExample");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new GridLayout(2, 2));
        startButton = makeButton("Start");
        stopButton = makeButton("Stop");
        stopButton.setEnabled(false);
        progressBar = makeProgressBar(0, 99);
        listBox = new JList(listModel);
        scrollPane.setViewportView(listBox);
        add(scrollPane);
        //Display the window.
        pack();
        setVisible(true);
    }
//Class SwingWorker<T,V> T - the result type returned by this SwingWorker's doInBackground
//and get methods V - the type used for carrying out intermediate results by this SwingWorker's
//publish and process methods

    private class mySwingWorker extends javax.swing.SwingWorker<ArrayList<Integer>, Integer> {
//The first template argument, in this case, ArrayList<Integer>, is what s returned by doInBackground(),
//and by get(). The second template argument, in this case, Integer, is what is published with the
//publish method. It is also the data type which is stored by the java.util.List that is the parameter
//for the process method, which recieves the information published by the publish method.

        @Override
        protected ArrayList<Integer> doInBackground() {
//Returns items of the type given as the first template argument to the SwingWorker class.
            if (javax.swing.SwingUtilities.isEventDispatchThread()) {
                System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() returned true.");
            }
            Integer tmpValue = new Integer(1);
            ArrayList<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < 100; i++) {
                for (int j = 0; j < 100; j++) { //find every 100th prime, just to make it slower
                    tmpValue = FindNextPrime(tmpValue.intValue());
//isCancelled() returns true if the cancel() method is invoked on this class. That is the proper way
//to stop this thread. See the actionPerformed method.
                    if (isCancelled()) {
                        System.out.println("SwingWorker - isCancelled");
                        return list;
                    }
                }
//Successive calls to publish are coalesced into a java.util.List, which is what is received by process,
//which in this case, isused to update the JProgressBar. Thus, the values passed to publish range from
//1 to 100.
                publish(new Integer(i));
                list.add(tmpValue);
            }
            return list;
        }//Note, always use java.util.List here, or it will use the wrong list.

        @Override
        protected void process(java.util.List<Integer> progressList) {
//This method is processing a java.util.List of items given as successive arguments to the publish method.
//Note that these calls are coalesced into a java.util.List. This list holds items of the type given as the
//second template parameter type to SwingWorker. Note that the get method below has nothing to do with the
//SwingWorker get method; it is the List's get method. This would be a good place to update a progress bar.
            if (!javax.swing.SwingUtilities.isEventDispatchThread()) {
                System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() + returned false.");
            }
            Integer percentComplete = progressList.get(progressList.size() - 1);
            progressBar.setValue(percentComplete.intValue());
        }

        @Override
        protected void done() {
            System.out.println("doInBackground is complete");
            if (!javax.swing.SwingUtilities.isEventDispatchThread()) {
                System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() + returned false.");
            }
            try {
//Here, the SwingWorker's get method returns an item of the same type as specified as the first type parameter
//given to the SwingWorker class.
                ArrayList<Integer> results = get();
                for (Integer i : results) {
                    listModel.addElement(i.toString());
                }
            } catch (Exception e) {
                System.out.println("Caught an exception: " + e);
            }
            startButton();
        }

        boolean IsPrime(int num) { //Checks whether a number is prime
            int i;
            for (i = 2; i <= num / 2; i++) {
                if (num % i == 0) {
                    return false;
                }
            }
            return true;
        }

        protected Integer FindNextPrime(int num) { //Returns next prime number from passed arg.
            do {
                if (num % 2 == 0) {
                    num++;
                } else {
                    num += 2;
                }
            } while (!IsPrime(num));
            return new Integer(num);
        }
    }

    private JButton makeButton(String caption) {
        JButton b = new JButton(caption);
        b.setActionCommand(caption);
        b.addActionListener(this);
        getContentPane().add(b);
        return b;
    }

    private JProgressBar makeProgressBar(int min, int max) {
        JProgressBar progressBar1 = new JProgressBar();
        progressBar1.setMinimum(min);
        progressBar1.setMaximum(max);
        progressBar1.setStringPainted(true);
        progressBar1.setBorderPainted(true);
        getContentPane().add(progressBar1);
        return progressBar1;
    }

    private void startButton() {
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        System.out.println("SwingWorker - Done");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("Start" == null ? e.getActionCommand() == null : "Start".equals(e.getActionCommand())) {
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
// Note that it creates a new instance of the SwingWorker-derived class. Never reuse an old one.
            (swingWorker = new mySwingWorker()).execute(); // new instance
        } else if ("Stop" == null ? e.getActionCommand() == null : "Stop".equals(e.getActionCommand())) {
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            swingWorker.cancel(true); // causes isCancelled to return true in doInBackground
            swingWorker = null;
        }
    }

    public static void main(String[] args) {
// Notice that it kicks it off on the event-dispatching thread, not the main thread.
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                SwingWorkerExample swingWorkerExample = new SwingWorkerExample();
            }
        });
    }
}
import javax.swing.*;

public class ProgressBarMinValue {
   private static void createAndShowGui() {
      JProgressBar progressBar = new JProgressBar();

      int value = 234;
      int denominator = 400;
      int minValue = 200;
      progressBar.setString(value + "/" + denominator);
      progressBar.setMinimum(minValue);
      System.out.println("value := " + value);

      progressBar.setValue(value);  // (A)

      progressBar.setMaximum(denominator);

      // progressBar.setValue(value);  // (B)

      JPanel mainPanel = new JPanel();
      mainPanel.add(progressBar);

      JOptionPane.showMessageDialog(null, mainPanel);
      System.out.println("progressBar.getValue() := " + progressBar.getValue());
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}