【发布时间】:2016-01-05 23:42:16
【问题描述】:
我知道如何重绘 JPanel 存在多种威胁。我一直在尝试通过应用 revalidate() 和 repaint() 方法(如在 stackoverflow 中找到的)从动作侦听器内部重新绘制 JPanel。可悲的是,这不起作用。但是当我只是更改按钮的文本时,它正在重新绘制!
public SimulationPanel()
{
//configure panel.....
/* ActionListener */
btnStepsIntoFuture.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0)
{
//Do something
/* refresh grid panel */
worldPanel.createGrid();
simPanel.revalidate(); //= not working
simPanel.repaint(); //= not working
//btnEndSim.setText("End world simulation "); = working
//btnEndSim.setText("End world simulation"); = working
}
});
/* Add components to Simulationpanel */
simPanel.add(buttonsOnTopPanel, BorderLayout.NORTH);
simPanel.add(worldPanel.getWorldPanel(), BorderLayout.CENTER);
simPanel.add(stepsIntoFuturePanel, BorderLayout.SOUTH);
}
额外信息:世界面板是模拟面板内的一个网格,但我想这并不重要,因为重绘是通过更改按钮的文本来工作的。..
编辑:
public void createGrid(){
/* Set constraint on GridBagLayout */
GridBagConstraints gbc = new GridBagConstraints();
/* Create world grid with panels */
for (int row = 0; row < SettingsPanel.getNrOfRows(); row++) {
for (int col = 0; col < SettingsPanel.getNrOfColumns(); col++) {
/* Add constraint for correct dimension (row ; column) */
gbc.gridx = col;
gbc.gridy = row;
/* Initialize new cell in world grid */
CellPanel cellPanel = new CellPanel();
/* Draw elements of grid */
drawBackgroundIcons(cellPanel, row, col);
drawBorders(cellPanel, row, col);
worldPanel.add(cellPanel, gbc);
}
}
/* Print overview */
printOverviewOfWorld();
}
/* draw background icon of object */
public void drawBackgroundIcons(CellPanel cellPanel, int row, int col)
{
/* Set person, zombie weapon icon as background image */
if(personArray[row][col] != null)
{
Image img = new ImageIcon(this.getClass().getResource("/resources/"+personArray[row][col].getName()+".png")).getImage();
cellPanel.setImg(img);
}
}
我通过改变二维数组中的位置让对象在网格上移动 1 步(右、左、上、对角线……)。
如何使用 revalidate/repaint 方法使其工作?
干杯
【问题讨论】:
-
问题是
worldPanel.createGrid();是做什么的?您在“worldPanel”上调用一个方法。您是否真的创建了新组件并将这些组件添加到“simPanel”?您不能只创建对 worldPanel 变量的新引用并期望组件自动添加到 simPanel。所以基本上我们无法回答你的问题,因为我们不知道你的代码到底做了什么。 -
感谢您的回答,我更新了问题。组件已正确添加到 simPanel。但是当我向未来迈出一步时,我不会添加额外的组件,我只想改变背景。提前谢谢
标签: java jpanel repaint cardlayout