Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Add components and ActionListener from one class to another

Posted on 2006-11-27
9
Medium Priority
?
278 Views
Last Modified: 2010-03-31
Hi
Newbie to Java. Had a couple of confusing lectures at college so lost. What I'm trying to do is add a JPanel with JButton created in one class to my main class and also have the JButton retain it's ActionListener. Code examples/corrections appreciated. My code so far:

//Start Main
import java.awt.*;
import javax.swing.*;

public class MainOne extends JFrame {
      private Container container;
      private JPanel holdPanel;
            
      public MainOne() {  
            super("Main One");
            
            container = getContentPane();
            container.setLayout(new FlowLayout(FlowLayout.CENTER));
            
            holdPanel = new JPanel();
            container.add(holdPanel);
            holdPanel.add(secondOne.sparePanel);
            
            setSize(450, 400);
            setVisible(true);
      }
      
      
      public static void main(String args[]) {
            MainOne mOne = new MainOne();
            mOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }      
}
//End Main

//Start second
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class secondOne extends JFrame {
      public static JPanel sparePanel = new JPanel();
      public static JButton spareBtn[] = new JButton[5];
      public ActionListener sListener = new spareListener();
            
      public secondOne() {
            
            sListener = new spareListener();
            
            sparePanel.setLayout(new GridLayout(5,1,0,0));
            sparePanel.setBackground(Color.red);
            
            for (int i = spareBtn.length -1; i >= 0; i--) {
                  if (i > 0) {
                        spareBtn[i] = new JButton("Btn" + i);
                        spareBtn[i].addActionListener(sListener);
                        sparePanel.add(spareBtn[i]);
                        }
                  }            
      }
      
      public static class spareListener implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                  for (int x = 0; x < spareBtn.length; x++)
                        if (event.getSource() == spareBtn[x])
                              spareBtn[x].setText("HEEELLLPPPP ME");
            }        
      }
      
      
}
//End second

0
Comment
Question by:xpher
[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
  • 4
  • 3
  • 2
9 Comments
 
LVL 24

Expert Comment

by:sciuriware
ID: 18017746
When you add a button or other component to any container, its actionlistener
doesn't have to be changed.
What you can do if you must is to add another actionlistener to have the action on 2 places.

;JOOP!
0
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
ID: 18017757
> holdPanel.add(secondOne.sparePanel);

You are doing it correctly. The only thing you forgot to do is to actually construct the panel the way you need it, eg, to set the layout or the background. I see that you are doing all these thigns inside the constructor but you never actually call the constructor (since the panel in the second class is static) and therefore you never create the panel the way you need it. The solution is simple, create a secondOne instance like

secondOne secondPanel = new secondOne();

and then use this instance when you are adding the panel

holdPanel.add(secondPanel .sparePanel);
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 18017760
But to simplify your program:

Change
             public class MainOne extends JFrame {
to
             public class MainOne extends JFrame implements ActionListener {
then move the entire method
         public void actionPerformed(ActionEvent event) {
               for (int x = 0; x < spareBtn.length; x++)
                    if (event.getSource() == spareBtn[x])
                         spareBtn[x].setText("HEEELLLPPPP ME");
          }        
 to the end of 'MainOne'

That makes it easier to act from 'actionPerformed()' upon data in the main program.
E.g.: if you want to disable a button to prevent double use, you need to access the button field from there.

So discard class spareListener
;JOOP
0
Industry Leaders: 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!

 
LVL 35

Expert Comment

by:girionis
ID: 18017761
Sorry for the typo, this

holdPanel.add(secondPanel .sparePanel);

should be

holdPanel.add(secondPanel.sparePanel);

(without the space after the secondPanel).
0
 
LVL 1

Author Comment

by:xpher
ID: 18019881
Thanks girionis that helps. Only problem is if I convert to applet (part of assignment) every time I refresh the page it adds an extra panel of buttons. (i.e refresh once 2 visible panels refresh twice get 3 and so on. I know not part of original question so should I re-ask?
0
 
LVL 35

Expert Comment

by:girionis
ID: 18025997
> every time I refresh the page it adds an extra panel of buttons.

You probably forgot to call repaint in your applet in order to repaint the component. Try it and tell us if this works.
0
 
LVL 1

Author Comment

by:xpher
ID: 18031957
Thanks but it didn't. Have no problems if everything is constructed in main class so is it a problem just because created in another class.
0
 
LVL 1

Author Comment

by:xpher
ID: 18032188
Sorted it. In the second one

public class secondOne extends JFrame {
     public static JPanel sparePanel;// = new JPanel(); <<<changed this
     public static JButton spareBtn[] = new JButton[5];
     public ActionListener sListener = new spareListener();
         
     public secondOne() {
         
          sListener = new spareListener();
          sparePanel = new JPanel();  <<<<<<<<<<<<<<put it here
          sparePanel.setLayout(new GridLayout(5,1,0,0));
          sparePanel.setBackground(Color.red);


That works OK. MAny thanks for your assistance
Regards
Chris
         
0
 
LVL 35

Expert Comment

by:girionis
ID: 18034947
:)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

636 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