JPanel和Frame之间的默认彩色间距

时间:2014-02-07 01:10:19

标签: java string swing jpanel paintcomponent

我写了一个简单的程序,在打印“生日快乐!”时随机改变背景颜色。到屏幕,但我看到一个不需要的间距。我该如何解决这个问题?

Birthday Program

Birthday.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Birthday {

    DrawString panel = new DrawString();

    public Birthday() {
        JFrame f = new JFrame();

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(panel);
        f.setTitle("Happy Birthday!");
        f.setLocation(10, 10);
        f.setVisible(true);
        f.setResizable(false);
        f.pack();

        Timer timer = new Timer(500, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel.repaint();
            }
        });
        timer.start();
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Birthday();
            }
        });
    }
}

DrawString.java

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;

public class DrawString extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        int width = getWidth();
        int height = getHeight();

        int x = 350;
        int y = 250;
        int red   = random(0,255);
        int green = random(0,255);
        int blue  = random(0,255);
        Color black = new Color(0,0,0);

        Color newColor = new Color(red,green,blue);
        g.setColor(newColor);
        g.fillRect(0,0,1000,500);
        g.setColor(black);
        g.setFont(new Font(null,Font.BOLD,40));
        g.drawString("Happy Birthday!",x,y);
    }

    public static int random(int min, int max)
    {
        int range = max - min + 1;
        int number = (int) (range * Math.random() + min);
        return number;
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(1000, 500);
    }
}

1 个答案:

答案 0 :(得分:8)

这与可调整大小和不可调整大小的边框之间的差异有关。

因为你在调用setVisible之前调用了setResizable,所以窗口没有对帧装饰的变化作出反应......

最后尝试拨打setVisible,例如......

    f.setResizable(false);
    f.pack();
    f.setVisible(true);

对于一般的UI创建,这通常是很好的建议,在建立UI内容和属性后最后调用setVisible;)