[英]How to draw rectangle in JPanel from button click event
我對Java Graphics比較陌生。 當用戶單擊JButton時,我想在JPanel中的(X,Y)坐標處繪制20 x 80矩形。 (其中“ X”和“ Y”來自2個JTextField)。
我已經閱讀了許多問題和教程,但無法解決問題。 在某些情況下,我可以繪制矩形,但是在不清空JPanel的情況下不能繪制新的矩形。
這是我的代碼:
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);
}
您的ActionListener代碼錯誤。 您不想創建新面板,而是想將Rectangle添加到現有面板。
創建GUI時,應在GUI中添加兩個面板:
addRectangle(...)
類的方法,以便該面板可以繪制Rectangle。 查看“ 自定義繪畫方法”,以了解兩種常見的自定義繪畫方法 :
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.