簡體   English   中英

正在調用PaintComponent()但未繪制JComponent

[英]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(...) 此方法僅用於繪畫和繪畫。
  • 你的界限和你的繪畫區域是相同的 - 但它們代表兩種截然不同的東西。 邊界是組件相對於其容器的位置,繪制x,y是相對於JComponent本身的。 所以你畫出了你的界限。
  • 所以同樣,你的drawButton方法應該繪制為0,0: g.drawRect(0, 0, size.width, size.height);
  • setBounds都不應該調用setBounds 那是布局經理的工作。 通過這樣做,您添加了一整層潛力,很難找到錯誤。
  • 我會覆蓋getPreferredSize()來幫助設置組件的最佳大小(編輯 - 你已經做過,雖然以一種非常簡單的方式)。
  • 您不應該在按鈕內設置按鈕的位置 - 再次,這是其容器的布局管理器的工作。
  • 應該首先在paintComponent覆蓋中調用super.paintComponent(g)
  • 我會避免給我的班級一個與普通核心班級沖突的名字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM