【发布时间】:2015-01-26 08:24:07
【问题描述】:
就像标题所说的那样,我正在尝试在框架内设置面板的背景颜色,以便它们都有不同的颜色。到目前为止我尝试的是单独或同时使用setBackground 方法,我得到的结果总是只显示一种颜色,这很奇怪,因为内框不应该能够更改外框的设置对吧?
代码示例:
public class frameStuff{
private JFrame frame;
private frame1 in_frame;
@SuppressWarnings("serial")
class frame1 extends JPanel {
frame1(){
super();
}
public void paint(Graphics g){
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frameStuff window = new frameStuff();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frameStuff() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 500, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
// frame.getContentPane().setBackground(Color.GRAY);/*if this line wasn't a comment then everything would be grey instead of white as it's now.
in_frame = new frame1();
in_frame.setBounds(100, 100, 350, 220);
in_frame.setBackground(Color.BLUE);
in_frame.setVisible(true);//this doesn't seem to matter whatever the case
frame.getContentPane().add(in_frame);
}
}
【问题讨论】:
-
删除
public void paint(Graphics g){ }.. 不要重写一个工作方法只是让它什么都不做! -
请注意,
class frame1 extends JPanel {不是框架,不应该这样称呼! -
“这就是我想要一个服装JPanel类开始的原因..” 如果没有必要显示问题,那就是多余的。否则,它现在正在引起问题。鉴于这是
JComponent(JPanel扩展JComponent),永远覆盖paint(..)是正确的 - 而是覆盖paintComponent(..)并立即调用super.paintComponent(..); -
frame.getContentPane().setLayout(null);这一天会出现一两次。 (所以再次)Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。 -
"重写paint(..)永远是不正确的——而是重写paintComponent(..)并立即调用super.paintComponent(..);"似乎添加了这一行“super.paint(g);”到paint方法解决了这里的问题,你还建议按照你说的去做吗?这种方式更快吗?顺便说一句,您可以将对此的回复作为答案发布,我会接受它:p
标签: java swing jframe jpanel paint