views:

156

answers:

1

The button in the code below is to me the only object that should listen for ActionEvents but when I resize the window the circle changes color which should only happen when the button is pressed.

Does it in some way use frame.repaint() when resizing the window that generates new values for the drawPanel object or even makes a new drawPanel object for each time the screen is displayed with new random values?

Test.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test implements ActionListener {

    JFrame frame;
    JButton button;

    public static void main (String[] args) {
            Test gui = new Test();
            gui.go();
    }

    public void go() {
     frame = new JFrame("Test");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     button = new JButton("Pressme!");
     button.addActionListener(this);

     MyPanelDraw drawPanel = new MyPanelDraw();

     frame.getContentPane().add(BorderLayout.SOUTH, button);
     frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
     frame.setSize(300,300);
     frame.setVisible(true);
    }

    public void actionPerformed (ActionEvent event) {

     button.setText("Changed");
     frame.repaint();

    }

}

MyPanelDraw.java

import javax.swing.*;
import java.awt.*;

class MyPanelDraw extends JPanel {

    public void paintComponent(Graphics g) {
     Graphics2D g2d = (Graphics2D) g;

     int red = (int) (Math.random() * 255);
     int green = (int) (Math.random() * 255);
     int blue  = (int) (Math.random() * 255);
     Color startColor = new Color(red, green, blue);

     red = (int) (Math.random() * 255);
     green = (int) (Math.random() * 255);
     blue = (int) (Math.random() * 255);

     Color endColor = new Color(red,green, blue);

     GradientPaint gradient = new GradientPaint(70,70,startColor, 150,150, endColor);
     g2d.setPaint(gradient);
     g2d.fillOval(40,70,100,100);

    }
}
+2  A: 

The repaint method is called when the container is revalidated (which happens when it is resized). The repaint method is called whenever Swing needs to redraw the component for whatever reason. You shouldn't rely on it not being called.

Dan Dyer
Thanks. But regarding the drawFrame object, does the frame.redraw() call drawPanel.paintComponent?
Patrik Björklund
Anytime you manually invoke a repaint() on a Component all the children of that Component are also repainted. So in the case of a frame, that would mean everthing is repainted.
camickr
You should not change the state of any variables in the paintComponent() method. You should be creating a "randomizeColors" method. This method would change the two colors and save them as instance variables. It would then invoke repaint() on the panel.
camickr
Sounds like sound advice camickr, the example is taken from the head first java book so they will probably advocate something similar further down the road :)
Patrik Björklund