gpt4 book ai didi

java - JPanel 中的 JPanel 在不同位置被绘制两次

转载 作者:行者123 更新时间:2023-11-29 05:56:45 27 4
gpt4 key购买 nike

我目前正致力于在 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();
}

}

最佳答案

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

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

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

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

关于java - JPanel 中的 JPanel 在不同位置被绘制两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11812324/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com