1

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

JPanel 的图像在不同位置绘制了两次
中心按钮是正确的,并且位于正确的位置,而左上角不是。黑色是主面板的背景。

这是我要创建的窗口的代码:

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

}
4

1 回答 1

4

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

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

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

不知道为什么,但是当我删除该行时它起作用了。

于 2012-08-04T22:14:28.053 回答