我知道如何重绘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);
}


额外的信息:worldpanel是Simulationpanel内部的一个网格,但是我想这没关系,因为重新绘制可以通过更改按钮的文本来实现。

编辑:

    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方法一起使用?

干杯

最佳答案

您可以使用如下所示的update(Graphics g)方法:

jPanel.update(jPanel.getGraphics());


为我工作,而无需使用任何Worker或Runnable。

仍然不知道为什么它重新绘制JFrame的Minimum Size,但是它可以工作。

10-06 02:23