本帖最后由 colinxt 于 2011-02-25 01:03:42 编辑

解决方案 »

  1.   

    JComponent的BasicUI不绘制背景的,即JComponent即使设置为不透明的,一样不绘制背景,想要使用背景的话,还是用JPanel吧
      

  2.   

    添加个面板JPanel,然后设置背景颜色红色就Ok了
      

  3.   

    谢谢楼上几位;
    我试了一下新增个JPanel一样不行:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;public class FirstExample
    {
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
         public void run()
         {
         DrawFrame frame = new DrawFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
         }
        });
    }
    }class DrawFrame extends JFrame
    {
    public DrawFrame()
    {
    setTitle("DrawTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    DrawComponent component = new DrawComponent();
    Background b = new Background(); //新建背景panel
    add(b);  //添加背景panel
    add(component);
    }

    public static final int DEFAULT_WIDTH = 400;
    public static final int DEFAULT_HEIGHT = 400;
    }class DrawComponent extends JComponent
    {
    public void paintComponent(Graphics g)
    {
    Graphics2D g2 = (Graphics2D) g;

    double leftX = 100;
    double topY = 100;
    double width = 200;
    double height = 150;

    g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
    g2.draw(new Line2D.Double(leftX, topY + height, leftX + width, topY)); }
    }//以下为新增的Background类
    class Background extends JPanel
    {
    public void paintBorder(Graphics g)
    {
    setBackground(Color.RED);
    }
    }
      

  4.   

    import java.awt.Color;import javax.swing.JFrame;
    import javax.swing.JPanel;public class Test {
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            panel.setBackground(Color.RED);
            frame.add(panel);        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 500);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }
      

  5.   


    明白了,谢谢,
    再问一下,怎么样同时显示红色背景和一个叉呢?
    试了一下,发现panel会把frame给覆盖了