[英]PaintComponent() being called but JComponent not being painted
基本上我在繪制我制作的自定義組件時遇到了問題。 每當調用repaint()時,我的Button類的paintComponent()被調用,但我的框架中沒有顯示任何內容。 我也知道組件的大小合適,並且位於正確的位置,因為我設置了一個邊框來檢查它。
以下是我的自定義組件類:
public class Button extends JComponent {
protected static final Color BUTTON_COLOR = Color.black;
protected Point position;
protected Dimension size;
public Button(int posX, int posY, int width, int height) {
super();
position = new Point(posX, posY);
size = new Dimension(width, height);
setBounds(position.x, position.y, size.width, size.height);
setBorder(BorderFactory.createTitledBorder("Test"));
setOpaque(true);
}
@Override
protected void paintComponent(Graphics g) {
setBounds(position.x, position.y, size.width, size.height);
drawButton(g);
super.paintComponent(g);
}
@Override
public Dimension getPreferredSize() {
return size;
}
public void drawButton(Graphics g) {
selectColor(g, BUTTON_COLOR);
g.fillRect(position.x, position.y, size.width, size.height);
g.setColor(Color.black);
g.drawRect(position.x, position.y, size.width, size.height);
}}
這是我的自定義組件添加到的JPanel:
public class MainMenu extends JPanel {
public MainMenu() {
setBackground(Color.BLACK);
setLocation(0,0);
setPreferredSize(new Dimension(800,600));
setDoubleBuffered(true);
setVisible(true);
this.setFocusable(true);
this.requestFocus();
}}
最后,我將以下組件添加到MainMenu JPanel中:
main_menu.add(new Button(200, 200, 150, 50));
dropdown = new JComboBox<File>() {
@Override
public void paintComponent(Graphics g) {
dropdown.setLocation(new Point(400, 200));
super.paintComponent(g);
}
};
main_menu.add(dropdown);
奇怪的是當在main_menu上調用repaint()時,即使調用了Button的paintComponent(),JComboBox也會被繪制而不是Button。
幾個問題:
paintComponent
方法(如paintComponent
setBounds(...)
調用setBounds(...)
。 此方法僅用於繪畫和繪畫。 drawButton
方法應該繪制為0,0: g.drawRect(0, 0, size.width, size.height);
setBounds
都不應該調用setBounds
。 那是布局經理的工作。 通過這樣做,您添加了一整層潛力,很難找到錯誤。 getPreferredSize()
來幫助設置組件的最佳大小(編輯 - 你已經做過,雖然以一種非常簡單的方式)。 super.paintComponent(g)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.