I've come across an issue when messing around with shapes. I created a simple program with a slider with which you manipulate the size of an arc. The problem is that when I run it, the arc isn't painted to the screen. However, when I change the value of the slider, everything starts working perfectly. Any thoughts on what this might be caused by? Here's the code:
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.*;
import java.awt.geom.*;
@SuppressWarnings("serial")
public class GraphicsTest2 extends JFrame implements ChangeListener { // START OF GraphicsTest2
private JPanel sliderPanel, thePanel;
private JSlider slider;
private DrawStuff draw;
public static void main(String[] args) { // START OF main
new GraphicsTest2();
} // END OF main
public GraphicsTest2() { // START OF CONSTRUCTOR
super("Graphics test 2");
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thePanel = new JPanel();
thePanel.setLayout(new BorderLayout(10, 10));
slider = new JSlider(JSlider.HORIZONTAL, 1, 360, 120);
slider.addChangeListener(this);
sliderPanel = new JPanel();
sliderPanel.add(slider, BorderLayout.CENTER);
draw = new DrawStuff();
thePanel.add(sliderPanel, BorderLayout.SOUTH);
thePanel.add(draw, BorderLayout.CENTER);
this.add(thePanel, BorderLayout.CENTER);
this.pack();
this.validate();
this.setVisible(true);
} // END OF CONSTRUCTOR
public void stateChanged(ChangeEvent e) { // START OF stateChanged
if(e.getSource() == slider) {
int size = slider.getValue();
draw.arc = new Arc2D.Double(draw.getWidth() / 2 - 50, draw.getHeight() / 2 - 50, 100, 100, 0, size, Arc2D.PIE);
this.repaint();
}
} // END OF stateChanged
private class DrawStuff extends JComponent { // START OF DrawStuff
Shape arc;
public void paintComponent(Graphics g) { // START OF paintComponent
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.GREEN);
g2.fill(arc);
} // END OF paintComponent
public DrawStuff() {
this.setPreferredSize(new Dimension(100, 140));
arc = new Arc2D.Double(this.getWidth() / 2 - 50, this.getHeight() / 2 - 50, 100, 100, 0, 120, Arc2D.PIE);
}
} // END OF DrawStuff
} // END OF GraphicsTest2
When you create your arc
in the constructor of DrawStuff
here:
arc = new Arc2D.Double(this.getWidth() / 2 - 50, this.getHeight() / 2 - 50, 100, 100, 0, 120, Arc2D.PIE);
this.getWidth()
and this.getHeight()
will give a result of 0 because the components are not sized yet. A simple fix would be to use the fixed size like this:
arc = new Arc2D.Double(210 / 2 - 50, 140 / 2 - 50, 100, 100, 0, 120, Arc2D.PIE);