meTopia
meTopia

Reputation: 21

Check if JButtons are within a particular JPanel

I am creating a GUI application using Java. There are different sections in the main frame, each having a particular functionality. The header panel contains the buttons Submit, Undo, Shuffle, Help and Quit. Here is the sample code:

JPanel header = new JPanel();  

JButton submit = new JButton("Submit");  
header.add(submit);  

JButton undo= new JButton("Undo");  
header.add(undo); 

JButton shuffle= new JButton("Shuffle");  
header.add(shuffle);

JButton help= new JButton("Help");  
header.add(help); 

JButton quit = new JButton("Quit");  
header.add(quit); 

Further down my code, I need to check that the button clicked is not in the header panel (there are buttons in other panels too).

public void actionPerformed(ActionEvent e)
   {
      String clicked = e.getActionCommand();

      if(!clicked.equals("Submit") && !clicked.equals("Undo") && !clicked.equals("Help")&& !clicked.equals("Quit") && !clicked.equals("Shuffle")){  


      //some code here

Is there any alternate neater way to check that the button clicked is not in the header panel? I will need to do something similar in another panel which contains more buttons. Using IF statements to check for each button is inefficient and untidy, I believe.

Upvotes: 2

Views: 310

Answers (2)

Micic
Micic

Reputation: 1

You can use addActionListener for every button separately.

Upvotes: 0

M B
M B

Reputation: 333

Honestly, I'd just implement actions for every button. It may require more code but it's a better solution. But if you insist to go this way you can try this

    public void actionPerformed(ActionEvent e) {
        if (!Arrays.asList(PANEL.getComponents()).stream().filter(b -> b instanceof JButton)
            .map(b -> (JButton) b).filter(b -> 
                 b.getText().equals(e.getActionCommand())).findFirst().isPresent()) {
             // execute code if button is not a child of PANEL
        }
    }

Upvotes: 1

Related Questions