如何使自定义JComponent的后台工作? [英] How to make background work in custom JComponent?
本文介绍了如何使自定义JComponent的后台工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的例子中,我有一个自定义的的JComponent
绿色背景被绘制,但它不会出现。为什么会这样?
公共类Test_Background { 公共静态类JEllipse扩展JComponent的{ 私人最终椭圆Ellipse2D的; 公共JEllipse(INT宽度,高度INT){
椭圆=新Ellipse2D.Double(0,0,宽度,高度); setOpaque(真);
的setBackground(Color.GREEN);
} @覆盖
公共尺寸的get preferredSize(){
返回新的Dimension((INT)ellipse.getBounds()。getMaxX()
(INT)ellipse.getBounds()getMaxY());
} @覆盖
保护无效paintComponent(图形G){
super.paintComponent方法(G); ((Graphics2D的)G).draw(椭圆形);
}
} 公共静态无效的主要(字串[] args){
SwingUtilities.invokeLater(Runnable的新(){ @覆盖
公共无效的run(){
JEllipse E =新JEllipse(400,300); JFrame的F =新的JFrame(背景测试);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(E);
f.pack();
f.setVisible(真);
}
});
}
}
解决方案
JComponent的不画背景。您可以自己或者画它,或者使用的JPanel这确实绘制其背景
In the following example, I have a custom JComponent
being drawn on green background, but it does not appear. Why does this happen?
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 does not paint its background. You can either paint it yourself, or use JPanel which does paint its background
这篇关于如何使自定义JComponent的后台工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文