【发布时间】:2014-04-25 10:13:12
【问题描述】:
我无法更改 JFrame 或 JFrame 内的 JPanel 的背景颜色,这是我的代码:
public class MyFrame extends JFrame {
public MyFrame(){
setSize(600,600);
setResizable(false);
panel = new MyPanel();
panel.setBackground(Color.BLACK);
//getContentPane().setBackground(Color.BLACK); doesn't work
getContentPane().add(panel);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(-1);
}
public void windowClosed(WindowEvent ev){
System.exit(-1);
}
});
}
public void paint(Graphics g){
super.paint(g);
g.clearRect(0,0,600,600);
synchronized (this){
if (positions!=null){
for (int i=0; i<positions.length; i++){
P2d p = positions[i];
//int x0 = (int)(180+p.x*180);
//int y0 = (int)(180-p.y*180);
g.drawOval((int)p.x,(int)p.y,5,5);
}
}
}
}
}
我尝试了好几种方法,但我不能改变颜色,它总是白色的,我该怎么办?
【问题讨论】:
-
panel.setBackground(Color.BLACK);应该可以工作。显示您的 MyPanel 类 -
@kleopatra 您链接的问题与
JFrame相关,尽管此问题的标题可能具有误导性,但假设OP 的MyPanel 遵循MyFrame 并扩展JPanel这个问题似乎是关于改变颜色JPanel的核心无法正常工作。