Solved

Add components and ActionListener from one class to another

Posted on 2006-11-27
9
257 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
servlet example issue 6 46
tomcat startup error 5 102
SequenceInputStream example 3 19
Need help aligning JRadioButton that put in a box using GridBagLayout 2 18
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

860 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