Results 1 to 18 of 18
  1. #1
    pjr5043 is offline Member
    Join Date
    Sep 2008
    Posts
    16
    Rep Power
    0

    Default how to listen for buttons between jpanels?

    i need to listen to a button in jpanel1, then have an action displayed in jpanel2.
    how do i do this?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    There are many ways to do this, but much depends on the details. Is the JButton in a different class form the 2nd JPanel? You could have a 3rd class, a "Controller" class hold the actionlistener code and facilitate communication between classes. You could have the class with the JButton have its own addActionListener method and then attach any added ActionListeners to the JButton,... again lots of ways. perhaps it would be best if you posted a small compilable program that shows us your problem. The 2 keys here are *small* and *compilable*. Good luck.

  3. #3
    pjr5043 is offline Member
    Join Date
    Sep 2008
    Posts
    16
    Rep Power
    0

    Default

    i probably cna't compile a small prog .. but basically what i have is two jpanels

    Java Code:
    on jpanel1 i have (shrttext)
    
    student=new student (chris hansen)
    
    JButton = jb1 (getName())
    jb1.addActionListener(this)
    add (jb1);
    
    then for jpanel2, the panel that i want to change i have:
    
    JButton = jb6("....")
    add (jb6)
    
          Object obj = event.getSource();
          if (obj == jb1){
             p6.setText(jb1.getText());
    but that wont work .. i'm not sure what i need to do to get them to both communicate w/ each other

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Again, are these components in different classes?

  5. #5
    pjr5043 is offline Member
    Join Date
    Sep 2008
    Posts
    16
    Rep Power
    0

    Default

    yes .. one is in jpanel1 the other is in jpanel2

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    It's hard to tell. According to naming convention, jpanel1 should be a variable or field not a class since class names should all begin with a capital letter. So you're telling me that jpanel1 is in fact a class that extends JPanel, and same for jpanel2? Again, I'm just trying to clarify things here.

    I'm assuming that you're creating these classes using NetBeans generated code? If so, I recommend that you not do that, that you learn to create Swing components from scratch because this is a classic case of a tool (NetBeans) actually inhibiting learning (your ability to understand how to use Swing). Once you are familiar with Swing coding then by all means use the NetBeans generation to speed things up, but until then, you are much better served to learn how to do it the right way. The Sun Swing tutorials can show you the way.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    For instance, here are 3 classes, 2 that subclass JPanel, one of which can send out text the other which can receive text and a controller class that hooks the two together:

    Java Code:
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    /**
     * Subclasses JPanel, receives text from another class
     * @author Pete
     */
    public class PanelCommReceiver extends JPanel
    {
      private JTextField showResultsField = new JTextField(12);
      
      public PanelCommReceiver()
      {
        showResultsField.setEditable(false);
        add(new JLabel("Results from other panel: "));
        add(showResultsField);
      }
      
      /**
       * call this to set text of textField
       * @param text
       */
      public void setText(String text)
      {
        showResultsField.setText(text);
      }
    }
    Java Code:
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    /**
     * Subclasses JPanel, can send text out via the getText() method
     * can hook into button press via addActionListener
     * @author Pete
     */
    public class PanelCommSender extends JPanel
    {
      private JTextField sendingField = new JTextField(12);
      private JButton sendButton = new JButton("Send");
      
      public PanelCommSender()
      {
        add(sendingField);
        add(sendButton);
      }
      
      public void addActionListener(ActionListener al)
      {
        // attach this listener to the button
        sendButton.addActionListener(al);
      }
      
      /**
       * call this to get the text currently in the textfield
       * @return String text
       */
      public String getText()
      {
        return sendingField.getText();
      }
    }
    Java Code:
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    
    public class PanelCommControl
    {
      private static void createAndShowUI()
      {
        // create new instances of the receiving and sending panels:
        final PanelCommReceiver receivePanel = new PanelCommReceiver();
        final PanelCommSender sendPanel = new PanelCommSender();
        
        // let them communicate w/ each other
        sendPanel.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
            receivePanel.setText(sendPanel.getText());
          }
        });
        
        // place the receiving JPanel into a JFrame
        JFrame frame = new JFrame("Receiving Panel");
        frame.getContentPane().add(receivePanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(300, 300)); // make it bigger so it can be seen
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        
        // place the sending JPanel into a JDialog
        JDialog dialog = new JDialog(frame, "Sending Panel", false);
        dialog.getContentPane().add(sendPanel);
        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            // run the whole show in a thread-safe manner
            createAndShowUI();
          }
        });
      }
    }

  8. #8
    pjr5043 is offline Member
    Join Date
    Sep 2008
    Posts
    16
    Rep Power
    0

    Default

    yea both jpanel 1 and 2 extend jpanel, my professor gave me all these start files .. i'm using jcreator .. i dont know about swing or anything like that i'm just real confused as to how to communicate between the two classses

    i was thinking i would need to use something like a an extends or super()

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    i was thinking i would need to use something like a an extends or super()
    I'm not sure what you mean here, but if my examples don't help, you may wish to clarify your problem further. Best of luck regardless.

  10. #10
    serjant's Avatar
    serjant is offline Senior Member
    Join Date
    Jun 2008
    Location
    Ukraine,Zaporozhye
    Posts
    487
    Rep Power
    7

    Default

    Java Code:
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    /**
     * Subclasses JPanel, can send text out via the getText() method
     * can hook into button press via addActionListener
     * @author Pete
     */
    public class PanelCommSender extends JPanel
    {
      private JTextField sendingField = new JTextField(12);
      private JButton sendButton = new JButton("Send");
      
      public PanelCommSender()
      {
        add(sendingField);
        add(sendButton);
        sendButton.addActionListener(new ActionListener(){
              public void actionPerfomed(ActionEvent e){
                 //what should button do on 
              }
         });
      }
      
      
      
      /**
       * call this to get the text currently in the textfield
       * @return String text
       */
      public String getText()
      {
        return sendingField.getText();
      }
    }
    I would recommend to use MouseAdapter for the JButtons

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    I'm confused as to what your change to my code accomplishes and why you would use a MouseAdapter on a JButton.

  12. #12
    pjr5043 is offline Member
    Join Date
    Sep 2008
    Posts
    16
    Rep Power
    0

    Default

    alrite guys ... lemme start over. heres what i'm thinking

    I have 3 jpanels jpanel1 and jpanel 2 both are on my jpanel. i have to use an addaactionlistnener, so is there a way i can just do it on the main jppanel, and have to communicate between the other two like that?

  13. #13
    serjant's Avatar
    serjant is offline Senior Member
    Join Date
    Jun 2008
    Location
    Ukraine,Zaporozhye
    Posts
    487
    Rep Power
    7

    Default

    Oops ,i didn't notice the PanelCoomControl class,now i understood that he needed the action listener for making changes for another JPanel class.Sorry,my fault.It is 3 a.m. I think it is time to snooze

    About MouseAdapter,I use usually mouseadapter,then you can now for sure that the button was pressed.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by pjr5043 View Post
    I have 3 jpanels jpanel1 and jpanel 2 both are on my jpanel. i have to use an addaactionlistnener, so is there a way i can just do it on the main jppanel, and have to communicate between the other two like that?
    Without more information, I'm at a loss to help you. Your best bet here is to show us your code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:

    SSCCE

    Again, if the code is compilable and runnable more people will be able to help you.

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by serjant View Post
    About MouseAdapter,I use usually mouseadapter,then you can now for sure that the button was pressed.
    But what advantage does this hold over using an ActionListener for the button? Buttons were made to specifically communicate via ActionListeners.

  16. #16
    pjr5043 is offline Member
    Join Date
    Sep 2008
    Posts
    16
    Rep Power
    0

    Default

    app.java
    Java Code:
    public class  app
    {
      public static void main(String args[])
      {	
        myJFrame mjf = new myJFrame();
      }
    }

    jframe

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class myJFrame extends JFrame
    {
    	public myJFrame ()
    	{
    		super ("My First Frame");		
     	 	myJPanel mjp = new myJPanel();      	
    		getContentPane().add(mjp,"Center");
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    		setSize (640, 480);
    		setVisible(true);
    	}
    
    }

    jpanel

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class myJPanel extends JPanel 
    {
    	public myJPanel()
    	{
    		super();
    		setBackground(Color.gray);		
    		setLayout(new BorderLayout());		
    		myJPanel1 p1 = new myJPanel1();
    		add(p1,"North");
    		myJPanel2 p2 = new myJPanel2();
    		add(p2,"Center");					
    	}	    
    }
    jpanel1
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class myJPanel1 extends JPanel 
    {
    	public myJPanel1()
    	{
    		super();
    		setBackground(Color.yellow);
    		student st1 = new student("Fred","Fonseca",44);
    		// the whatsUp of this student has to shown in the other panel
    		JButton jl1 = new JButton(st1.getInfo());	
    		add(jl1);				
    	}	
    	public void actionPerformed(ActionEvent event) 			
    }
    jpanel2
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    public class myJPanel2 extends JPanel 
    {	
    JLabel p1;	
    	public myJPanel2()
    	{
    		super();
    		setBackground(Color.pink);
    		//setLayout(new GridLayout(4,1));
    		JButton j1 = new JButton("When the user clicks on the button in the UPPER panel" );
    		add(j1);		
    		JButton j2 = new JButton("Display here whatsUp from the student in UPPER Panel" );
    		add(j2);		
    		JButton j3 = new JButton("===>>>>You CANNOT create a student here <======" );
    		add(j3);
    		JButton j4 = new JButton("It has to be the student from the UPPER Panel" );
    		add(j4);
    				
    	}
    }
    student
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    public class student 
    {
    		String firstName;
    		String lastName;
    		int age;
    		public student(String a, String b, int x)
    		{	
    			super();
    			firstName = a;
    			lastName = b;
    			age = x;	
    		}
    		String getInfo()
    		{
    			return "NAME = "+firstName+ "  "+lastName+"  "+"Age = "+age;
    		}	
    		String whatsUp()
    		{
    			double r = Math.random();
    			int myNumber = (int) (r * 3f); //comment: a random number between 0 and 2
    			String answer = "I don't know";
    			if(myNumber == 0) answer = "searching the web";
    			if(myNumber == 1) answer = "doing Java";
    			if(myNumber == 2) answer = "Listening to endless lecture";
    			return answer;
    		}
    }

  17. #17
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    I would change myJPanel1 in a few ways. First I'd rename it MyJPanel1 to comply with Java naming conventions that all class names begin with an upper case. Next I'd make the JButton a class field, not a variable that is local only to the constructor. Then I'd add JTextFields in this JPanel to get the information you need: first name, last name, and age. I'd have a public getStudent() method to retrieve the information from the fields and package it into a Student object. And finally, I'd have a public void addActionPerformed method as I have in my PanelCommSender class.

    Again for myJPanel2, I'd change the name to conform to conventions, I'd have some class field JTextFields or JLabels to show the information obtained from the first panel, and I'd have a public setStudent(Student s) method to receive a Student object from the first panel and then display the Student results into the display fields.

    Finally, I'd use the myJPanel as the controller (as per my previous example), hooking the two other classes together via the ActionListener. Have a look at my example as its concepts would be eminently workable for your program.

  18. #18
    pjr5043 is offline Member
    Join Date
    Sep 2008
    Posts
    16
    Rep Power
    0

    Default

    alrite .. well i think most of what u listed is very advanced for me .. i haven't learned that yet. i just talked to my professors and he said i ahve to move a button from panel 1 into panel2

    what i did with my code is i have the listening button on the same panel .. i just need to know how to transfer that over

Similar Threads

  1. Replies: 3
    Last Post: 05-22-2011, 04:16 PM
  2. JList and JPanels
    By JetsYanks in forum New To Java
    Replies: 8
    Last Post: 12-25-2009, 03:11 PM
  3. Problems with JPanels and displaying
    By Mastergeek666 in forum AWT / Swing
    Replies: 1
    Last Post: 01-19-2008, 01:32 AM
  4. Can't synchronize multiple JPanels in a JFrame
    By vassil_zorev in forum AWT / Swing
    Replies: 0
    Last Post: 12-30-2007, 05:22 PM
  5. How to add Images to JPanels?
    By Soda in forum New To Java
    Replies: 3
    Last Post: 12-08-2007, 06:54 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •