日期:2014-05-20  浏览次数:20921 次

GUI怎么设置背景颜色?
代码如下:
Java code

import java.awt.*;import javax.swing.*;
public class BackgroundTest {
public static void main(String[] args) {     
new KFrame();    
}
}

class KFrame extends JFrame {
KFrame() {     
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 关闭窗口后操作为退出程序 
setSize(500, 500);// 程序窗口尺寸     
setVisible(true);// 窗口显示     
JPanel component = new KComponent(); 
add(component);     
component.setBackground(Color.YELLOW);//设置背景颜色(可是没有用)    }
}
class KComponent extends JPanel {    
public void paintComponent(Graphics g) {     g.drawString("King's", 150, 150);
}
}

如上,为什么我的那句component.setBackground(Color.YELLOW);想设置背景颜色为黄色,可是为什么没用?写了当没写,问题出在哪?

------解决方案--------------------
Java code
public void paintComponent(Graphics g) {
    g.drawString("King's", 150, 150);
}