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);
}
}
JFrameuses aBorderLayoutby default, so only the last component you added is been updated by the layout manager (BorderLayout)You could try changing the layout manager, maybe
FlowLayoutorGridLayout, but sinceAdoesn't override thegetPrefferedSizemethod, it will be sized to0x0by the layout managers anyway.See Laying Out Components Within a Container for more details
It's also kind of pointless calling
revalidateandrepainton a window that hasn't been made visible