gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:37:54 28 4
gpt4 key购买 nike

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

Birthday Program

生日.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);
}
}

最佳答案

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

因为您在调用 setResizing 之前调用了 setVisible,所以窗口尚未对框架装饰的更改使用react...

尝试最后调用setVisible,例如......

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

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

关于java - JPanel 和 Frame 之间的默认彩色间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21617469/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com