在下面的示例中,我JComponent
在绿色背景上绘制了一个自定义,但它没有出现。为什么会这样?
public class Test_Background {
public static class JEllipse extends JComponent {
private final Ellipse2D ellipse;
public JEllipse(int width, int height) {
ellipse = new Ellipse2D.Double(0, 0, width, height);
setOpaque(true);
setBackground(Color.GREEN);
}
@Override
public Dimension getPreferredSize() {
return new Dimension((int) ellipse.getBounds().getMaxX(),
(int) ellipse.getBounds().getMaxY());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).draw(ellipse);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JEllipse e = new JEllipse(400, 300);
JFrame f = new JFrame("Background Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(e);
f.pack();
f.setVisible(true);
}
});
}
}