我编写了一个简单的程序,在打印“生日快乐!”时随机更改背景颜色。到屏幕上,但我看到了不必要的间距。我怎样才能解决这个问题?
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);
}
}
最佳答案
这与可调整大小和不可调整大小的框架边框之间的差异有关。
因为在调用setVisible
之前先调用setResizable
,所以窗口对框架装饰的变化没有反应...
例如,尝试最后调用setVisible
。
f.setResizable(false);
f.pack();
f.setVisible(true);
这通常是创建一般UI的好建议,在建立UI内容和属性后,最后调用
setVisible
;)