JComponent.setBackground似乎无效

时间:2015-12-09 17:27:06

标签: java swing

我写了这段代码。我正在使用XFCE 4桌面在Debian 8上使用OpenJDK 1.7编译和运行此代码。

import javax.swing.JFrame;
import javax.swing.JComponent;
import java.awt.EventQueue;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;

public class FrameDemo
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                HelloWorldComponent component = new HelloWorldComponent();
                component.setOpaque(true);
                component.setBackground(Color.BLUE); // Attempt 2

                frame.add(component);
                frame.pack();

                frame.setLocationByPlatform(true);
                frame.setVisible(true);
                component.setBackground(Color.BLUE); // Attempt 3
            }
        });
    }
}

class HelloWorldComponent extends JComponent
{
    public HelloWorldComponent()
    {
        setOpaque(true);           // Attempt 4
        setBackground(Color.BLUE); // Attempt 4
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g); // Attempt 5

        Graphics2D g2 = (Graphics2D) g; // Attempt 6
        g2.clearRect(0, 0, 200, 100); // Attempt 6

        setBackground(Color.BLUE); // Attempt 1
        g.drawString("hello, world", 50, 50);
    }

    public Dimension getPreferredSize()
    {
        return new Dimension(200, 100);
    }
}

但是当我运行此代码时,我的框架中看不到任何蓝色背景。

enter image description here

我做错了什么?如何确保正确显示蓝色背景?

0 个答案:

没有答案