Small Student Program; using a grid
Hi, I know this might be somewhat simple code, but I can't figure out why this is not executing correctly. I'm basically just trying to make the robot move across the grid by increasing the index value of the panels[] array. I have tested whether or not the image of the robot appears and the image does in fact appear. The problem is running the insert(Robot robot, JPanel location) method inside the run() method. If i run insert(r, panels[locationCount]) in the grid constructor, it shows up.
But if i say,
insert(r, panels[locationCount]);
locationCount++;
inside of the run() method, there is no activity at all. It might be a simple mistake, but I'm curious to know why nothing shows up on the grid itself.
Following code:
package gridPack;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class grid extends JPanel{
private ImageIcon robotImg = new ImageIcon("robotImg.PNG");
private JPanel[] panels = new JPanel[100];
private Robot r;
private int locationCount = 0;
public grid(){
setLayout(new GridLayout(10,10));
for (int x = 0; x < panels.length; x++){
panels[x] = new JPanel();
panels[x].setBorder(BorderFactory.createLineBorder(Color.black));
}
r = new Robot();
insert(r, panels[0]);
for (int x = 0; x < panels.length; x++)
add(panels[x]);
setPreferredSize(new Dimension(500,500));
}
public void run(){
while(true){
locationCount+=1;
insert(r, panels[locationCount]);
try{
Thread.sleep(100);
}catch(InterruptedException e){}
}
}//end of run method
public void insert(Robot robot, JPanel location){
location.add(robot);
}
private class Robot extends JLabel{
public Robot(){
setIcon(getImage());
}
public ImageIcon getImage(){
return robotImg;
}
}
}
// this is the Main driver class
package gridPack;
import javax.swing.*;
public class Main extends JFrame{
public static void main(String[] args){
grid g = new grid();
JFrame frame = new JFrame("gridTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().add(g);
frame.pack();
g.run();
}
}
Re: Small Student Program; using a grid
Try calling repaint() after you change the GUI's contents.
Re: Small Student Program; using a grid
thanks norm! it worked. But now, i wanted to add different JLabel objects i've created. With said objects, I want them to appear on a random spot on the grid by pressing a JButton. But, the labels and their icons do not show up until i resize the frame. Is there a way to make them repaint without having to manually resize the frame?
Re: Small Student Program; using a grid
Whenever you add or remove components from a container you need to call the container's revalidate() method which instructs it to re-layout its components.