JPanel中的JPanel在不同位置被抽取两次

时间:2012-08-04 22:05:11

标签: java swing custom-component paintcomponent jcomponent

我目前正致力于为新游戏在java中创建一些自定义UI。我现在正在创建一个窗口。无论如何,当我创建窗口(作为JPanel)并在该窗口的顶部添加另一个主面板时,对于主要内容,主面板在两个不同的位置(正确的一个)和一次在左上角。如图所示:

Image of the JPanel drawn twice in different locations
中心按钮是正确的按钮,位置正确,而左上角则没有。黑色是主面板的背景。

这是我正在尝试创建的窗口的代码:

package gui.elements;

import graphic.CutSprite;
import graphic.SpriteStorage;
import gui.CFont;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

public class CWindow extends JPanel {
    private static final long serialVersionUID = 1L;

    // The main panel, on which components in the window are to be placed
    private JPanel panel;

    private String title;

    public CWindow(String title) {
        this(title, 380, 380);
    }

    public CWindow(String title, int width, int height) {
        this.title = title;

        // Place the main panel of the window
        panel = new JPanel();
        panel.setBackground(Color.BLACK);
        add(panel);
    }

    @Override
    public void paintComponent(Graphics graphics) {
        super.paintComponents(graphics);
    }

    public JPanel getPanel() {
        return panel;
    }

}

这是CWindow被实例化并添加的框架:

package gui;

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import gui.elements.CWindow;

public class Screen {

    private static Screen single = new Screen();
    public static Screen get() { return single; }

    private JFrame frame;
    private PanelManager panelManager;
    private ScreenCanvas screenCanvas;

    /**
     * Constructor, set the window, and initialize the game.
     */
    public Screen() {
        frame = new JFrame("Game");

        // Frame (window) settings
        frame.setSize(860, 540);
        frame.setLocationRelativeTo(null); //Open window in center of screen
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        CWindow w = new CWindow("This is a window!");
        frame.add(w);

        JButton tf9 = new JButton("Dunno?");
        w.getPanel().add(tf9);

        // Display the window
        frame.setVisible(true);
    }


    /**
     * @return the height of the screen
     */
    public static int getHeight() {
        return get().frame.getHeight();
    }

    /**
     * @return the width of the screen
     */
    public static int getWidth() {
        return get().frame.getWidth();
    }


    /**
     * @param args
     */
    public static void main(String[] args) {
        Screen.get();
    }

}

1 个答案:

答案 0 :(得分:3)

好的,找到并回答,很奇怪。发布xD令人尴尬后6分钟。

好的,问题是CWindow类中以下代码中的super.paintComponents(graphics);

@Override
public void paintComponent(Graphics graphics) {
    super.paintComponents(graphics);
}

不知道为什么,但是当我移除那条线时它就起作用了。