1
我目前正在爲Java遊戲創建一些自定義用戶界面。我現在正在創建一個窗口。無論如何,當我創建窗口(作爲JPanel
)並在該窗口的頂部添加另一個主面板時,對於主要內容,主面板在兩個不同位置被繪製兩次,正確的一次,並且一次在左上角。喜歡的圖片顯示: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();
}
}
即將寫出自己:D – 2012-08-04 22:14:54
我敢打賭,如果你調用'super.paintComponent(graphics);',它會正常工作。 (注意.paintComponent中缺少's')。 :) – 2012-08-06 04:39:34
美麗,就像分號錯誤;)謝謝:-) – 2012-08-12 19:32:07