Results 1 to 10 of 10
Like Tree3Likes
  • 1 Post By SurfMan
  • 1 Post By jim829
  • 1 Post By jim829

Thread: Need help with JPanels

  1. #1
    Sizzlewump's Avatar
    Sizzlewump is offline Member
    Join Date
    Oct 2010
    Location
    MI, USA
    Posts
    68
    Rep Power
    0

    Default Need help with JPanels

    Is the JFrame the container that holds the JPanels? If so I'm trying to make a JFrame with 2 JPanels inside. The west panel will be a grid of buttons. The east panel will be a list of 12 radio buttons. Like this:

    Need help with JPanels-samplegrid.png


    Here's my starting point code:

    Java Code:
    import javax.swing.*;
    import java.awt.*;
     
    public class BorderLayoutDemo2 {
        public static boolean RIGHT_TO_LEFT = false;
         
        public static void addComponentsToPane(Container pane) {
             
            if (!(pane.getLayout() instanceof BorderLayout)) {
                pane.add(new JLabel("Container doesn't use BorderLayout!"));
                return;
            }
             
            if (RIGHT_TO_LEFT) {
                pane.setComponentOrientation(
                        java.awt.ComponentOrientation.RIGHT_TO_LEFT);
            }
             
            JButton button = new JButton("Default");
    
            button = new JButton("Left");
            button.setPreferredSize(new Dimension(200, 100));
            pane.add(button, BorderLayout.CENTER);
             
            button = new JButton("Right");
            pane.add(button, BorderLayout.LINE_END);
        }
         
        private static void createAndShowGUI() {
    
            JFrame frame = new JFrame("BorderLayoutDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            addComponentsToPane(frame.getContentPane());
            frame.pack();
            frame.setVisible(true);
        }
         
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            } catch (UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            UIManager.put("swing.boldMetal", Boolean.FALSE);
             
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    I'm not sure where to go from here. Having a hard time with GridLayout vs BorderLayout. What needs to happen for me to modify the sizes of the panels? When I try to change the parameters at line 22 it seems to do nothing. Is this due to the .pack call at line 34?
    "The secret to getting what you want is to reject everything that you don't want." -Wolbers

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,991
    Rep Power
    8

    Default Re: Need help with JPanels

    You need three JPanels:
    1) A JPanel with the BorderLayout that contains the grid in the center and the radiobuttons in east (JPanel 2 and 3 in this list).
    2) A JPanel that has the GridLayout of (20 rows and 10 columns) and contains the buttons.
    3) A JPanel that can either have a GridLayout (10 rows, 1 column), or a FlowLayout, and it contains the radiobuttons.

    Most layouts automatically size their contents. So you can set a preferredSize on the button, but the layout will override that.
    Sizzlewump likes this.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    Sizzlewump's Avatar
    Sizzlewump is offline Member
    Join Date
    Oct 2010
    Location
    MI, USA
    Posts
    68
    Rep Power
    0

    Default Re: Need help with JPanels

    Surfman, I tried your advice and had some big success! Thanks a ton! I actually went back and simplified most of the code down to a more basic form.

    Now I'm trying to decide how to go about the next part. In the east JPanel (optionsPane), I want to have 7 options. The first 2 options will have multiple sub-options (I'm thinking JComboBox). For the remaining 5 options I think they should be JRadioButton's. Each of the JComboBoxes will have a subset of thumbnail images. My long-term goal for each option is to have it toggle any button in the center JPanel to display a different thumbnail (much as in minesweeper). So only one option should be selected at any time and subsequent button clicks on the center panel (gridPane) will toggle an image. If another option is selected and a non-default button in the center grid is clicked, it should change the image on the button to the new selection. Does this make sense?

    I thought to have the first 2 options as some combination of JComboBoxes and JRadioButtons, but that doesn't seem very visually appealing to me. Perhaps I should make an extra JradioButton that simply says "none" which will be defaulted when a JComboBox selection is made.

    Here's my new code and thanks again for any and all suggestions! You guys do a great job of helping java-hacks like myself on here.

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.lang.*;
    
    public class TryStuff extends JFrame
    {
    
       private JPanel outerPane = new JPanel();
    	private JPanel gridPane = new JPanel();
    	private JPanel optionsPane = new JPanel();
    	private JButton tiles[][];
    	private JLabel landLabel;
    	private JComboBox landOptions;
    	
    	public TryStuff(String title)
    	{
    	   //set a title & min size for outer frame
    	   super(title);
    		setMinimumSize(new Dimension(1000, 800));
    		
    		//setup combo box land
    		String[] landNames =
    		{"position1.png","position2.png","position3.png","position4.png","position5.png",
    		"position6.png","position7.png","position8.png","position9.png","position10.png",
    		"position11.png","position12.png","position13.png","position14.png","position15.png"};
    		
    		Icon[] icons = {
    		   new ImageIcon(getClass().getResource(landNames[0])),
    			new ImageIcon(getClass().getResource(landNames[1])),
    	      new ImageIcon(getClass().getResource(landNames[2])),
    			new ImageIcon(getClass().getResource(landNames[3])),
    			new ImageIcon(getClass().getResource(landNames[4])),
    			new ImageIcon(getClass().getResource(landNames[5])),
    			new ImageIcon(getClass().getResource(landNames[6])),
    			new ImageIcon(getClass().getResource(landNames[7])),
    			new ImageIcon(getClass().getResource(landNames[8])),
    			new ImageIcon(getClass().getResource(landNames[9])),
    			new ImageIcon(getClass().getResource(landNames[10])),
    			new ImageIcon(getClass().getResource(landNames[11])),
    			new ImageIcon(getClass().getResource(landNames[12])),
    			new ImageIcon(getClass().getResource(landNames[13])),
    			new ImageIcon(getClass().getResource(landNames[14]))};
    		//add components to panels
    		tiles = new JButton[29][31];
    		buildButtons();
    		
    		optionsPane.add(new JButton("FirstImage"));
    		
    		landOptions = new JComboBox(landNames);
    		landOptions.setMaximumRowCount(15);
    		landLabel = new JLabel(icons[0]);
    		optionsPane.add(landLabel);
    		//add panel layouts then panels
    		gridPane.setLayout(new GridLayout(29,31));
    		optionsPane.setLayout(new GridLayout(7,1));
    		outerPane.setLayout(new BorderLayout());
    		getContentPane().add(outerPane);
    		
    		optionsPane.add(landOptions);
    		outerPane.add(gridPane, BorderLayout.CENTER);
    		outerPane.add(optionsPane, BorderLayout.EAST);
    		
    		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    	}
    	
    	private void buildButtons()
       {
          for(int i=0;i<29;i++)
    	   {
             for(int j=0;j<31;j++)
    		   {
                tiles[i][j] = new JButton();
                tiles[i][j].setSize(400,400);
                gridPane.add(tiles[i][j]);
             }
          }
       }
    		
       public static void main(String[] args)
    	{
    	   //make instance of frame object & display it
          TryStuff t = new TryStuff("Place a title for the frame here");
    		t.pack();
    		t.setVisible(true);
    	}
    
    
    }
    "The secret to getting what you want is to reject everything that you don't want." -Wolbers

  4. #4
    Sizzlewump's Avatar
    Sizzlewump is offline Member
    Join Date
    Oct 2010
    Location
    MI, USA
    Posts
    68
    Rep Power
    0

    Default Re: Need help with JPanels

    It may go without saying, but if anyone is interested in trying out this code, be sure to make a workaround for the 15 .png resources that are referenced in the code. Or you can use this one and copy it 15 times:
    Need help with JPanels-position1.png
    "The secret to getting what you want is to reject everything that you don't want." -Wolbers

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Need help with JPanels

    Might I recommend you stay away from "magic numbers?" Those are numbers which are used as
    constants throughout a program and have no assigned meaning.

    Java Code:
    tiles = newJButton[29][31];
    Better practice would be to use something like:

    Java Code:
    private final static int ROWS = 29;
    private final static int COLS = 31;
    tiles = new JButton[ROWS][COLS];
    Since you use those values elsewhere it makes it easier for you and others to maintain
    your code as it helps to document the values. And if you need to change one of them
    you only need to focus on one location and not several locations.

    Regards,
    Jim
    Sizzlewump likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  6. #6
    Sizzlewump's Avatar
    Sizzlewump is offline Member
    Join Date
    Oct 2010
    Location
    MI, USA
    Posts
    68
    Rep Power
    0

    Default Re: Need help with JPanels

    Thanks for pointing that out, Jim. That was an oversight on my part, you are quite right. I have changed my code to reflect your advice. Still need to work out some kinks in the code. My next step is figuring out how to associate a click in the options panel with a click in the grid panel. Since I created the buttons in the grid using an array, I'm not exactly sure how to reference them individually.

    Could I do something like an if statement that reads "if the last button clicked is in panel "X", then change button "Y" label to the label of last button clicked,"?
    "The secret to getting what you want is to reject everything that you don't want." -Wolbers

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Need help with JPanels

    Quote Originally Posted by Sizzlewump View Post
    Could I do something like an if statement that reads "if the last button clicked is in panel "X", then change button "Y" label to the label of last button clicked,"?
    I am not entirely certain what your overall goal is. However, for any set of buttons, you will need a listener. Those buttons may share the same listener.
    When the button is clicked, you can find out which button was clicked inside the listener by interrogating the event source from the event object. It would be
    a simple matter of maintaining a reference to the last button clicked and swap images.

    Regards,
    Jim
    Sizzlewump likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    Sizzlewump's Avatar
    Sizzlewump is offline Member
    Join Date
    Oct 2010
    Location
    MI, USA
    Posts
    68
    Rep Power
    0

    Default Re: Need help with JPanels

    Okay, that sounds like good news. I think I'm a little confused about button labels. I was thinking that the text you can read on the button is the label and that you could interchange an image for that text.

    My end goal is to fill in the grid on the left using the right panel as my 'paint palette' if you will. Here is my latest code:
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.lang.*;
    import java.awt.event.*;
     
    public class TryStuff extends JFrame
    {
     
       private JPanel outerPane = new JPanel();
       private JPanel gridPane = new JPanel();
       private JPanel optionsPane = new JPanel();
       private JButton tiles[][];
       private JLabel landLabel;
    	private JLabel artifactLabel;
    	private JComboBox landOptions;
    	private JComboBox artifactOptions;
       private final static int ROWS = 29;
    	private final static int COLS = 31;
    	
        public TryStuff(String title)
        {
           //set a title & min size for outer frame
           super(title);
            setMinimumSize(new Dimension(1000, 800));
             
            //setup combo box land
            String[] landNames =
            {"position1.png","position2.png","position3.png","position4.png","position5.png",
            "position6.png","position7.png","position8.png","position9.png","position10.png",
            "position11.png","position12.png","position13.png","position14.png","position15.png"};
             
            final Icon[] landIcons = {
               new ImageIcon(getClass().getResource(landNames[0])),
               new ImageIcon(getClass().getResource(landNames[1])),
               new ImageIcon(getClass().getResource(landNames[2])),
               new ImageIcon(getClass().getResource(landNames[3])),
               new ImageIcon(getClass().getResource(landNames[4])),
               new ImageIcon(getClass().getResource(landNames[5])),
               new ImageIcon(getClass().getResource(landNames[6])),
               new ImageIcon(getClass().getResource(landNames[7])),
               new ImageIcon(getClass().getResource(landNames[8])),
               new ImageIcon(getClass().getResource(landNames[9])),
               new ImageIcon(getClass().getResource(landNames[10])),
               new ImageIcon(getClass().getResource(landNames[11])),
               new ImageIcon(getClass().getResource(landNames[12])),
               new ImageIcon(getClass().getResource(landNames[13])),
               new ImageIcon(getClass().getResource(landNames[14]))};
    		  
    		  //setup combo box artifact
    		  String[] artifactNames =
    		  {"ark.png", "sevenCities.png", "ankor.png", "atlantis.png", "templar.png", "confucius.png"};
            
    		  final Icon[] artifactIcons = {
    		     new ImageIcon(getClass().getResource(artifactNames[0])),
    			  new ImageIcon(getClass().getResource(artifactNames[1])),
    			  new ImageIcon(getClass().getResource(artifactNames[2])),
    			  new ImageIcon(getClass().getResource(artifactNames[3])),
    			  new ImageIcon(getClass().getResource(artifactNames[4])),
    			  new ImageIcon(getClass().getResource(artifactNames[5]))};
    		  
    		  //add components to panels
            tiles = new JButton[ROWS][COLS];
    		  buildButtons();
            landOptions = new JComboBox(landNames);
            landOptions.setMaximumRowCount(15);
            landLabel = new JLabel(landIcons[0]);
            optionsPane.add(landLabel);
    		  
    		  landOptions.addItemListener(
    		     new ItemListener()
    			  {
    			     public void itemStateChanged(ItemEvent event)
    				  {
    				     if(event.getStateChange() == ItemEvent.SELECTED)
    					     landLabel.setIcon(landIcons[
    						     landOptions.getSelectedIndex()]);
    				  }
    			  }
    		  );
    		  
    		  artifactOptions = new JComboBox(artifactNames);
    		  artifactOptions.setMaximumRowCount(6);
    		  artifactLabel = new JLabel(artifactIcons[0]);
    		  optionsPane.add(artifactLabel);
    		  artifactOptions.addItemListener(
    		     new ItemListener()
    			  {
    			     public void itemStateChanged(ItemEvent event)
    				  {
    				     if(event.getStateChange() == ItemEvent.SELECTED)
    					     artifactLabel.setIcon(artifactIcons[
    						     artifactOptions.getSelectedIndex()]);
    				  }
    			  }
    		  );
    		  
    		  optionsPane.add(new JButton("Mountain"));
    		  optionsPane.add(new JButton("Friendly Village"));
    		  optionsPane.add(new JButton("Barbarian Village"));
    		  optionsPane.add(new JButton("Landmark"));
    		  optionsPane.add(new JButton("Capitol"));
    
    
            //add panel layouts then panels
            gridPane.setLayout(new GridLayout(ROWS,COLS));
            optionsPane.setLayout(new GridLayout(7,1));
            outerPane.setLayout(new BorderLayout());
            getContentPane().add(outerPane);
             
            optionsPane.add(landOptions);
    		  optionsPane.add(artifactOptions);
            outerPane.add(gridPane, BorderLayout.CENTER);
            outerPane.add(optionsPane, BorderLayout.EAST);
             
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
         
        private void buildButtons()
        {
          for(int i=0;i<ROWS;i++)
           {
             for(int j=0;j<COLS;j++)
               {
                tiles[i][j] = new JButton();
                tiles[i][j].setSize(400,400);
                gridPane.add(tiles[i][j]);
             }
          }
        }
             
       public static void main(String[] args)
        {
           //make instance of frame object & display it
          TryStuff t = new TryStuff("Place a title for the frame here");
            t.pack();
            t.setVisible(true);
        }
    }
    Thanks again!
    "The secret to getting what you want is to reject everything that you don't want." -Wolbers

  9. #9
    Sizzlewump's Avatar
    Sizzlewump is offline Member
    Join Date
    Oct 2010
    Location
    MI, USA
    Posts
    68
    Rep Power
    0

    Default Re: Need help with JPanels

    This is my working applet:
    Need help with JPanels-output.png
    "The secret to getting what you want is to reject everything that you don't want." -Wolbers

  10. #10
    Sizzlewump's Avatar
    Sizzlewump is offline Member
    Join Date
    Oct 2010
    Location
    MI, USA
    Posts
    68
    Rep Power
    0

    Default Re: Need help with JPanels

    How can I get my code to call on artifactLabel.getIcon() and then have it set a button label from my gridPane to display the same image? I feel like I almost have it worked out, but something escapes me.

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.lang.*;
    import java.awt.event.*;
     
    public class TryStuff2 extends JFrame //implements ActionListener
    {
     
       private JPanel outerPane = new JPanel();
       private JPanel gridPane = new JPanel();
       private JPanel optionsPane = new JPanel();
       private JButton tiles[][];
       private JLabel landLabel;
    	private JLabel artifactLabel;
    	private JComboBox landOptions;
    	private JComboBox artifactOptions;
    	//private JTextField status = new JTextField(12);
       private final static int ROWS = 29;
    	private final static int COLS = 31;
    	
        public TryStuff2(String title)
        {
           //set a title & min size for outer frame
           super(title);
            setMinimumSize(new Dimension(1000, 800));
    		  
            //setup combo box land
            String[] landNames =
            {"position1.png","position2.png","position3.png","position4.png","position5.png",
            "position6.png","position7.png","position8.png","position9.png","position10.png",
            "position11.png","position12.png","position13.png","position14.png","position15.png"};
             
            final Icon[] landIcons = {
               new ImageIcon(getClass().getResource(landNames[0])),
               new ImageIcon(getClass().getResource(landNames[1])),
               new ImageIcon(getClass().getResource(landNames[2])),
               new ImageIcon(getClass().getResource(landNames[3])),
               new ImageIcon(getClass().getResource(landNames[4])),
               new ImageIcon(getClass().getResource(landNames[5])),
               new ImageIcon(getClass().getResource(landNames[6])),
               new ImageIcon(getClass().getResource(landNames[7])),
               new ImageIcon(getClass().getResource(landNames[8])),
               new ImageIcon(getClass().getResource(landNames[9])),
               new ImageIcon(getClass().getResource(landNames[10])),
               new ImageIcon(getClass().getResource(landNames[11])),
               new ImageIcon(getClass().getResource(landNames[12])),
               new ImageIcon(getClass().getResource(landNames[13])),
               new ImageIcon(getClass().getResource(landNames[14]))};
    		     
    		  //setup combo box artifact
    		  String[] artifactNames =
    		  {"ark.png", "sevenCities.png", "ankor.png", "atlantis.png", "templar.png", "confucius.png"};
            
    		  final Icon[] artifactIcons = {
    		     new ImageIcon(getClass().getResource(artifactNames[0])),
    			  new ImageIcon(getClass().getResource(artifactNames[1])),
    			  new ImageIcon(getClass().getResource(artifactNames[2])),
    			  new ImageIcon(getClass().getResource(artifactNames[3])),
    			  new ImageIcon(getClass().getResource(artifactNames[4])),
    			  new ImageIcon(getClass().getResource(artifactNames[5]))};
    		  
    		  //add components to panels
            tiles = new JButton[ROWS][COLS];
    		  buildButtons();
            landOptions = new JComboBox(landNames);
            landOptions.setMaximumRowCount(15);
    		  
    		  landOptions.addItemListener(
    		     new ItemListener()
    			  {
    			     public void itemStateChanged(ItemEvent event)
    				  {
    				     if(event.getStateChange() == ItemEvent.SELECTED)
    					     artifactLabel.setIcon(landIcons[
    						     landOptions.getSelectedIndex()]);
    				  }
    			  }
    		  );
    		  
    		  artifactOptions = new JComboBox(artifactNames);
    		  artifactOptions.setMaximumRowCount(6);
    		  artifactLabel = new JLabel(artifactIcons[0]);
    		  optionsPane.add(artifactLabel);
    		  artifactOptions.addItemListener(
    		     new ItemListener()
    			  {
    			     public void itemStateChanged(ItemEvent event)
    				  {
    				     if(event.getStateChange() == ItemEvent.SELECTED)
    					     artifactLabel.setIcon(artifactIcons[
    						     artifactOptions.getSelectedIndex()]);
    				  }
    			  }
    		  ); 
    		  
    		  optionsPane.add(new JButton("Mountain"));
    		  optionsPane.add(new JButton("Friendly Village"));
    		  optionsPane.add(new JButton("Barbarian Village"));
    		  optionsPane.add(new JButton("Landmark"));
    		  optionsPane.add(new JButton("Capitol"));
    
            //add panel layouts then panels
            gridPane.setLayout(new GridLayout(ROWS,COLS));
            optionsPane.setLayout(new GridLayout(7,1));
            outerPane.setLayout(new BorderLayout());
            getContentPane().add(outerPane);
             
            optionsPane.add(landOptions);
    		  optionsPane.add(artifactOptions);
    		  //optionsPane.add(status);
            //status.setEnabled(false);
            outerPane.add(gridPane, BorderLayout.CENTER);
            outerPane.add(optionsPane, BorderLayout.EAST);
    
             
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
         
        private void buildButtons()
        {
          for(int i=0;i<ROWS;i++)
           {
             for(int j=0;j<COLS;j++)
               {
                tiles[i][j] = new JButton();
    				tiles[i][j].addActionListener(handler);
                tiles[i][j].setSize(400,400);
                gridPane.add(tiles[i][j]);
             }
          }
        }
    	 ReportClick handler = new ReportClick();
    
    	class ReportClick implements ActionListener
       {
             public void actionPerformed(ActionEvent event)
             {
                /*JButton btn = (JButton) event.getSource();
                String s = btn.getText();
                status.setText(s);*/	
             }
          }     
       public static void main(String[] args)
        {
           //make instance of frame object & display it
           TryStuff2 t = new TryStuff2("Place a title for the frame here");
           t.pack();
           t.setVisible(true);
        }
    }
    "The secret to getting what you want is to reject everything that you don't want." -Wolbers

Similar Threads

  1. Stacking JPanels
    By verd in forum AWT / Swing
    Replies: 4
    Last Post: 07-26-2012, 08:01 PM
  2. JPanels ?
    By santa in forum New To Java
    Replies: 5
    Last Post: 02-25-2012, 07:10 PM
  3. Replies: 2
    Last Post: 04-26-2011, 02:50 PM
  4. Problems regarding JPanels in JPanels
    By ColtonPhillips in forum AWT / Swing
    Replies: 2
    Last Post: 07-19-2010, 08:33 PM
  5. HELP with jPanels
    By maverik_vz in forum AWT / Swing
    Replies: 1
    Last Post: 03-12-2009, 11:46 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •