2011-05-13 320 views
0

美好的一天。Java。用按鈕單擊繪製形狀的問題

我開發的程序在用戶點擊按鈕時必須顯示幾個形狀。至少它沒有顯示它。哪裏不對? 代碼是:

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

類繪製形狀:

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); 
     //... 
    } 

} 

回答

1

當您添加/上可見GUI刪除組件的代碼應該是:

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

你添加的設計每次點擊一個按鈕時新面板都不是一個很好的面板。

相反,您應該創建一個自定義繪畫面板並覆蓋paintComponent()方法。然後當你點擊一個按鈕時,你可以在自定義組件中調用一個方法來設置你想繪製的形狀。 paintComponent()方法應該足夠聰明以繪製形狀。然後在面板上調用repaint()。

閱讀Swing教程中有關Custom Painting的部分以獲取更多信息和工作示例。