从actionlistener重新绘制JPanel

时间:2016-01-05 23:42:16

标签: java jpanel repaint cardlayout

我知道如何重新绘制JPanel存在多种威胁。我一直在尝试通过应用revalidate()和repaint()方法(在stackoverflow中找到)从actionlistener中重新绘制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是模拟面板内的一个网格,但我想这并不重要,因为重绘通过更改按钮文本来实现..

编辑:

    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);
    }

}

我通过改变二维数组中的位置让对象在网格上移动一步(右,左,上,对角线......)。

如何使用revalidate / repaint方法?

干杯

1 个答案:

答案 0 :(得分:1)

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

jPanel.update(jPanel.getGraphics());

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

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