如何使用GradientPaint每秒绘制jpanel?

时间:2012-12-07 06:50:37

标签: java swing jpanel paintcomponent

我有两个类..类面板扩展了JPanel,

和另一个每秒控制该jpanel的绘画的类..(我使用swing.Timer)

我的代码失败

到目前为止,我试着继续......

类面板扩展了JPanel:

@Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Control control = new Control(this,g);
        repaint();
    }

班级控制:

public class Control implements ActionListener{

    private int XX=0;
    private int YY=0;

    private Graphics2D g2;
    private JPanel panel;

    Timer tim = new Timer(1000, this);


    public Control(JPanel el,Graphics g) {


        this.g2=(Graphics2D)g.create();
        this.panel=el;
        tim.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        XX++;
        YY++;

    /////////////////////
    //my priority 
        GradientPaint gp = new GradientPaint(XX, YY, Color.BLUE, panel.getWidth(), panel.getHeight(), Color.WHITE);
    //////////////////////

        g2.setPaint(gp);
        g2.fillRect(0, 0, panel.getWidth(), panel.getHeight());
        panel.repaint();
    }
}

我需要每秒更改GradientPaint的起点

然后每秒在jpanel中绘制

我该怎么办?

谢谢..

3 个答案:

答案 0 :(得分:5)

  1. 不要在Object / paintpaintComponent)内创建任何Control control = new Control(this,g);,请准备此/ Object(s)之前(你可以将元素放到数组中,只能在paintComponent内部循环),这个想法在运行时创建一堆Object,直到NPE成为

  2. 您的代码设计错误,必须阅读Oracles 2D Graphics tutorialtons examples here

  3. 必须覆盖PreferredSize

  4. JPanel
  5. 您也可以创建BufferedImage

答案 1 :(得分:5)

mKorbel所说的一切......

  • 永远不要保持对paint子系统传递给你的Graphics上下文的引用。它在油漆循环之间变化
  • 永远不要在repaint方法中调用paintXxx或任何可能导致重绘请求的方法,这将导致重绘管理器在将来的某个时间安排新的重绘,并最终循环CPU 100%
  • Painting in AWT and Swing
  • Custom Painting in Swing
  • How to Swing Timer


public class TestPaintTimer {

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

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

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new GradientPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class GradientPanel extends JPanel {

        private Color startColor = Color.RED;
        private Color endColor = Color.BLUE;
        private float progress = 0f;
        private float direction = 0.1f;

        public GradientPanel() {
            Timer timer = new Timer(125, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    progress += direction;
                    if (progress > 1f) {
                        direction *= -1;
                        progress = 1f;
                    } else if (progress < 0) {
                        direction *= -1;
                        progress = 0f;
                    }

                    startColor = calculateProgress(Color.RED, Color.BLUE, progress);
                    endColor = calculateProgress(Color.BLUE, Color.RED, progress);

                    repaint();
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            LinearGradientPaint lgp = new LinearGradientPaint(
                            new Point(0, 0),
                            new Point(0, getHeight()),
                            new float[]{0f, 1f},
                            new Color[]{startColor, endColor});
            g2d.setPaint(lgp);
            g2d.fill(new Rectangle(getWidth(), getHeight()));
            g2d.dispose();
        }

        public Color calculateProgress(Color startValue, Color endValue, float fraction) {
            int sRed = startValue.getRed();
            int sGreen = startValue.getGreen();
            int sBlue = startValue.getBlue();
            int sAlpha = startValue.getAlpha();

            int tRed = endValue.getRed();
            int tGreen = endValue.getGreen();
            int tBlue = endValue.getBlue();
            int tAlpha = endValue.getAlpha();

            int red = calculateProgress(sRed, tRed, fraction);
            int green = calculateProgress(sGreen, tGreen, fraction);
            int blue = calculateProgress(sBlue, tBlue, fraction);
            int alpha = calculateProgress(sAlpha, tAlpha, fraction);

            return new Color(red, green, blue, alpha);
        }

        public int calculateProgress(int startValue, int endValue, float fraction) {
            int value = 0;
            int distance = endValue - startValue;
//        value = Math.round((float)distance * fraction);
            value = (int) ((float) distance * fraction);
            value += startValue;

            return value;
        }

    }

}

答案 2 :(得分:0)

感谢mKorbel&amp; MadProgrammer最终我可以解决它..

继承我寻找的代码..

回应mKorbel&amp;的回答madProgrammer

   public class again extends JPanel{
    int xx=0;
    int xxMax;
    String go = "RIGHT";

    Timer t;
    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(go.equals("RIGHT")){
                if(xx>=xxMax){go="LEFT";};
                xx += 10;

            }else if(go.equals("LEFT")){
                if(xx<=0){go="RIGHT";};
                xx -= 10;

            }
            repaint();
        }};

    public again() {
        t = new Timer(1, listener);
        t.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g.create();
        GradientPaint gp = new GradientPaint(0, 0, Color.black, xx, getHeight(), Color.WHITE);
        g2.setPaint(gp);
        g2.fillRect(0, 0, getWidth(), getHeight());
        g2.dispose();
        xxMax=getWidth();
    }
}


class Frame extends JFrame{

    public Frame(){
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        add(new again());
        setVisible(true);
    }

    public static void main (String[]args){
        new Frame().setExtendedState(MAXIMIZED_BOTH);
    }
}