JComponent没有绘制到JPanel

lil*_*roo 6 java swing jcomponent jpanel

我有一个扩展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);
}
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 4

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

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

System.out.println(comp.getSize());
Run Code Online (Sandbox Code Playgroud)

考虑让您的 JComponent 重写 getPreferredSize 并返回一个有意义的 Dimension:

public Dimension getPreferredSize() {
  return new Dimension(width, height);
}
Run Code Online (Sandbox Code Playgroud)

如果您想使用 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
}
Run Code Online (Sandbox Code Playgroud)