JComponent.setBackground()没有用?

mehere8 mehere8 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
java doc里面是这么写的

setBackground
public void setBackground(Color bg)
Sets the background color of this component. The background color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations. Direct subclasses of JComponent must override paintComponent to honor this property.
It is up to the look and feel to honor this property, some may choose to ignore it.

代码:

// the main() method is ignored.

public MyFrame extends JFrame
{ //set ...
MyComponent cmp=new MyComponent();
// '1'
add(cmp);
}

class MyComponent extends JComponent
{ public void paintComponent(Graphics gr)
{ setBackground(Color.RED);
}
}



然后背景颜色还是没有变

在代码中 ‘1’处加上 cmp.setOpaque(true); 也没有用 (貌似要求都符合了--opaque;override paintComponent() )

如果不是JComponet 而是JPanel 就没有问题

那么如果我想用JComponent 怎么设置背景颜色呢?
...全文

相关推荐

评论 18
收藏 已收藏
分享
返回顶部
mehere8
Java SE 62,620 成员 307,251 内容