有人可以解释为什么我的组件只有在我将鼠标悬停在它们应该在的位置时才会被绘制?
我设置了一个可以拖动到任何地方的无边框框架,并且我试图在右上角创建一个退出按钮,但直到我将鼠标悬停在它上面才会被绘制。我在 JFrame 上绘制背景图像,然后绘制我的按钮并将整个内容设置为可见。
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class GUI extends JFrame
{
private Image Background = null;
private static Point Offset = new Point();
public GUI() {
this.setUndecorated(true);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
AddListeners();
SetCustomTheme();
LoadBackground();
Layout();
pack();
this.setSize(300, 300);
this.setVisible(true);
}
private void Layout() {
GroupLayout Info = new GroupLayout(this.getContentPane());
this.getContentPane().setLayout(Info);
JButton Button = new JButton();
Info.setHorizontalGroup(
Info.createSequentialGroup()
.addComponent(Button)
);
Info.setVerticalGroup(
Info.createParallelGroup()
.addComponent(Button)
);
}
private void SetCustomTheme() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
}
private void LoadBackground() {
try {
Background = ImageIO.read(getClass().getResource("Images/meh.png"));
} catch (Exception Ex) {
}
}
private void SetCustomIcon() {
Image Icon = Toolkit.getDefaultToolkit().getImage("Images/lol.jpg");
setIconImage(Icon);
}
private void AddListeners() {
this.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
Offset.x = e.getX();
Offset.y = e.getY();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override public void mouseDragged(MouseEvent e) {
Point p = getLocation();
setLocation(p.x + e.getX() - Offset.x, p.y + e.getY() - Offset.y);
}
});
}
@Override public void paint(Graphics g) {
g.drawImage(Background, 0,0,this.getWidth(),this.getHeight(), null);
}
}