每次调用repaint()方法后,为什么GUI元素会加倍?

时间:2016-07-16 15:03:20

标签: java swing graphics

我的GUI出现问题。我在我的jpanel上构建一个网格,这是一个单独的类,而不是扩展jframe的类。当我单击一个按钮并选择打开在jframe类中处理的网格,然后单击jpanel类中生成的网格时,会出现第二个网格。这意味着:另一个网格移动到原始网格的南边1厘米。我猜测它与repaint()方法有关,就像闪烁问题一样。我在jframe和jpanel类中调用该方法。我仍然无法绕过它。这里的问题在哪里?有趣的是,第二个网格一旦我点击我的gui窗口右上角的快捷方式就会消失,以最小化窗口然后最大化它。我提供两种方法,我认为这与我的问题有关。正下方是openFile方法,它对我的​​jframe类

中的buttonlistener作出反应
public void openFile() {
    final JFileChooser chooser = new JFileChooser();
    add(chooser);
    if (selectedFilePath != null) {
        chooser.setCurrentDirectory(new File(selectedFilePath));
    } else {
        chooser.setCurrentDirectory(new File(System
                .getProperty("user.home")));
    }
    int result = chooser.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
        selectedFilePath = selectedFile.getAbsolutePath();
        BGSRead bgs = new BGSRead();
        bgs.readString(selectedFilePath);
        bgs.readFile();
        width = bgs.getWidth();
        height = bgs.getHeight();
        numberOfIslands = bgs.getNumberOfIslands();
        islandsListInAscendingOrder = bgs.getIslandsOrder();
        bridgeList=bgs.getBridgeList();
        if (grid != null) {
            remove(grid);
        }
        grid = new GameField(width, height,   
        islandsListInAscendingOrder,bridgeList);
        add(grid);
        grid.setVisible(true);
        validate();
        repaint();
    }
}

,这是我的jpanel类中的paintComponent()方法:

protected void paintComponent(Graphics g) {
    // draw grid

    /*
     * for (int i = 0; i < height; i++) { g.drawLine(GameMain.GAP, i *
     * GameMain.GAPBETWEENPOINTS + GameMain.GAP, (width - 1) *
     * GameMain.GAPBETWEENPOINTS + GameMain.GAP, i *
     * GameMain.GAPBETWEENPOINTS + GameMain.GAP); } for (int i = 0; i <
     * width; i++) { g.drawLine(i * GameMain.GAPBETWEENPOINTS +
     * GameMain.GAP, GameMain.GAP, i * GameMain.GAPBETWEENPOINTS +
     * GameMain.GAP, (height - 1) * GameMain.GAPBETWEENPOINTS +
     * GameMain.GAP); }
     */
    // draw circles
    if (islandListInAscendingOrder.size() > 0) {
        for (int i = 0; i < islandListInAscendingOrder.size(); i++) {
            x = islandListInAscendingOrder.get(i).getIslandCoordinate().x
                    * GameMain.GAPBETWEENPOINTS + GameMain.GAP
                    - (GameMain.R / 2);
            y = islandListInAscendingOrder.get(i).getIslandCoordinate().y
                    * GameMain.GAPBETWEENPOINTS + GameMain.GAP
                    - (GameMain.R / 2);
            g.drawOval(x, y, GameMain.R, GameMain.R);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

protected void paintComponent(Graphics g) {

应改为:

protected void paintComponent(Graphics g) {
    super.paintComponent(g); // clear previous drawing!

调用super方法绘制组件背景,从而删除先前的绘图。