gpt4 book ai didi

java - PaintComponent() 被调用但 JComponent 未被绘制

转载 作者:行者123 更新时间:2023-11-29 05:08:47 25 4
gpt4 key购买 nike

基本上我在绘制我制作的自定义组件时遇到了问题。每当调用 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() 时,绘制了 JComboBox 而不是 Button,即使调用了 Button 的 paintComponent()。

最佳答案

几个问题:

  • 您永远不应在绘制方法(例如 paintComponent)中调用 setBounds(...)。此方法仅供绘画和绘画。
  • 您的边界和绘画区域是相同的——但它们代表两种截然不同的事物。边界是组件相对于其容器的位置,绘画 x、y 是相对于 JComponent 本身的。所以你画画超出了你的界限。
  • 同样,您的 drawButton 方法应该在 0, 0 处绘制:g.drawRect(0, 0, size.width, size.height);
  • setBounds 无论如何都不应该被调用。那是布局管理器的工作。通过这样做,您会增加一整层潜在且难以发现的错误。
  • 我会覆盖 getPreferredSize() 以帮助设置组件的最佳大小(编辑——您已经这样做了,尽管是以一种非常简单的方式)。
  • 您不应该在按钮内设置按钮的位置——同样,这是其容器的布局管理器的工作。
  • super.paintComponent(g) 可能应该首先在 paintComponent 覆盖中调用。
  • 我会避免给我的类(class)起一个与通用核心类(class)冲突的名字。

关于java - PaintComponent() 被调用但 JComponent 未被绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29458487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com