我想在我的面板中繪製矩形。下面是我的圖形類:舔按鈕後,它不顯示任何形狀在我的面板
class MyComponent extends JComponent {
public void paint(Graphics g) {
g.fillRect(30, 30, 100, 100);
}
}
而且我有矩形按鈕,我添加此動作監聽
rect.addActionListener(new ButtonListener());
而且我的行爲實現是:
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==rect)
{
p1.add(new MyComponent());
p1.repaint();
}
}
}
但是當我點擊矩形按鈕沒有反應。被稱爲更新的子組件之前repaint
panel.revalidate();
panel.repaint();
通常paintComponent
被覆蓋,而不是paint
在Swing與super.paintComponent
被稱爲
旁註:你不應該重寫'漆()'但是'paintComponent()'。不要忘記調用'super.paintComponent()'。請參閱[更仔細地瞭解繪圖機制](https://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html) – dic19 2014-11-22 02:30:38
我將其更改爲「仍然不工作」 – 2014-11-22 02:38:00
根據佈局管理器的p1,MyComponent可能不會顯示,因爲它沒有默認大小。你還應該重寫MyComponent類的getPreferredSize方法來返回適當的大小... – MadProgrammer 2014-11-22 03:08:03