in this code i added two components to the jframe and also used revalidate and repaint but only one of the components is being viewed. i need a way to refresh the 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
uses a BorderLayout
by default, so only the last component you added is been updated by the layout manager (BorderLayout
)
You could try changing the layout manager, maybe FlowLayout
or GridLayout
, but since A
doesn't override the getPrefferedSize
method, it will be sized to 0x0
by the layout managers anyway.
See Laying Out Components Within a Container for more details
It's also kind of pointless calling revalidate
and repaint
on a window that hasn't been made visible