现在我的代码在程序更改的每一步都会打开一个新的JFrame,我希望这个JFrame代替刷新。这些数据应该显示捕食者捕食模拟,其中小鱼吃藻类,鲨鱼吃小鱼,鲨鱼和小鱼四处走动,互相吃。我已经设置了一种工作方式,但我需要帮助我已经拥有的数据表示。
编辑:现在我在按钮上有图像来表示三者中的每一个,他们移动的方式是用新图像刷新按钮。
JFrame frame=new JFrame(); //creates frame
JButton[][] grid; //names the grid of buttons
int width = Model.getGrid().length;
int length = Model.getGrid()[0].length;
frame.setLayout(new GridLayout(width,length)); //set layout
grid=new JButton[width][length]; //allocate the size of grid
int size = Model.getGameModel().copyOfActors().size();
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
size = Model.getGameModel().copyOfActors().size();
//don't think this for loop is written correctly. See if there is an actor with location == grid[x][y] and if not put a *
//shouldn't need this for loop at all
boolean foundAnActor = false;
for(int i = 0; i < size; i++)
{
if(Model.getGameModel().copyOfActors().get(i).getX() == x && Model.getGameModel().copyOfActors().get(i).getY() == y && foundAnActor == false)
{
grid[x][y] = new JButton(new ImageIcon (Model.getGameModel().copyOfActors().get(i).image)); //this should put the image on the button
foundAnActor = true;
}
}
if(foundAnActor == false)
{
grid[x][y]=new JButton(String.valueOf(Controller.stepsTaken) ); //creates new button
}
frame.add(grid[x][y]);
//tried to add a frame
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
// tried to add a frame
答案 0 :(得分:1)
好的,你似乎在JButtons中显示状态为ImageIcons,并且出错了。不要创建新的JButton,新的JFrame,而是创建一个JButton数组,当模型的状态发生变化时,只需遍历这个数组,通过调用JButton上的setIcon(...)
来传递状态JButton,传入相应的Icon基于模型状态。