Solved

Add components and ActionListener from one class to another

Posted on 2006-11-27
9
244 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Android studio getdrawable(int) is deprecated 4 43
micro services vs rest web services 16 86
Java DateChooser? 3 29
Java Options in Zimbra Server 2 46
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
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 basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

920 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

16 Experts available now in Live!

Get 1:1 Help Now