我无法更改 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);
}
}
}
}
}
我尝试了多种方法,但我无法改变颜色,它总是白色,我该怎么办?
最佳答案
试试这个。绘制一个填充背景颜色的矩形。
- 使用
SwingUtilities.invokeLater()
或EventQueue.invokeLater()
- 使用
paintComponent()
方法进行自定义绘制 - 不要直接在
JFrame
上绘图。 - 使用
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
关闭JFrame
示例代码:
public class MyFrame extends JFrame {
public MyFrame() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setSize(new Dimension(600, 600));
setResizable(false);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.clearRect(0, 0, 600, 600);
Color prevColor = g.getColor();
g.setColor(Color.BLUE); // background color
g.fillRect(0, 0, 600, 600); // fill a rectangle with background color
g.setColor(prevColor);
// your custom painting
...
}
};
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
});
}
}
关于java - 如何改变JFrame的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23290189/