?
Solved

How Do I Compare Components?

Posted on 2003-03-01
30
Medium Priority
?
229 Views
Last Modified: 2010-08-05
When I call <JPanel>.getComponents() it returns an array of Components, correct?

After that, how do I compare those Components types to find out what I want?  I have:

          Component[] items;

          items = panel.getComponents();

          for(int ii; ii < items.length; ii++)
          {
             if(items[ii] == JButton)
                 items[ii].setEnabled(false);
          }

and I get Cannot Resolve Symbol on the JButton.  I have imported javax.swing.*

Basically, I want to disable all the buttons on that JPanel.
0
Comment
Question by:havyn
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 15
  • 8
  • 4
  • +3
30 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 80 total points
ID: 8048400
Change


            if(items[ii] == JButton)

to


            if(items[ii] instanceof JButton) {

               ((JButton)items[ii]).setEnabled(false);
            }

0
 

Author Comment

by:havyn
ID: 8048456
compiles now, but still isn't diabling anything...could be passing this wrong.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8048469
Perhaps you'd better post the code?
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 

Author Comment

by:havyn
ID: 8048471
when i pass "this" is passes the entire current class instance, right?
0
 

Author Comment

by:havyn
ID: 8048473
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//import javax.swing.plaf.metal.MetalLookAndFeel;

// ButtonPanel was created by Brendan B. Hannemann
// 12/10/02
// Version 1.0

/**
 * This class is in charge of actually creating the elements that go into the
 * GUI, such as buttons, panels, etc.
 *
 * @okButton..threeButton : all of the JButtons are just text labeled and have
 *                          the ButtonListener class attached to them for when
 *                          someone clicks them.
 *
 * @stor : a Storage object to hold the commands to be sent to ButtonListener,
 *         Storage, and eventually Translator.
 *
 * @btnListener : a ButtonListener event to attach to all the buttons.
 */
public class ButtonPanel extends JPanel
{
     private JButton okButton, cancelButton, sendButton, forwardButton,
                     leftButton, backwardButton, rightButton, sevenButton,
                     eightButton, nineButton, fourButton, fiveButton, sixButton,
                     oneButton, twoButton, threeButton, clearButton,
                     quitButton, ifButton, thenButton, fSense, bSense;

     Storage stor = new Storage();
     ButtonListener btnListener = new ButtonListener(stor, this);

/**
 * Actually creates everything.  Look here to change individual GUI elements.
 *
 * @xPanel... : these are all JPanels to stick the JButtons on, or in some cases
 *              to stick other JPanels onto in order to create a more complex
 *              layout.
 */
     public ButtonPanel()
     {
          setLayout(new BorderLayout());

          //MetalLookAndFeel.setCurrentTheme(new MacMetricsTheme());

          okButton = new JButton("Ok");
          okButton.addActionListener(btnListener);
          okButton.setActionCommand("OK");
          cancelButton = new JButton("Cancel");
          cancelButton.addActionListener(btnListener);
          cancelButton.setActionCommand("CANCEL");
          sendButton = new JButton("Send");
          sendButton.addActionListener(btnListener);
          sendButton.setActionCommand("SEND");
          clearButton = new JButton("Clear");
          clearButton.addActionListener(btnListener);
          clearButton.setActionCommand("CLEAR");
          quitButton = new JButton("Quit");
          quitButton.addActionListener(btnListener);
          quitButton.setActionCommand("QUIT");

          forwardButton = new JButton("Forward");
          forwardButton.addActionListener(btnListener);
          forwardButton.setActionCommand("FORWARD");
          leftButton = new JButton("Left");
          leftButton.addActionListener(btnListener);
          leftButton.setActionCommand("LEFT");
          backwardButton = new JButton("Backward");
          backwardButton.addActionListener(btnListener);
          backwardButton.setActionCommand("BACKWARD");
          rightButton = new JButton("Right");
          rightButton.addActionListener(btnListener);
          rightButton.setActionCommand("RIGHT");

          ifButton = new JButton("If");
          ifButton.addActionListener(btnListener);
          ifButton.setActionCommand("IF");
          thenButton = new JButton("Then");
          thenButton.addActionListener(btnListener);
          thenButton.setActionCommand("THEN");
          fSense = new JButton("s1");
          fSense.addActionListener(btnListener);
          fSense.setActionCommand("FRONT");
          bSense = new JButton("s2");
          bSense.addActionListener(btnListener);
          bSense.setActionCommand("BACK");

          sevenButton = new JButton("7");
          sevenButton.addActionListener(btnListener);
          sevenButton.setActionCommand("7");
          eightButton = new JButton("8");
          eightButton.addActionListener(btnListener);
          eightButton.setActionCommand("8");
          nineButton = new JButton("9");
          nineButton.addActionListener(btnListener);
          nineButton.setActionCommand("9");
          fourButton = new JButton("4");
          fourButton.addActionListener(btnListener);
          fourButton.setActionCommand("4");
          fiveButton = new JButton("5");
          fiveButton.addActionListener(btnListener);
          fiveButton.setActionCommand("5");
          sixButton = new JButton("6");
          sixButton.addActionListener(btnListener);
          sixButton.setActionCommand("6");
          oneButton = new JButton("1");
          oneButton.addActionListener(btnListener);
          oneButton.setActionCommand("1");
          twoButton = new JButton("2");
          twoButton.addActionListener(btnListener);
          twoButton.setActionCommand("2");
          threeButton = new JButton("3");
          threeButton.addActionListener(btnListener);
          threeButton.setActionCommand("3");

          JPanel commPanel = new JPanel();
          commPanel.setLayout(new GridBagLayout());
          commPanel.setBackground(Color.white);

          JPanel dirPanel = new JPanel();
          dirPanel.setLayout(new BorderLayout());
          dirPanel.setBackground(Color.white);

          JPanel topPanel = new JPanel();
          topPanel.setLayout(new BorderLayout());
          topPanel.setBackground(Color.white);

          JPanel calcPanel = new JPanel();
          calcPanel.setLayout(new GridLayout(3, 3, 0, 0));
          calcPanel.setBackground(Color.white);

          JPanel calc2Panel = new JPanel();
          calc2Panel.setLayout(new FlowLayout());
          calc2Panel.setBackground(Color.white);

          JPanel logicPanel = new JPanel();
          logicPanel.setLayout(new GridBagLayout());
          logicPanel.setBackground(Color.white);

          commPanel.add(okButton);
          commPanel.add(clearButton);
          commPanel.add(cancelButton);
          commPanel.add(sendButton);
          commPanel.add(quitButton);
          logicPanel.add(ifButton);
          logicPanel.add(thenButton);
          logicPanel.add(fSense);
          logicPanel.add(bSense);
          dirPanel.add(forwardButton, BorderLayout.NORTH);
          dirPanel.add(leftButton, BorderLayout.WEST);
          dirPanel.add(backwardButton, BorderLayout.SOUTH);
          dirPanel.add(rightButton, BorderLayout.EAST);
          topPanel.add(dirPanel, BorderLayout.WEST);
          topPanel.add(calc2Panel, BorderLayout.EAST);
          topPanel.add(logicPanel, BorderLayout.SOUTH);
          calcPanel.add(sevenButton);
          calcPanel.add(eightButton);
          calcPanel.add(nineButton);
          calcPanel.add(fourButton);
          calcPanel.add(fiveButton);
          calcPanel.add(sixButton);
          calcPanel.add(oneButton);
          calcPanel.add(twoButton);
          calcPanel.add(threeButton);
          calc2Panel.add(calcPanel);

          add(commPanel, BorderLayout.SOUTH);
          add(topPanel, BorderLayout.NORTH);

          setBackground(Color.white);
     }
}
0
 

Author Comment

by:havyn
ID: 8048475
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

// ButtonListener was created by Brendan B. Hannemann
// 12/10/02
// Version 1.0

/**
 * This class is an ActionListener that listens for button actions and performs
 * the appropriate command based on the button that is pressed.
 */
public class ButtonListener implements ActionListener
{
     private Storage sCom;
     private String tempValue = new String();
     private String tempCommand = new String();
     private JPanel panel;

/**
 * Constructor for the listener.
 *
 * @stor : the incoming Storage object.
 */
     public ButtonListener(Storage stor, JPanel jP)
     {
          sCom = stor;
          panel = jP;
     }

/**
 * Called when the button is pressed.
 *
 * NOTE: if the OK button is pressed, this will call the Storage and Translator
 *       classes and then exit the GUI completely.
 *
 * @ae : the ActionEvent performed, used with the getActionCommand() method to
 *       figure out which button was pressed.
 */
     public void actionPerformed(ActionEvent ae)
     {
          String command = ae.getActionCommand();
          Component[] items;

          items = panel.getComponents();

          if (command == "FORWARD")      {    tempCommand = "forward";
                                              for(int ii = 0; ii < items.length; ii++)
                                              {
                                                if(items[ii] instanceof JButton)
                                                    ((JButton)items[ii]).setEnabled(false);
                                              }
                                         }
          else if (command == "BACKWARD")     tempCommand = "backward";
          else if (command == "RIGHT")        tempCommand = "right";
          else if (command == "LEFT")         tempCommand = "left";
          else if (command == "IF")           tempCommand = "if";
          else if (command == "THEN")         tempCommand = "then";
          else if (command == "FRONT")        tempValue = "0";
          else if (command == "BACK")         tempValue = "1";
          else if (command == "1")            tempValue += "1";
          else if (command == "2")            tempValue += "2";
          else if (command == "3")            tempValue += "3";
          else if (command == "4")            tempValue += "4";
          else if (command == "5")            tempValue += "5";
          else if (command == "6")            tempValue += "6";
          else if (command == "7")            tempValue += "7";
          else if (command == "8")            tempValue += "8";
          else if (command == "9")            tempValue += "9";
          else if (command == "CLEAR")  {     tempCommand = "";
                                              tempValue = "0";
                                        }
          else if (command == "CANCEL") {     sCom.deleteCommand();
                                              updateList();
                                        }
          else if (command == "OK")     {     sCom.saveCommand(tempCommand);
                                              sCom.saveValue(getValue());
                                              tempValue = "";
                                              updateList();
                                        }
          else if (command == "SEND")   {     String[] commands =
                                                     sCom.getCommands();
                                              int[] values = sCom.getValues();
                                              Translator t = new Translator();
                                              t.readArray(sCom.getCommands(),
                                              sCom.getValues());
                                        }
          else if (command == "QUIT")         System.exit(0);
     }

     private int getValue()
     {
        int retVal = 0;
        Integer tempVal = new Integer(tempValue);

        retVal = tempVal.intValue();

        return retVal;
     }

     private void updateList()
     {
        Buttons.update(sCom);
     }
}
0
 

Author Comment

by:havyn
ID: 8048479
I have a ButtonPanel that adds ButtonListeners to each JButton.  I want to disable certain buttons from within the ButtonListener.  I thought I could do this by passing 'this' to the ButtonListener..
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8048486
if (command == "FORWARD")      

should be

 if (command.equal("FORWARD"))

(yours compares object references). Or better still [safer]

 if (command.equalsIgnoreCase("FORWARD"))
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8048487
Sorry!

if (command.equal("FORWARD"))

should have been

if (command.equals("FORWARD"))
0
 

Author Comment

by:havyn
ID: 8048489
well the buttons do work already...but i will try that out.
0
 

Author Comment

by:havyn
ID: 8048498
yeah that doesn't make a difference for my application.
0
 

Author Comment

by:havyn
ID: 8048508
the application works (and buttons correctly send commands), but i want to be able to selectively disable buttons to prevent my arrays from getting out of sync.  i have two parallel arraylists, one for commands and one for values.  i am trying to make it so that if you press a command button (forward, backward, etc.) that it disables the other command buttons until you select a value for that command.  this is to prevent there from being like 5 commands and only 1 value.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8048514
When

if (command == "FORWARD")      

works, you can regard that as a lucky accident ;-)
0
 

Author Comment

by:havyn
ID: 8048519
well i have these buttons with the setActionCommand set to those particular strings, so that's why it does...  :-)
0
 

Author Comment

by:havyn
ID: 8048522
just for fun i went ahead and changed them all to your .equals suggestion anyway.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8048532
While i'm thinking about your requirements, change this

String command = ae.getActionCommand();


to this and see what happens

String command = new String(ae.getActionCommand());
0
 

Author Comment

by:havyn
ID: 8048540
if you want, i can send you the actual files so you can compile them and maybe see what i'm talking about.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8048548
I'm a little busy right now, but where are you now in the proceedings?
0
 

Author Comment

by:havyn
ID: 8048568
what do you mean?  still nothing is disabled...but everything compiles.  look at the first class i posted, specifically at the line:

 ButtonListener btnListener = new ButtonListener(stor, this);

will sending 'this' at this point still send everything, even though stuff isn't created yet at that point?  perhaps when i call getComponents on the JPanel there is nothing to get!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8048633
Have i got this right? Do you want to disable all buttons apart from the one that gets the command?
0
 
LVL 1

Accepted Solution

by:
shji1 earned 240 total points
ID: 8048826
If you are having trouble finding those JButtons, you can use the following recursive method in order to disable all of them (I hope)...

private static void disableAllButtonsRec(JComponent component) {
   if (component instanceof JButton) {
       ((JButton)component).setEnabled(false);
   }
   Component comp[] = component.getComponents();
   if (comp.length == 0) {
        return;
   }
   for (int i = 0; i < comp.length; i++) {
       if (comp[i] instanceof JComponent) {
           disableAllButtonsRec((JComponent) comp[i]);
       }
   }
}

Call this method with the panel that is holding the buttons as a parameter.
--
0
 
LVL 92

Assisted Solution

by:objects
objects earned 80 total points
ID: 8049015
getComponents() only returns the components that have been added to that container, in your case the only compoents added are commPanel and topPanel. None of your buttons are added to your top level panel so they will not get returned.

0
 

Author Comment

by:havyn
ID: 8049987
hmm...so the recursive option is the way to go?

@CEHJ: I want to disable all of the directional buttons once one is pressed, cause i don't want two directions being chosen.  multiple values can be entered, so those shouldn't disable anything.
0
 
LVL 92

Expert Comment

by:objects
ID: 8050103
> so the recursive option is the way to go?

If you want disable all buttons in the component hierarchy then yes.
0
 

Author Comment

by:havyn
ID: 8050548
i got word that the best way to do this would be to separate all of my panels with buttons into separate classes with separate listeners...that way i could access them easily.  would this make sense?
0
 
LVL 92

Expert Comment

by:objects
ID: 8050581
> would this make sense?

yes thats another way of doing it.
that would give you finer control over which button were disabled.
0
 

Author Comment

by:havyn
ID: 8050601
how do i give points to multiple people?
0
 
LVL 92

Expert Comment

by:objects
ID: 8050677
Ask a question at CS to do a point split:
http://www.experts-exchange.com/Community_Support/
0
 

Expert Comment

by:DigitalXtreme
ID: 8053081
Points split requested. I have refunded your points to 100. Please select an expert's comment as an answer and post 2 questions in this Topic Area titled "points for <expertname>" for the other experts. Post the link to those questions back to this question so the experts know where to collect their points. Thank You :)

DigitalXtreme
CS Moderator
0
 

Expert Comment

by:CleanupPing
ID: 9058989
havyn:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month10 days, 8 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question