简体   繁体   中英

Java: A defined paint method for my frame won't call repaint() when referenced from another class

I am trying to call this constructor from another class, but when I create the new thread, it doesn't ever call repaint. If I just call the run() method from the main method in the class, it works exactly as expected. It seems like my repaint() method isn't getting called from the other class. I was worried that my other class was still doing calculations, but even after putting it in a thread, I had no luck.

Code:

public class MakeTransparent implements Runnable{
private int i;
private static int dollars;
private float transparency;

public MakeTransparent(int dollars){

    this.setDollars(dollars);
    this.transparency = 1;
    this.i = 300;
}
@Override
public void run() {
    JFrame frame = new JFrame("Tiddlybiscuits"){
        private static final long serialVersionUID = 1L;

        public void paint(Graphics arg0) {
            Graphics2D g2 = (Graphics2D)arg0;
            super.paint(g2);
            g2.setColor(getBackground());
            g2.fillRect(0, 0, this.getWidth(),this.getHeight());
            g2.setColor(Color.CYAN);
            g2.setFont(g2.getFont().deriveFont(50, 200F));
            //System.out.println(arg0.getFontMetrics());
            String string = "+$";
            Composite c = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getTransparency());
            g2.setComposite(c);
            g2.drawString(string + getDollars(), 30, getI());
            try {Thread.sleep(40);} catch (InterruptedException e) {}
            setI(getI()-5);
            setTransparency(getTransparency()-.03f);
            repaint();
        }
    };
    frame.setSize(500,500);
    frame.setLocationRelativeTo(null);
    frame.setUndecorated(true);
    frame.setBackground(new Color(1,55,134,0));

    frame.setLayout(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    try { Thread.sleep(1400); } catch (InterruptedException e) {    }
    frame.dispose();
}
  • Don't call Thread.sleep EVER from within the context of the Event Dispatching Thread
  • Don't call any method that might cause a repaint to occur from within in paint method, this will cause an infinite update loop which will eventually consume your CPU
  • Avoid overriding paint of top level containers like JFrame , apart from not been double buffered, most windows contain other components ( JRootPane , contentPane , glassPane ) all which can interfere with what you are trying to paint
  • Swing is a single threaded frame work and is not thread safe. This means that you should never perform any long running or blocking operations from within the context of the Event Dispatching Thread and you should never create or modify any UI component from outside the Event Dispatching Thread.
  • There is only ever one EDT and ALL UI code will run within in. Things like painting are ALWAYS executed within the EDT automatically.

Take a look at:

for more details and ideas about how to work within the frameworks requirements

褪色

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

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

                TestPane tp = new TestPane();
                Timer timer = new Timer(40, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        float t = tp.getTransparancy() - 0.03f;
                        if (t < 0) {
                            t = 0;
                            ((Timer)e.getSource()).stop();
                        }
                        int i = tp.getI();

                        tp.setI(i - 1);
                        System.out.println(t);
                        tp.setTransparancy(t);
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(tp);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                timer.start();
            }
        });
    }

    public class TestPane extends JPanel {

        private float transparancy = 1f;
        private int i = 200;
        private int dollars;

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

        public void setTransparancy(float value) {
            if (transparancy != value) {
                float old = transparancy;
                this.transparancy = value;
                firePropertyChange("transparancy", old, transparancy);
                repaint();
            }
        }

        public float getTransparancy() {
            return transparancy;
        }

        public int getDollars() {
            return dollars;
        }

        public int getI() {
            return i;
        }

        public void setI(int value) {
            if (i != value) {
                float old = i;
                this.i = value;
                firePropertyChange("i", old, i);
                repaint();
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(getBackground());
            g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
            g2d.setColor(Color.CYAN);
            g2d.setFont(g2d.getFont().deriveFont(50, 200F));
            //System.out.println(arg0.getFontMetrics());
            String string = "+$";
            Composite c = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getTransparancy());
            g2d.setComposite(c);
            g2d.drawString(string + getDollars(), 30, getI());
            g2d.dispose();
        }

    }

}

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