• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

How Do I Compare Components?

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
havyn
Asked:
havyn
  • 15
  • 8
  • 4
  • +3
3 Solutions
 
CEHJCommented:
Change


            if(items[ii] == JButton)

to


            if(items[ii] instanceof JButton) {

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

0
 
havynAuthor Commented:
compiles now, but still isn't diabling anything...could be passing this wrong.
0
 
CEHJCommented:
Perhaps you'd better post the code?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
havynAuthor Commented:
when i pass "this" is passes the entire current class instance, right?
0
 
havynAuthor Commented:
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
 
havynAuthor Commented:
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
 
havynAuthor Commented:
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
 
CEHJCommented:
if (command == "FORWARD")      

should be

 if (command.equal("FORWARD"))

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

 if (command.equalsIgnoreCase("FORWARD"))
0
 
CEHJCommented:
Sorry!

if (command.equal("FORWARD"))

should have been

if (command.equals("FORWARD"))
0
 
havynAuthor Commented:
well the buttons do work already...but i will try that out.
0
 
havynAuthor Commented:
yeah that doesn't make a difference for my application.
0
 
havynAuthor Commented:
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
 
CEHJCommented:
When

if (command == "FORWARD")      

works, you can regard that as a lucky accident ;-)
0
 
havynAuthor Commented:
well i have these buttons with the setActionCommand set to those particular strings, so that's why it does...  :-)
0
 
havynAuthor Commented:
just for fun i went ahead and changed them all to your .equals suggestion anyway.
0
 
CEHJCommented:
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
 
havynAuthor Commented:
if you want, i can send you the actual files so you can compile them and maybe see what i'm talking about.
0
 
CEHJCommented:
I'm a little busy right now, but where are you now in the proceedings?
0
 
havynAuthor Commented:
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
 
CEHJCommented:
Have i got this right? Do you want to disable all buttons apart from the one that gets the command?
0
 
shji1Commented:
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
 
objectsCommented:
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
 
havynAuthor Commented:
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
 
objectsCommented:
> so the recursive option is the way to go?

If you want disable all buttons in the component hierarchy then yes.
0
 
havynAuthor Commented:
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
 
objectsCommented:
> would this make sense?

yes thats another way of doing it.
that would give you finer control over which button were disabled.
0
 
havynAuthor Commented:
how do i give points to multiple people?
0
 
objectsCommented:
Ask a question at CS to do a point split:
http://www.experts-exchange.com/Community_Support/
0
 
DigitalXtremeCommented:
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
 
CleanupPingCommented:
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

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 15
  • 8
  • 4
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now