简体   繁体   English

Java:为我的框架定义的绘画方法从另一个类引用时不会调用repaint()

[英]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. 如果我只是从类中的main方法调用run()方法,则它的工作原理与预期的完全一样。 It seems like my repaint() method isn't getting called from the other class. 看来我的repaint()方法没有从另一个类中调用。 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 不要从事件调度线程的上下文中调用Thread.sleep EVER
  • 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 不要在paint方法中调用任何可能导致repaint方法,这将导致无限的更新循环,最终将占用您的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 避免覆盖诸如JFrame类的顶级容器的paint ,除了不进行双重缓冲外,大多数窗口还包含其他组件( JRootPanecontentPaneglassPane ),所有这些组件都可能干扰您尝试绘制的内容
  • 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. 这意味着您永远不要在事件调度线程的上下文内执行任何长时间运行或阻止的操作,并且永远不要在事件调度线程之外创建或修改任何UI组件。
  • There is only ever one EDT and ALL UI code will run within in. Things like painting are ALWAYS executed within the EDT automatically. 只有一个EDT,并且所有UI代码都将在其中运行。诸如绘画之类的事情总是在EDT中自动执行。

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();
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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