Java中的repaint()

可能重复:
Java GUI repaint()问题?

我写了一个Java代码,但是我遇到了GUI问题。 当我将一个组件添加到JFrame对象中时,我调用repaint()方法以更新GUI但它不起作用。 但是当我最小化或调整此框架的大小时,GUI会更新。

这是我的代码:

public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(460, 500); frame.setTitle("Circles generator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); String input = JOptionPane.showInputDialog("Enter n:"); int n = Integer.parseInt(input); CircleComponent component = new CircleComponent(n); frame.add(component); component.repaint(); } 

如果您将JComponent添加到已经可见的Container,那么您已经调用了

 frame.getContentPane().validate(); frame.getContentPane().repaint(); 

例如

 import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(460, 500); frame.setTitle("Circles generator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SwingUtilities.invokeLater(new Runnable() { public void run() { frame.setVisible(true); } }); String input = JOptionPane.showInputDialog("Enter n:"); CustomComponents0 component = new CustomComponents0(); frame.add(component); frame.getContentPane().validate(); frame.getContentPane().repaint(); } static class CustomComponents0 extends JLabel { private static final long serialVersionUID = 1L; @Override public Dimension getMinimumSize() { return new Dimension(200, 100); } @Override public Dimension getPreferredSize() { return new Dimension(300, 200); } @Override public void paintComponent(Graphics g) { int margin = 10; Dimension dim = getSize(); super.paintComponent(g); g.setColor(Color.red); g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2); } } } 

只需写:

 frame.validate(); frame.repaint(); 

那样做。

问候

你正在以错误的顺序做事。

您需要先将所有 JComponents添加到JFrame,然后再调用pack()然后在JFrame上调用setVisible(true)

如果您以后添加了可能更改GUI大小的JComponents,则需要再次调用pack() ,然后在JFrame上repaint()

您可能还需要调用frame.repaint()来强制帧实际重绘自己。 在我尝试重新绘制组件之前我遇到了一些问题,并且在调用父级的repaint()方法之前它没有更新显示的内容。