Reputation: 1233
I'm currently working on creating some custom UI in java for a new game. And I'm creating a window at the moment. Anyway, when I create the window (as a JPanel
) and add another main panel on top of that one, for the main content, the main panel gets drawn twice in two different locations, the correct one, and once in the top left corner. Like the picture indicates:
The center button is the correct one, and is located correctly whilst the top left isn't. The black is the background of the main panel.
And here's the code of the window I'm trying to create:
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;
}
}
And here's the frame where CWindow
is instantiated and added:
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();
}
}
Upvotes: 1
Views: 989
Reputation: 1233
Okay, found and answer, weird enough. 6 mins after posting xD embarrassing.
okay, so the problem was the super.paintComponents(graphics);
in the following code in the CWindow class
@Override
public void paintComponent(Graphics graphics) {
super.paintComponents(graphics);
}
No idea why, but it worked when i removed that line.
Upvotes: 4