[英]How to make background work in custom JComponent?
在下面的示例中,我有一个自定义的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);
}
});
}
}
JComponent不会绘制其背景。 您可以自己绘制,也可以使用可以绘制背景的JPanel
我记得它仅支持此backgroun属性,但实际上并未绘制它。 使用g.fillRect(如果为椭圆,则为fillEllipse)来创建自己的背景。
paint()方法中有几个问题。
Graphics.setColor()
,因此您要绘制的颜色是完全未知的。 您想要更多类似这样的东西:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(getBackground());
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setColor(getForeground());
g2.draw(ellipse);
}
或者,您可以从JPanel而不是JComponent进行扩展,它将为您绘制背景,仅让您做前景:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(getForeground());
g2.draw(ellipse);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.