-3

i have two class .. class panel extends JPanel,

and another class that control the paint of that jpanel every seconds.. (i use swing.Timer)

my code below is fail

heres i try so far..

class panel extends JPanel :

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

class Control :

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

i need the start point of GradientPaint change every second

then paint it in jpanel every second

what should i do?

thanks ..

mopr mopr
  • 193
  • 2
  • 4
  • 13

3 Answers3

5
  1. don't to create any Object inside paint/paintComponent (Control control = new Control(this,g);), prepare this/these Object(s) before (you can to put elements to the Array to and inside paintComponent only to loop inside), this idea creates bunch of Object on runtime, untill NPE became

  2. you code is wrong designed, have to read Oracles 2D Graphics tutorial, tons examples here

  3. have to override PreferredSize for JPanel

  4. you can to create BufferedImage too

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
5

Everything that mKorbel has said and...

  • NEVER maintain a reference to a Graphics context passed to you by the paint sub system. It changes between paint cycles
  • NEVER call repaint or any method that might cause a repaint request from within the paintXxx methods, it will cause the repaint manager to schedule a new repaint at some time in the future and eventually cycle your 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;
        }

    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • thanks a lot.. really helpfull.. billion of thanks for the code.. it save my days/my life ... – mopr mopr Dec 07 '12 at 07:44
  • by the way.. if i have JFrame that contain a button.. then when i click it. it will show JDialog that contain your panel(from your code). then i close that JDialog... is the timer still running? i must stop the timer before i close it? or its okay to abandon it ?(let garbage collector do the job?) – mopr mopr Dec 07 '12 at 11:40
  • Yes time is still running. I wouldn't rely on the GC to pick it up. If need be, you can make the timer a class field and provide methods to start and stop it – MadProgrammer Dec 07 '12 at 20:04
0

thanks to mKorbel & MadProgrammer finally i can solve it..

heres the code what i looking for..

responding the answer of mKorbel & 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);
    }
}
mopr mopr
  • 193
  • 2
  • 4
  • 13