简体   繁体   中英

JPanel setColor() repeatation is not working properly or am I doing something wrong?

So I have this method that takes a JFrame, and two JPanels as arguments, and makes a fadeout/fadein transition from one Jpanel to another. All I do is add a new Jpanel on the first Jpanel on the parameter and keep updating its background color in a loop until it becomes black from transparent. The first half works fine until it comes to second half where I try to run a while loop where it keeps looping until the background color of the tint panel on the 2nd Jpanel becomes transparent from black. It stays black the whole time.

Any thoughts on this? What am I doing wrong?

public static void fadeShow(JFrame frame, JPanel panel1, JPanel panel2) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    JPanel tint = new JPanel();
                    tint.setOpaque(true);
                    tint.setBackground(new Color(0,0,0,0));
                    tint.setBounds(frame.getBounds().x+1, frame.getBounds().y, frame.getWidth(), frame.getHeight());
                    panel1.add(tint);
                    Thread.sleep(1500);
                    int i = 5;
                    while(i <= 255) {
                        tint.setBackground(new Color(0,0,0,i));
                        i+=25;
                        Thread.sleep(50);
                    }
                    panel1.setVisible(false);
                    tint.setVisible(false);
                    panel1.remove(tint);
                    tint = new JPanel();
                    tint.setOpaque(true);
                    tint.setBackground(new Color(0,0,0,255));
                    tint.setBounds(frame.getBounds().x+1, frame.getBounds().y, frame.getWidth(), frame.getHeight());
                    panel2.add(tint);
                    frame.add(panel2);
                    i = 250;
                    while(i > 0) {
                        tint.setBackground(new Color(0,0,0,i));
                        i-=25;
                        Thread.sleep(50);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }).start();




}

Your program flouts Swing threading rules by making significant Swing gui state changes from within a background thread. This risks freezing your GUI or causing strange visual artifacts. Instead use a Swing Timer , since this can allow you to make repeated calls with an interval delay, and guarantee that those calls will all be made on the Swing event thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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