在此代码中,我向 jframe 添加了两个组件,并且还使用了重新验证和重新绘制,但仅查看了其中一个组件。我需要一种方法来刷新 jframe
class A extends JPanel{
int i ,j;
A(int i,int j){
this.i = i;
this.j = j;
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawOval(i,j,10,10);
}
}
public class T2d extends JPanel
{
public static void main(String[] args) {
JFrame jFrame = new JFrame("hi");
jFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
jFrame.add(new A(50,50));
jFrame.revalidate();//revalidate and repaint doesn't refresh the frame
jFrame.repaint();//i have read all the past question about this
//but none of them solved my problem.
jFrame.add(new A(1000,100));
jFrame.revalidate();
jFrame.repaint();
jFrame.setVisible(true);
}
}
最佳答案
JFrame
使用 BorderLayout
默认情况下,布局管理器仅更新您添加的最后一个组件 ( BorderLayout
)
您可以尝试更改布局管理器,也许 FlowLayout
或GridLayout
,但自从 A
不会覆盖 getPrefferedSize
方法,它将大小调整为 0x0
无论如何,由布局管理器控制。
参见Laying Out Components Within a Container了解更多详情
这也是一种毫无意义的调用revalidate
和repaint
在尚未可见的窗口上
关于java - 添加java 2d组件后如何刷新JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30995496/