Results 1 to 6 of 6
  1. #1
    hhan is offline Member
    Join Date
    Aug 2011
    Posts
    2
    Rep Power
    0

    Default Looping in JPanel

    I have a jpanel in a jpanel which is use to display a list of survey.
    I named the first panel columPanel and the second rowPanel.
    And I am trying to loop through each columnPanel to get the components in rowPanel. (eg;i wanna check if the jRadioButtons are selected) but apparently it is only checking for the last component.
    Can someone help me?

    Java Code:
    				Component c = null;
    				    Component[] components = columnPanel.getComponents();
    				    if(components != null)
    				    {
    				        int numComponents = components.length;
    				        for(int i = 0; i < numComponents; i++)
    				        {
    				            c = components[i];
    				            if(c != null)
    				            {
    				                if(c instanceof JPanel)
    				                {
    			 for(int x=1; x<5; x++){
    				                	JRadioButton jr = (JRadioButton) rowPanel.getComponent(x);
    				                	if(c.equals(components[i]))
    				                		if(jr.isSelected()==true){
    				                			System.out.println("ok");
    				                		}
    				                }
    				            }
    				        }
    }
    				                }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Can you first tell us what problems you're having? Also, it would help to post well-formatted code without random indentation. The easier it is to read your code the more folks who will want to read it and help you.

    For instance, which is easier to read, your code post or this:
    Java Code:
          Component c = null;
          Component[] components = columnPanel.getComponents();
          if (components != null) {
             int numComponents = components.length;
             for (int i = 0; i < numComponents; i++) {
                c = components[i];
                if (c != null) {
                   if (c instanceof JPanel) {
                      for (int x = 1; x < 5; x++) {
                         JRadioButton jr = (JRadioButton) rowPanel.getComponent(x);
                         if (c.equals(components[i]))
                            if (jr.isSelected() == true) {
                               System.out.println("ok");
                            }
                      }
                   }
                }
             }
          }
    Also, why are you looping through components? Why not have an array or ArrayList of JRadioButtons (or ButtonGroup objects if you have several collections of JRadioButtons tied together by several ButtonGroups).
    Last edited by Fubarable; 08-06-2011 at 03:21 PM.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    For instance, if you had an array of Strings for your radio button texts and a similarly lengthed array of JRadioButtons:

    Java Code:
       public static final String[] RADIO_NAMES  = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
       
       private JRadioButton[] radios = new JRadioButton[RADIO_NAMES.length];
    Then you could easily create your radio buttons in a for loop:

    Java Code:
          for (int i = 0; i < radios.length; i++) {
             radios[i] = new JRadioButton(RADIO_NAMES[i]);
             radios[i].setActionCommand(RADIO_NAMES[i]);
             rowPanel.add(radios[i]);
          }
    And when you need to check their status, could easily do this in a for loop (or here, a for-each loop):

    Java Code:
          for (JRadioButton radio : radios) {
             if (radio.isSelected()) {
                System.out.println("Radio " + radio.getActionCommand() + " is selected");
             }
          }
    And you won't have to worry about mucking through components in code that will crash horribly if you change the number of components or radio buttons.

  4. #4
    hhan is offline Member
    Join Date
    Aug 2011
    Posts
    2
    Rep Power
    0

    Default

    Sorry for the indentation.

    I am able to loop through the jpanel to get what i want which is to check if the jRadiobutton are selected and if it is, i will get the values i need.

    But however, the problem is it is only checking for the last component and only printing the values of the last componenet. But what i actually need is for it to check through every single component in the jPanel


    .


    Java Code:
    [INDENT]
    		public void updateSurveyCount(){
    		int questionId = 0;
    		int choiceValue = 0;
    		int choiceId = 0;
    		JRadioButton jr1 = (JRadioButton) rowPanel.getComponent(1);
    		JRadioButton jr2 = (JRadioButton) rowPanel.getComponent(2);
    		JRadioButton jr3 = (JRadioButton) rowPanel.getComponent(3);
    		JRadioButton jr4 = (JRadioButton) rowPanel.getComponent(4);		
    		
    		JLabel qId = (JLabel) rowPanel.getComponent(5);
    		JLabel cId1 = (JLabel) rowPanel.getComponent(6);
    		JLabel cId2 = (JLabel) rowPanel.getComponent(7);
    		JLabel cId3 = (JLabel) rowPanel.getComponent(8);
    		JLabel cId4 = (JLabel) rowPanel.getComponent(9);
    		JLabel cV1 = (JLabel) rowPanel.getComponent(10);
    		JLabel cV2 = (JLabel) rowPanel.getComponent(11);
    		JLabel cV3 = (JLabel) rowPanel.getComponent(12);
    		JLabel cV4 = (JLabel) rowPanel.getComponent(13);
    	    
    		 if(jr1.isSelected()==false && jr2.isSelected()==false && jr3.isSelected()==false && jr4.isSelected()==false){					
    				JOptionPane.showMessageDialog(getJFrame(), "Please attempt all question");	
    		 }else	
    	
    			 for(int x=1; x<5; x++){
    					JRadioButton jr =  (JRadioButton) rowPanel.getComponent(x);	
    			
    			if(jr.isSelected()){
     			questionId = Integer.parseInt(qId.getText());
    				if(getjRadioButton1().isSelected()){
    					choiceId = Integer.parseInt(cId1.getText());
    					choiceValue = Integer.parseInt(cV1.getText());
    				}
    				else if(getjRadioButton2().isSelected()){
    					choiceId = Integer.parseInt(cId2.getText());
    					choiceValue = Integer.parseInt(cV2.getText());
    				}
    				else if (getjRadioButton3().isSelected()){
    					choiceId = Integer.parseInt(cId3.getText());
    					choiceValue = Integer.parseInt(cV3.getText());
    				}else{
    				choiceId = Integer.parseInt(cId4.getText());
    				choiceValue = Integer.parseInt(cV4.getText());
    					}
    				} 
    			}
      			System.out.println("QuestionId: " + questionId);
    			System.out.println("ChoiceId: " + choiceId);
    			System.out.println("ChoiceValue: " + choiceValue);	
    
    		}[/INDENT]

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I'm not sure how to answer your question given the information presented since there's a whole lot of code that we can't see that is likely pertinent to the question.

    But regardless, I'm still sticking with my answer in my second post to this thread. To be perfectly honest, the code you've posted above is very fragile and will be hard to update, debug and maintain. I still think that you shouldn't go mucking through your JPanels but rather use collections of references to more easily and reliably find and manipulate the state of your GUI. Java is a powerful OOP language and you should use it to its full advantage.

    If you need more help on your specific problem, I suggest though that you create a small compilable runnable program that demonstrates the issue, an SSCCE. We do not want to see code fragments nor do we want to see your whole program but rather a distillation of just the problem in code that we can run, modify and correct.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    For instance, say I wanted the user to select a day of the week expanding on the code example I've provided above:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class FooSwing extends JPanel {
       public static final String[] RADIO_NAMES = {"Monday", "Tuesday",
          "Wednesday", "Thursday", "Friday"};
    
       private JPanel columnPanel = new JPanel();
       private JPanel rowPanel = new JPanel();
       private JRadioButton[] radios = new JRadioButton[RADIO_NAMES.length];
       private ButtonGroup buttonGrp = new ButtonGroup();
    
       public FooSwing() {
          rowPanel.setLayout(new GridLayout(1, 0));
          for (int i = 0; i < radios.length; i++) {
             radios[i] = new JRadioButton(RADIO_NAMES[i]);
             radios[i].setActionCommand(RADIO_NAMES[i]);
             rowPanel.add(radios[i]);
             buttonGrp.add(radios[i]);
          }
    
          JButton checkRadiosBtn = new JButton(new AbstractAction("Check Radios") {
             public void actionPerformed(ActionEvent arg0) {
                checkRadiosAction();
             }
          });
          JPanel buttonPanel = new JPanel();
          buttonPanel.add(checkRadiosBtn);
    
          rowPanel.setBorder(BorderFactory.createTitledBorder("Select a day of the week"));
          columnPanel.setBorder(BorderFactory.createTitledBorder("Column Panel"));
    
          columnPanel.setLayout(new BoxLayout(columnPanel, BoxLayout.PAGE_AXIS));
          columnPanel.add(rowPanel);
          columnPanel.add(buttonPanel);
          add(columnPanel);
       }
    
       private void checkRadiosAction() {
          ButtonModel btnModel = buttonGrp.getSelection();
          if (btnModel == null) {
             JOptionPane.showMessageDialog(this, "Please first select a day of the week",
                      "Button Not Selected", JOptionPane.ERROR_MESSAGE);
          } else {
             System.out.println("Radio " + btnModel.getActionCommand() + " has been selected");
          }
       }
       
       private static void createAndShowUI() {
          JFrame frame = new JFrame("Radio Button Example");
          frame.getContentPane().add(new FooSwing());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

    Now this displays 5 JRadioButtons going from Monday to Friday, allows the user to select only one of the day JRadioButtons, and shows an error if the user presses the JButton before selecting a JRadioButton.

    Now if later I want to add two more JRadioButtons for Saturday and Sunday, the only changes I need to make in my code is to change this:

    Java Code:
       public static final String[] RADIO_NAMES = {"Monday", "Tuesday",
          "Wednesday", "Thursday", "Friday"};
    To this:

    Java Code:
       public static final String[] RADIO_NAMES = {"Monday", "Tuesday",
          "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    That's it. Can you see how these can ease the development of your program?

Similar Threads

  1. Adding a jpanel to a customized Jpanel Class
    By trishtren in forum AWT / Swing
    Replies: 7
    Last Post: 04-05-2011, 06:52 PM
  2. Placing a new JPanel over a paint overriden JPanel
    By Tanshaydar in forum AWT / Swing
    Replies: 4
    Last Post: 12-08-2010, 06:00 PM
  3. Looping
    By Dean29126 in forum New To Java
    Replies: 3
    Last Post: 09-08-2010, 02:01 PM
  4. Help with While and For Looping
    By gmoney8316 in forum New To Java
    Replies: 2
    Last Post: 03-03-2010, 10:54 PM
  5. Replies: 3
    Last Post: 04-20-2009, 11:31 PM

Posting Permissions

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