Solved

Add components and ActionListener from one class to another

Posted on 2006-11-27
9
234 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
  • 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 125 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
 
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

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…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

708 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now