java - JComponent 不绘制到 JPanel

标签 java swing jpanel jcomponent

我有一个扩展 JComponent 的自定义组件,它覆盖了 paintComponent(Graphics g) 方法,但是当我尝试将它添加到我的 JPanel 时,它不起作用,没有绘制任何东西。 这是我的代码:

public class SimpleComponent extends JComponent{

int x, y, width, height;

public SimpleComponent(int x, int y, int width, int height){
    this.x = x;
    this.y = y;
}

@Override
public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.BLACK);
    g2.fillRect(x, y, width, height);
}
}


public class TestFrame{
public static void main(String[] args){
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel.setPreferredSize(new Dimension(400, 400));
    frame.add(panel);
    frame.pack();
    frame.setResizable(false);

    SimpleComponent comp = new SimpleComponent(10, 10, 100, 100);
    panel.add(comp);
    frame.setVisible(true);
}
}

最佳答案

工作正常——组件被添加到 JPanel,但它有多大?如果在呈现 GUI 后检查它,您可能会发现组件的大小为 0、0。

SimpleComponent comp = new SimpleComponent(10, 10, 100, 100);
panel.add(comp);
frame.setVisible(true);

System.out.println(comp.getSize());

考虑让您的 JComponent 覆盖 getPreferredSize 并返回一个有意义的维度:

public Dimension getPreferredSize() {
  return new Dimension(width, height);
}

如果您想使用 x 和 y,您可能还希望覆盖 getLocation()

编辑
您还需要设置宽度和高度字段!

public SimpleComponent(int x, int y, int width, int height) {
  this.x = x;
  this.y = y;
  this.width = width; // *** added
  this.height = height; // *** added
}

关于java - JComponent 不绘制到 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12759264/

相关文章:

java - 如何为 SWT Scrolled Composite 设置启用水平滚动

java - Realm 没有为反射对象的字段设置值(Android)

java - 将子节点添加到 SelectionPaths[]

java - 尝试在已设置的 JPanel 上绘图但失败

java - 在 jframe 运行时添加删除面板

java - 我可以在访问前一个 jPanel 的同时添加同一 jPanel 的全新实例吗?

java - 将对象添加到 JPanel

java - Android Retrofit2/RxJava2/Room——简单的数据处理

java - Java 中的 REST WebService 和并发

java - JTable 为所有单元格着色,而不仅仅是特定单元格