自定义组件最初不可见,但随后变为可见

时间:2014-04-15 17:51:47

标签: java swing jframe awt jcomponent

我在弄乱形状时遇到过一个问题。 我创建了一个带滑块的简单程序,您可以使用该滑块操纵弧的大小。问题是当我运行它时,弧线没有涂到屏幕上。但是,当我更改滑块的值时,一切都开始完美。关于这可能是由什么造成的任何想法?这是代码:

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

1 个答案:

答案 0 :(得分:0)

arc的构造函数中创建DrawStuff时:

arc = new Arc2D.Double(this.getWidth() / 2 - 50, this.getHeight() / 2 - 50, 100, 100, 0, 120, Arc2D.PIE);

this.getWidth()this.getHeight()将得到0的结果,因为组件尚未调整大小。一个简单的解决方法是使用固定大小,如下所示:

arc = new Arc2D.Double(210 / 2 - 50, 140 / 2 - 50, 100, 100, 0, 120, Arc2D.PIE);