paintComponent (Graphics g) 메서드를 오버라이드 (override)하는 JComponent를 확장하는 커스텀 컴퍼넌트가 있습니다 만, JPanel에 추가하려고하면 (자) 아무것도 동작하지 않습니다. - 구성 요소가 JPanel에 추가되고 있지만, 얼마나 큰JComponent가 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);
}
}
정말 이상합니다. 윈도우와 맥에서 항상 똑같은 문제가 발생했습니다. – lilroo
아, 너비와 높이가 0으로 설정되었습니다. – lilroo
너비와 높이 필드를 설정 했는데도 작동하지 않았지만 getPreferredSize() 메서드를 재정의했을 때 작동했습니다. – lilroo