2015-11-13 75 views
0

我對Java圖形相對來說比較新。我想在用戶單擊JButton時在JPanel中的(X,Y)座標處繪製20 x 80的矩形。 (其中'X'和'Y'來自2個JTextFields)。如何在按鈕點擊事件中繪製JPanel中的矩形

我已閱讀了許多問題和教程,但無法解決問題。在某些情況下,我可以繪製矩形,但不能在不清空JPanel的情況下繪製新的矩形。

enter image description here

這裏是我的代碼:

public class CustomPanel extends JPanel { 
     @Override 
     public void paintComponent(Graphics g) { 
     super.paintComponent(g); // first draw a clear/empty panel 
     g.draw3DRect(Integer.parseInt(x.getText()),Integer.parseInt(y.getText()), 20, 80, true); 
     // then draw using your custom logic. 
     } 
    } 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 
    //Code for frame 
    //Code for JTextfields x and y 

    JButton btnDraw = new JButton("Draw"); 
    btnDraw.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
       panel= new CustomPanel(); 


       panel.setBounds(406, 59, 407, 297); 
       frame.getContentPane().add(panel); 
       frame.revalidate(); 
     } 
    }); 
    btnDraw.setBounds(286, 339, 89, 23); 
    frame.getContentPane().add(btnDraw); 



} 
+0

向你的JPanel添加一個'Canvas'並繪製它,而不是直接在你的jpanel上繪圖 – redFIVE

回答

1

您的ActionListener代碼是錯誤的。你不想創建一個新的面板,你想添加一個矩形到現有的面板。

當您創建GUI,你應該添加兩個面板的GUI:

  1. 第一個面板將是一個空的面板,會做你的風俗畫。您通常會將此添加到框架的中心
  2. 第二個面板將包含「繪製」按鈕。您通常會將此面板添加到PAGE_END。然後當你點擊繪圖按鈕時,你在自定義繪畫面板中調用一個像addRectangle(...)這樣的方法,這樣面板就可以繪製矩形。

退房Custom Painting Approaches兩個常見的方式做油畫定製:

  1. 保留對象的列表作畫,然後在的paintComponent()方法,你遍歷列表中的每個塗料對象。
  2. 創建一個BufferedImage,然後將這個Rectangle繪製到BufferedImage上,然後您可以在JLabel或paintComponent()方法中繪製BufferedImage。