Java - jpanel not showing correctly

Wratox1

Member
Reaction score
22
Hello, i've just started to enjoy programming java, and im currently makeing a small game.

but i've run into a problem where a jpanel does not display properly(unless i do mainFrame.pack(), but then the window is resized to a very small window) after i added components to it, set it visible, hide it, removed the compononents, and then add components and set it visible again.

at the moment i do remove all the components from the jpanel, but its only one component that needs to be removed, and then added again. I need to add, remove and then add this component again because its a jbutton which i reuse in 2 jpanels that are not displayed at the same time.

here is my code where i remove the jbutton called exitButton from the jpanel called mainMenuPane and then add it and the other components to the jpanel called menuPane(it's menuPane that is not displaying properly)

Code:
private void createGameGraphics()
	{
		mainMenuPane.removeAll();
		
		exitButton.setPreferredSize(new Dimension(150, 25));
                exitButton.setMaximumSize(exitButton.getPreferredSize()) ;
        
		menuPane.add(optionsButton);
		menuPane.add(exitToMenuButton);
		menuPane.add(exitButton);
		
		mainFrame.add(menuPane);
		graphicsPane.add(graphicsObject);
		
		mainFrame.add(graphicsPane);
		this.revalidate();
		t.start();
	}

and here i remove the jbutton from menuPane and add it to mainMenuPane

Code:
if ("Exit to Menu".equals(e.getActionCommand()))
		{
			t.stop();
			mainMenuShow();
			playGame = false;
			menuPane.removeAll();
			
			exitButton.setPreferredSize(new Dimension(200, 50));
        	        exitButton.setMaximumSize(exitButton.getPreferredSize()) ;
        	
        	        mainFrame.remove(menuPane);
			mainFrame.remove(graphicsPane);
			
		}

Code:
public void mainMenuShow()
	{	
		mainMenuPane.setOpaque(true); //content panes must be opaque
          
        
        mainFrame.setContentPane(mainMenuPane); 
        mainMenuPane.setBackground ( Color.black);
        mainMenuPane.setLayout(new BoxLayout( mainMenuPane, BoxLayout.Y_AXIS ) );
        
        //mainMenuPane.add(Box.createVerticalGlue()); = creates a glue, an invisible box
        
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(playButton);
        
        mainMenuPane.add(exitButton);
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        
        this.revalidate();
	}

here is a screenshot of how the jpanel looks when i've added the components, removed them and added them again:

graphicsbug.jpg

and here is how it should look:

graphicscorrect.jpg

anyone know why the jpanel displays like it does?

tell me if you want more code, but its about 500 lines of code(including empty lines), just so you know.

//wratox
 

Wratox1

Member
Reaction score
22
Code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.*;
import java.awt.KeyboardFocusManager;
import java.awt.Color;
import java.net.URL;

import javax.swing.*;
import javax.swing.Action;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JDialog;
import javax.swing.BoxLayout;
import javax.swing.border.LineBorder;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.Timer;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class Void_Wars extends JPanel implements ActionListener,KeyListener,FocusListener,PropertyChangeListener {
    
    private static Void_Wars mainMenuPane = new Void_Wars();
    private static JFrame mainFrame,exitGameDialogFrame;

	final JDialog exitGameDialog = new JDialog(exitGameDialogFrame,"",true);
	private JPanel exitGamePane,menuPane,graphicsPane;

    private JLabel exitGameLabel = new JLabel("Are you sure you want to exit?");
    
    private JMenuBar menuBar;
	private JMenu menu;
	private JMenuItem menuItem;
    
    private static JButton playButton,exitButton,exitGameYesButton,exitGameNoButton,optionsButton,exitToMenuButton;
	
	private GameGraphics graphicsObject = new GameGraphics();
	
	private Timer t = new Timer(30,this);
	
	private int gameWidth,gameHeight;
	private boolean playGame;
    public Void_Wars() {
    	
    	mainFrame = new JFrame("Void Wars");
    	exitGameDialogFrame = new JFrame();
    	
    	exitGamePane = new JPanel();
    	menuPane = new JPanel();
    	graphicsPane = new JPanel();
    	
    	setupEnterActionForAllButtons();
    	
    	////////////----------MenuButtons----------////////////
    	//----------playButton----------
        playButton = new JButton("Play");
        playButton.setVerticalTextPosition(AbstractButton.CENTER);
        playButton.setHorizontalTextPosition(AbstractButton.LEADING); 
        playButton.setMnemonic(KeyEvent.VK_ENTER); // Alt-P clicks the button
        
        playButton.setActionCommand("Play");
        
        playButton.setAlignmentX(CENTER_ALIGNMENT);  // For vertical positioning
        playButton.setPreferredSize(new Dimension(200, 50));
        playButton.setMaximumSize(playButton.getPreferredSize()) ;
        
        playButton.setBackground(Color.blue);
        playButton.setForeground(Color.white);
        playButton.setContentAreaFilled(false);
		playButton.setOpaque(true);
        playButton.setFocusPainted(false);
        playButton.setBorder(new LineBorder(Color.black, 2));
        playButton.setFont (new Font ("Helvetica", Font.PLAIN, 25));
        
        //Listeners for playButton
        playButton.addActionListener(this);
        playButton.addKeyListener(this); 
        playButton.addFocusListener(this);
        
        //----------exitButton----------
        exitButton = new JButton("Exit");
        exitButton.setVerticalTextPosition(AbstractButton.CENTER);
        exitButton.setHorizontalTextPosition(AbstractButton.LEADING); 
        exitButton.setMnemonic(KeyEvent.VK_ESCAPE); // Alt-ESCAPE clicks the button
        
        exitButton.setActionCommand("Exit");
        
        exitButton.setAlignmentX(CENTER_ALIGNMENT);  // For vertical positioning
        exitButton.setPreferredSize(new Dimension(200, 50));
        exitButton.setMaximumSize(exitButton.getPreferredSize()) ;
        
        exitButton.setBackground(Color.blue);
        exitButton.setForeground(Color.white);
        exitButton.setContentAreaFilled(false);
		exitButton.setOpaque(true);
        exitButton.setFocusPainted(false);
        exitButton.setBorder(new LineBorder(Color.black, 0));
        exitButton.setFont (new Font ("Helvetica", Font.PLAIN, 25));
        
        //Listeners for exitButton
        exitButton.addActionListener(this);
        exitButton.addKeyListener(this); 
        exitButton.addFocusListener(this);
		
        
        
        ////////////----------exitGameDialog----------////////////
        exitGameDialog.setUndecorated(true);
    	exitGameDialog.setSize(200, 100);
		exitGameDialog.setLocationRelativeTo(null);
		
        exitGameDialog.setContentPane(exitGamePane);
		
		exitGameYesButton = new JButton("Yes");
		exitGameNoButton = new JButton("No");
		
		
		//----------exitGameYesButton----------
		exitGameYesButton.setAlignmentX(CENTER_ALIGNMENT);  // For vertical positioning
        exitGameYesButton.setPreferredSize(new Dimension(75, 50));
        exitGameYesButton.setMaximumSize(playButton.getPreferredSize()) ;
        
        exitGameYesButton.setActionCommand("Yes");
        
        exitGameYesButton.setBackground(Color.blue);
        exitGameYesButton.setForeground(Color.white);
        exitGameYesButton.setContentAreaFilled(false);
		exitGameYesButton.setOpaque(true);
        exitGameYesButton.setFocusPainted(false);
        exitGameYesButton.setBorder(new LineBorder(Color.black, 0));
        exitGameYesButton.setFont (new Font ("Helvetica", Font.PLAIN, 25));
        
        //Listeners for exitGameYesButton
        exitGameYesButton.addActionListener(this);
        exitGameYesButton.addKeyListener(this); 
        exitGameYesButton.addFocusListener(this);
        
        //----------exitGameNoButton----------
        exitGameNoButton.setAlignmentX(CENTER_ALIGNMENT);  // For vertical positioning
        exitGameNoButton.setPreferredSize(new Dimension(75, 50));
        exitGameNoButton.setMaximumSize(playButton.getPreferredSize()) ;
		
		exitGameNoButton.setActionCommand("No");
		
		exitGameNoButton.setBackground(Color.blue);
		exitGameNoButton.setForeground(Color.white);
        exitGameNoButton.setContentAreaFilled(false);
		exitGameNoButton.setOpaque(true);
        exitGameNoButton.setFocusPainted(false);
        exitGameNoButton.setBorder(new LineBorder(Color.black, 0));
        exitGameNoButton.setFont (new Font ("Helvetica", Font.PLAIN, 25));
		
		//Listeners for exitGameNoButton
		exitGameNoButton.addActionListener(this);
        exitGameNoButton.addKeyListener(this); 
        exitGameNoButton.addFocusListener(this);
		
		//----------optionsButton----------
        optionsButton = new JButton("Options");
        optionsButton.setVerticalTextPosition(AbstractButton.CENTER);
        optionsButton.setHorizontalTextPosition(AbstractButton.LEADING); 
        optionsButton.setMnemonic(KeyEvent.VK_ENTER); // Alt-P clicks the button
        
        optionsButton.setActionCommand("Options");
        
        optionsButton.setAlignmentX(LEFT_ALIGNMENT);  // For vertical positioning
        optionsButton.setPreferredSize(new Dimension(150, 25));
        optionsButton.setMaximumSize(optionsButton.getPreferredSize()) ;
        
        optionsButton.setBackground(Color.blue);
        optionsButton.setForeground(Color.white);
        optionsButton.setContentAreaFilled(false);
		optionsButton.setOpaque(true);
        optionsButton.setFocusPainted(false);
        optionsButton.setBorder(new LineBorder(Color.black, 2));
        optionsButton.setFont (new Font ("Helvetica", Font.PLAIN, 25));
		
		//Listeners for optionsButton
        optionsButton.addActionListener(this);
        optionsButton.addKeyListener(this); 
        optionsButton.addFocusListener(this);
        
        //----------exitToMenuButton----------
        exitToMenuButton = new JButton("Exit to Menu");
        exitToMenuButton.setVerticalTextPosition(AbstractButton.CENTER);
        exitToMenuButton.setHorizontalTextPosition(AbstractButton.LEADING); 
        exitToMenuButton.setMnemonic(KeyEvent.VK_ENTER); // Alt-P clicks the button
        
        exitToMenuButton.setActionCommand("Exit to Menu");
        
        exitToMenuButton.setAlignmentX(LEFT_ALIGNMENT);  // For vertical positioning
        exitToMenuButton.setPreferredSize(new Dimension(150, 25));
        exitToMenuButton.setMaximumSize(exitToMenuButton.getPreferredSize()) ;
        
        exitToMenuButton.setBackground(Color.blue);
        exitToMenuButton.setForeground(Color.white);
        exitToMenuButton.setContentAreaFilled(false);
		exitToMenuButton.setOpaque(true);
        exitToMenuButton.setFocusPainted(false);
        exitToMenuButton.setBorder(new LineBorder(Color.black, 2));
        exitToMenuButton.setFont (new Font ("Helvetica", Font.PLAIN, 25));
		
		//Listeners for optionsButton
        exitToMenuButton.addActionListener(this);
        exitToMenuButton.addKeyListener(this); 
        exitToMenuButton.addFocusListener(this);
		
		menuPane.setPreferredSize(new Dimension(1366,35 ));
        menuPane.setMaximumSize(menuPane.getPreferredSize()) ;
		
		
		GridBagLayout exitGameGridBag  = new GridBagLayout();
   		exitGamePane.setLayout(exitGameGridBag);
    	GridBagConstraints c = new GridBagConstraints();

    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.gridwidth = 2;
    	c.gridx = 0;
    	c.gridy = 0;
    	exitGamePane.add(exitGameLabel, c);

    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.gridwidth = 1;
    	c.gridx = 0;
    	c.gridy = 1;
    	exitGamePane.add(exitGameYesButton, c);

    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.gridx = 1;
    	exitGamePane.add(exitGameNoButton, c);
		
		gameWidth = 1366;
		gameHeight = 700;
		
		graphicsObject.setPreferredSize(new Dimension(gameWidth, gameHeight));
		graphicsObject.setMaximumSize(graphicsObject.getPreferredSize());
		graphicsObject.setBackground(Color.black);
		
		graphicsPane.setPreferredSize(new Dimension(gameWidth, gameHeight));
		graphicsPane.setMaximumSize(graphicsPane.getPreferredSize());
		graphicsPane.setBackground(Color.black);
		
    }
    
    private void setupEnterActionForAllButtons() {
        
        InputMap im = (InputMap) UIManager.getDefaults().get("Button.focusInputMap");
        Object pressedAction = im.get(KeyStroke.getKeyStroke("pressed SPACE"));
        Object releasedAction = im.get(KeyStroke.getKeyStroke("released SPACE"));

        im.put(KeyStroke.getKeyStroke("pressed ENTER"), pressedAction);
        im.put(KeyStroke.getKeyStroke("released ENTER"), releasedAction);
        
    }

    public void actionPerformed(ActionEvent e)
	{
		if ("Exit".equals(e.getActionCommand()))
		{
			exitGame();
		}
		
		if ("Play".equals(e.getActionCommand()))
		{
			createGameGraphics();
			playGame = true;
		}
		
		if ("Yes".equals(e.getActionCommand()))
		{
			System.exit(0);
		}
		
		if ("No".equals(e.getActionCommand()))
		{
			exitGameDialog.setVisible(false);
		}
		
		if ("Exit to Menu".equals(e.getActionCommand()))
		{
			t.stop();
			mainMenuShow();
			playGame = false;
			menuPane.removeAll();
			
			exitButton.setPreferredSize(new Dimension(200, 50));
        	exitButton.setMaximumSize(exitButton.getPreferredSize()) ;
        	
        	mainFrame.remove(menuPane);
			mainFrame.remove(graphicsPane);
			
		}
		
		if(playGame)
		{
			graphicsObject.repaint();
		}
		this.revalidate();
	}

	public void keyPressed(KeyEvent e)
	{
		int key = e.getKeyCode();
		if ((key == KeyEvent.VK_ENTER && KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == playButton) || key == KeyEvent.VK_P)
		{
			createGameGraphics();
			playGame = true;
		}
		
		if ((key == KeyEvent.VK_ENTER && KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == exitButton) || key == KeyEvent.VK_ESCAPE)
		{
			exitGame();
		}
	}
	
	public void keyReleased(KeyEvent e)
	{
		
	}
	
	public void keyTyped(KeyEvent e)
	{
		
	}
	
	public void focusLost(FocusEvent e)
	{
		if(e.getComponent() == playButton)
		{
			playButton.setBorder(new LineBorder(Color.black, 2));
		}
		if(e.getComponent() == exitButton)
		{
			exitButton.setBorder(new LineBorder(Color.black, 2));
		}
		if(e.getComponent() == exitGameYesButton)
		{
			exitGameYesButton.setBorder(new LineBorder(Color.black, 2));
		}
		if(e.getComponent() == exitGameNoButton)
		{
			exitGameNoButton.setBorder(new LineBorder(Color.black, 2));
		}
	}
	
	public void focusGained(FocusEvent e)
	{
		if(e.getComponent() == playButton)
		{
			playButton.setBorder(new LineBorder(Color.orange, 2));
		}
		if(e.getComponent() == exitButton)
		{
			exitButton.setBorder(new LineBorder(Color.orange, 2));
		}
		if(e.getComponent() == exitGameYesButton)
		{
			exitGameYesButton.setBorder(new LineBorder(Color.orange, 2));
		}
		if(e.getComponent() == exitGameNoButton)
		{
			exitGameNoButton.setBorder(new LineBorder(Color.orange, 2));
		}
	}
	
	public void propertyChange(PropertyChangeEvent evt)
	{
		
	}
	
	private void exitGame()
	{
		exitGameDialog.setVisible(true);
	}
	
	private void createGameGraphics()
	{
		mainMenuPane.removeAll();
		
		exitButton.setPreferredSize(new Dimension(150, 25));
        exitButton.setMaximumSize(exitButton.getPreferredSize()) ;
        
		menuPane.add(optionsButton);
		menuPane.add(exitToMenuButton);
		menuPane.add(exitButton);
		
		mainFrame.add(menuPane);
		graphicsPane.add(graphicsObject);
		
		mainFrame.add(graphicsPane);
		this.revalidate();
		t.start();
	}
	
	public void mainMenuShow()
	{	
		mainMenuPane.setOpaque(true); //content panes must be opaque
          
        
        mainFrame.setContentPane(mainMenuPane); 
        mainMenuPane.setBackground ( Color.black);
        mainMenuPane.setLayout(new BoxLayout( mainMenuPane, BoxLayout.Y_AXIS ) );
        
        //mainMenuPane.add(Box.createVerticalGlue()); = creates a glue, an invisible box
        
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(playButton);
        
        mainMenuPane.add(exitButton);
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        
        this.revalidate();
	}
	
    // Returns an ImageIcon, or null if the path was invalid. 
   /* protected static ImageIcon createImageIcon(String path) {
        URL imgURL = Void_Wars.class.getResource(path);	
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find image in system: " + path);
            return null;
        }
    }*/

    //Create the GUI and show it.  
    private static void createGUI() {
		UIManager.put("Button.select", Color.yellow.darker());
		UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
		
        try
        {
	    	// Set System L&F
       		 UIManager.setLookAndFeel(
            UIManager.getSystemLookAndFeelClassName());
    	} 
    	catch (UnsupportedLookAndFeelException e)
    	{
       		// handle exception
    	}
    	catch (ClassNotFoundException e)
    	{
       		// handle exception
    	}
    	catch (InstantiationException e)
    	{
       		// handle exception
    	}
    	catch (IllegalAccessException e)
    	{
       		// handle exception
    	}

        //Create and set up the frame.
        
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
        //Create and set up the content pane.
        
        
        mainMenuPane.setOpaque(true); //content panes must be opaque
          
        
        mainFrame.setContentPane(mainMenuPane); 
        mainMenuPane.setBackground ( Color.black);
        mainMenuPane.setLayout(new BoxLayout( mainMenuPane, BoxLayout.Y_AXIS ) );
        
        //mainMenuPane.add(Box.createVerticalGlue()); = creates a glue, an invisible box
        
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(playButton);
        
        mainMenuPane.add(exitButton);
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        mainMenuPane.add(Box.createVerticalGlue());
        
        
        //frame.getRootPane().setDefaultButton(null);
        //Display the window.
        mainFrame.pack();
        mainFrame.setExtendedState(mainFrame.getExtendedState()|JFrame.MAXIMIZED_BOTH);
        mainFrame.setVisible(true);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createGUI(); 
            }
        });
    }
}

Code:
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
class GameGraphics extends JPanel {
	
	
	
	public GameGraphics()
	{
		
	}
	
	public void repaint(Graphics g)
	{
		paintComponent(g);
	}
	
	public void paintComponent(Graphics g)
	{
       super.paintComponent(g);    // paint background, borders
       g.setColor(Color.black);
       g.fillRect(0,0,getWidth()-280,getHeight());
       g.setColor(Color.white);
       for(int yLines=0; yLines<19; yLines++)
       {
   		   g.drawLine(yLines*60,0,yLines*60,660);
  	   }
  	   for(int xLines=0; xLines<12; xLines++)
  	   {
   		   g.drawLine(0,xLines*60,1080,xLines*60);
  	   }
  	   /*g.setColor(Color.gray);
  	   g.fillRect(241,241,59,59);
  	   g.setColor(Color.gray);
  	   g.fillRect(241,301,59,59);*/
   }
}
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
I have been over the code and I wasn't able to find the error.

When it's not your code and not your way to program, it's hard to go throught the steps of the program.
Note that when you import a whole package (*), you don't need to import classes from it...

Also, when I program games in Java, I don't use the Swing API...

I override the paint(Graphics g) method of a JPanel, nothing more.

Look for double buffereing if you're interested in it.
http://profs.etsmtl.ca/mmcguffin/learn/java/07-backbuffer/ (Best tutorial I've ever found, Montreal School)
 

Wratox1

Member
Reaction score
22
I have been over the code and I wasn't able to find the error.

When it's not your code and not your way to program, it's hard to go throught the steps of the program.
Note that when you import a whole package (*), you don't need to import classes from it...

Also, when I program games in Java, I don't use the Swing API...

I override the paint(Graphics g) method of a JPanel, nothing more.

Look for double buffereing if you're interested in it.
http://profs.etsmtl.ca/mmcguffin/learn/java/07-backbuffer/ (Best tutorial I've ever found, Montreal School)

i know that when i import package i dont need to import classes, but if i didn't then i got error messages saying the program couldn't find the classes..

why shouldn't i use Swing API?

i know what double buffering is, just didnt think i would need it atm..
 

UndeadDragon

Super Moderator
Reaction score
447
Using Swing API is fine, but from previous experience, it is not the easiest thing to position elements with. I usually end up giving up and use Netbean's visual GUI editor :p

Even if your code is perfect I find that they never quite display how you want.
 

Wratox1

Member
Reaction score
22
Using Swing API is fine, but from previous experience, it is not the easiest thing to position elements with. I usually end up giving up and use Netbean's visual GUI editor :p

Even if your code is perfect I find that they never quite display how you want.

well, at the moment the elements are in the right position, but as you can see in my screenshot the jpanel is displayed wierd, but its still in the right position.
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
That's so true.

What I meant is that an app like Minecraft, isn't using Swing for displauy... It's using java.applet.Applet and overrided paint and update methods.
 

Wratox1

Member
Reaction score
22
That's so true.

What I meant is that an app like Minecraft, isn't using Swing for displauy... It's using java.applet.Applet and overrided paint and update methods.

but what do you suggest i should do to fix my problem? since i dont know anything in my code that should cause this, though im not that experienced..
 

Wratox1

Member
Reaction score
22
Yay, i fixed it, by setting menuPane.setVisible(false) when i go to main menu, and adding it to mainFrame and menuPane.setVisible(true) when i click the playbutton;) maybe not the best solution but it works :)
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top