开发者

Java. Problem with drawing shapes by button click

Good day.

I develop program which must show few shapes when user clicks the button. At least it doesn't show it. What is wrong? Code is:

public class ShowFrame extends JFrame
{
    public ShowFrame()
    {
        this.setTitle("Show data");                                             //Title
        this.setSize( DEF_WIDTH, DEF_HEIGHT );                                  //Size of frame
        this.setResizable(false); 

    //...                                     

    JButton testButton = new JButton("Test");
    buttonPanel.add开发者_Go百科(testButton);
    this.add(buttonPanel, BorderLayout.SOUTH);


    testButton.addActionListener( new ActionListener() {                    //Add listener
        public void actionPerformed(ActionEvent e) {              
            DrawStuff stuff = new DrawStuff();                              //Create class which draws shapes
            add(stuff, BorderLayout.CENTER);
            System.out.println("Test Button");
        }
    } );
   }

public static final int DEF_WIDTH  = 600;                                   
public static final int DEF_HEIGHT = 400;                                   

private JPanel buttonPanel = new JPanel();
}

Class which draws shapes:

public class DrawStuff extends JComponent
{
    public void paintComponent( Graphics g )
    {
        Graphics2D g2 = (Graphics2D) g;
        //...
        Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
        Line2D line      = new Line2D.Double(leftX, topY, 0, 0);
        //...
        g2.draw(rect);
        g2.draw(line);
        //...
    }

}


When you add/remove components on a visible GUI the code should be:

panel.add(...);
panel.revalidate();
panel.repaint();

Your design of adding a new panel every time you click a button is not a very good one.

Instead you should create a custom painting panel and override the paintComponent() method. Then when you click a button you invoke a method in your custom component to set the shape you want to draw. The paintComponent() method should be smart enought to paint the shape. Then you invoke repaint() on the panel.

Read the section from the Swing tutorial on Custom Painting for more information and working examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜