Results 1 to 15 of 15
  1. #1
    Sandia_man is offline Member
    Join Date
    May 2010
    Posts
    12
    Rep Power
    0

    Default How to catch a button event that is in a Panel

    Hi!!
    I'm developing a little application to try some things but I got stuck, so I came to the forum for some help!

    I tried googling but I couldn't find any info...

    I have the following situation:

    I have a class called userPanel, that class extends the Panel class. I draw some labels and buttons in that panel using the netbeans's gui editor...

    I also have a Form, and I added to that form instances of my "userPanel" class. The problem is that I don't know how to catch the button events of the buttons that are in the panel.

    To change for example the text in the labels I just use a "setLabels" method written by me... but I don't know how to work with buttons...

    How can I do to solve this???? Any ideas??

    Thanks in advance!!

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    how to catch the button events
    What is a button event? There are ActionEvents and MouseEvents and KeyEvents and many more.
    To catch an event you need to add a listener for that type of event to the component that is generating the event.

    I draw some labels and buttons
    Are you creating your own components here vs using Javas? Its a good way to learn how the GUI stuff works.

  3. #3
    Sandia_man is offline Member
    Join Date
    May 2010
    Posts
    12
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    What is a button event? There are ActionEvents and MouseEvents and KeyEvents and many more.
    To catch an event you need to add a listener for that type of event to the component that is generating the event.


    Are you creating your own components here vs using Javas? Its a good way to learn how the GUI stuff works.
    By drawing I tried to say that I've added those components.

    I want to catch ActionEvents (the push of the button), I don't know how to do it when the button is in an extended class of a Panel, and what I have added to the Form is the extension of the panel and not the button it self.

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

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    You'll have to show your code. If you use your own words to describe technical things, no one can understand you. A proper description is required.

    Are you using existing components such as Button or JButton, or are you trying to build your own buttons from panels?

  6. #6
    Sandia_man is offline Member
    Join Date
    May 2010
    Posts
    12
    Rep Power
    0

    Default

    ok, here is my code. I'm using AWT.

    I really don't know how to explain it better...


    This is the form where I add my own extended panel with the labels and buttons I need.

    Java Code:
    import java.awt.FlowLayout;
    
    public class Principal extends java.awt.Frame {
    
        /** Creates new form Principal */
        public Principal() {
            initComponents();
            SelecCantJug jugP = new SelecCantJug(this,true);
            jugP.setVisible(true);
            playersQuantity = jugP.getCantJugadores();
    
            if(playersQuantity == 0)
                System.exit(0);
    
            player =  new JugPanel[playersQuantity + 1];
            panelJugadores.setLayout(new FlowLayout());
    
          
    
            for(int i=0;i<playersQuantity +1;i++){
                player[i] = new JugPanel();
                //en 0 pongo al crupier
                if(i==0){
                    player[i].setNameJug("Initial");
                }else{
                    player[i].setNameJug(Integer.toString(i));
                    //jug[i].desHabilitarBotones(0);
                }
    
                panelJugadores.add(player[i]);
            }
    
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            panelJugadores = new java.awt.Panel();
    
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(panelJugadores, javax.swing.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE)
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(panelJugadores, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(22, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {                          
            System.exit(0);
        }                         
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Principal().setVisible(true);
                }
            });
        }
    
        JugPanel player[] = null;
        int playersQuantity;
        // Variables declaration - do not modify                     
        private java.awt.Panel panelJugadores;
        // End of variables declaration                   
    
    }
    This is an extended Dialog that lets me choose the number of players that will be playing the game.

    Java Code:
    public class SelecCantJug extends java.awt.Dialog {
    
        /** Creates new form Jugadores */
        public SelecCantJug(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
            cantJug.addItem("1 Jugador");
            cantJug.addItem("2 Jugadores");
            cantJug.addItem("3 Jugadores");
            cantJug.addItem("4 Jugadores");
            cantJug.select("1 Jugador");
    
          
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jug = new java.awt.Label();
            cantJug = new java.awt.Choice();
            button1 = new java.awt.Button();
    
            setLocationRelativeTo(this);
            setResizable(false);
            setTitle("Black Jack");
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    closeDialog(evt);
                }
            });
    
            jug.setText("Jugadores:");
    
            button1.setLabel("Play");
            button1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    button1ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(20, 20, 20)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(button1, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jug, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(cantJug, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(cantJug, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jug, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(11, Short.MAX_VALUE))
            );
    
            jug.getAccessibleContext().setAccessibleName("Players");
    
            pack();
        }// </editor-fold>
    
        /** Closes the dialog */
        private void closeDialog(java.awt.event.WindowEvent evt) {                             
            setVisible(false);
            dispose();
        }                            
    
        private void button1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            // TODO add your handling code here:
            cantJugadores = cantJug.getSelectedIndex()+1;
            this.setVisible(false);
    
        }                                       
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    SelecCantJug dialog = new SelecCantJug(new java.awt.Frame(), true);
                    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                        }
                    });
                    dialog.setVisible(true);
                }
            });
        }
    
        public int getCantJugadores() {
            return cantJugadores;
        }
    
        private int cantJugadores;
        // Variables declaration - do not modify
        private java.awt.Button button1;
        private java.awt.Choice cantJug;
        private java.awt.Label jug;
        // End of variables declaration
    
    }
    This is the panel with the buttons and labels that I need. I don't know how to catch the actionPerformed of these buttons from the Form (the first code).

    Java Code:
    import java.awt.Graphics;
    
    
    public class JugPanel extends java.awt.Panel {
    
        /** Creates new form JugPanel */
        public JugPanel() {
            initComponents();
        }
    
     
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jug = new java.awt.Label();
            jugNombre = new java.awt.Label();
            pedirCarta = new java.awt.Button();
            split = new java.awt.Button();
    
            jug.setText("Jugador:");
    
            pedirCarta.setActionCommand("button1");
            pedirCarta.setLabel("End");
    
            split.setLabel("Split");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jug, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jugNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(pedirCarta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(split, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(26, Short.MAX_VALUE))
            );
    
            layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {pedirCarta, split});
    
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jug, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jugNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(129, 129, 129)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(pedirCarta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(split, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
        }// </editor-fold>
    
        @Override
         public void paint( Graphics g ) {
             super.paint( g );
             g.setColor( getForeground() );
             g.drawRect( 5, 5, getWidth() - 10, getHeight() - 10 );
             g.setColor( getBackground() );
             g.fillRect( 10, 0, 0, 10 );
             g.setColor( getForeground() );
         }
    
    
    
         public void setNameJug(String nombre){
             jugNombre.setText(nombre);
         }
    
         
    
    
    
        // Variables declaration - do not modify
        private java.awt.Label jug;
        private java.awt.Label jugNombre;
        private java.awt.Button pedirCarta;
        private java.awt.Button split;
        // End of variables declaration
    
    
    }
    Hope you can understand me...
    Thanks a lot!!

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    To catch events like the pressing of a button, you need to add listeners to those objects/buttons. I don't see any listeners for the split button or the pedirCarta button.
    You do have a listener for button1.

  8. #8
    Sandia_man is offline Member
    Join Date
    May 2010
    Posts
    12
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    To catch events like the pressing of a button, you need to add listeners to those objects/buttons. I don't see any listeners for the split button or the pedirCarta button.
    You do have a listener for button1.
    Yes, But I want to do that from the class principal, I want to catch the pressing of the button split from the class Principal, I don't know how to do that...

    Thanks!!

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    Have the principal class implement ActionListener and use a reference to the principal class in the addActionListener() method call. Then when the split button is pressed, the actionPerformed() method in the principal class will be called.

    Or have the ActionListener code be in the class that defines the split button and have the actionPerformed() method in that listener call a method in the principal class.

  10. #10
    chiwawah is offline Member
    Join Date
    Dec 2010
    Posts
    1
    Rep Power
    0

    Default

    So happen I'm googling something similar, and I found the solution from the Part 5 of this Java Tutorial :
    Building an Application: Introduction

    Sorry for not having the patient to go through your code, and I'll just describe what I did. Hope this is also what u're looking for.

    First I wrote a class extended JPanel which hv 3 buttons only, a code snippet as follow:

    public class customerbuttonPanel extends javax.swing.JPanel {

    public customerbuttonPanel() {
    initComponents();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton NewCustomerButton;
    private javax.swing.JButton NewDeleteButton;
    private javax.swing.JButton NewSaveButton;
    // End of variables declaration//GEN-END:variables


    private void initComponents() {
    NewCustomerButton = new javax.swing.JButton();
    NewSaveButton = new javax.swing.JButton();
    NewDeleteButton = new javax.swing.JButton();

    NewCustomerButton.setText("New");

    NewSaveButton.setText("Save");

    NewDeleteButton.setText("Delete");

    //
    // Do All formatting stuffs, not important
    //
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addComponent(NewCustomerButton)
    .addPreferredGap(javax.swing.LayoutStyle.Component Placement.UNRELATED)
    .addComponent(NewDeleteButton)
    .addPreferredGap(javax.swing.LayoutStyle.Component Placement.UNRELATED)
    .addComponent(NewSaveButton))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.BASELINE)
    //
    //Add the NewCustomerButton to the Panel Layout
    .addComponent(NewCustomerButton)
    .addComponent(NewDeleteButton)
    .addComponent(NewSaveButton))
    );
    //
    // And finish all formatting stuffs, not important
    //

    }

    //NOTE HERE, ADD A PUBLIC METHOD SO THAT PARENT PANEL CAN ACCESS THE BUTTON
    public JButton getNewCustomerButton(){
    return NewCustomerButton;
    }

    }

    In the child panel you declare a private JButton as normal, and make sure you create a public method that return the created button as JButton.

    Then I add the child Panel to a parent panel through my IDE, and after the child panel setup in the constructor :

    public class customerPanel extends javax.swing.JPanel {

    public customerPanel() {
    initComponents();

    // After the Child Panel added to this Parent Panel in the Constructor init
    // routine, declare a JButton Object (newButton) from the getNewCustomerButton method
    // delcared in the child Panel.
    // Then you can manipulate the newButton, says, add a listener like what I did, or newButton.setText("blablabla");
    // or anything that twist the button to something u like.

    JButton newButton = buttonPanel.getNewCustomerButton();
    newButton.addActionListener (
    new ActionListener () {
    public void actionPerformed (ActionEvent ae)
    {clearFieldsforInput();}//Close method
    }//Close inner class
    );//Close argument and block for New Button Press Event Handling
    }

    private void initComponents() {
    // .
    // . other formatting stuffs

    // create a customerbuttonPanel Object here
    buttonPanel = new dbappsample.customerbuttonPanel();
    // .
    // .more formatting stuffs
    // .
    // .
    // and add the Panel to the gridBag Layout of this parent panel

    add(buttonPanel, gridBagConstraints);

    // .. other formatting stuffs in the init/ constructor

    }// </editor-fold>//GEN-END:initComponents

    }

    I create an instance of the button in the child Panel by calling the getbutton method that I created in the child panel:

    "JButton newButton = buttonPanel.getNewCustomerButton();"

    and manipulate the newButton instance in the parent class.
    Last edited by chiwawah; 12-13-2010 at 12:23 PM.

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    Quote Originally Posted by chiwawah View Post
    Hope this is also what u're looking for.
    Do you really think Sandia_man is still waiting for your answer 6 months after the question was asked? or are you date-reading-impaired?

    db

  12. #12
    hosscomp is offline Member
    Join Date
    Oct 2010
    Posts
    63
    Rep Power
    0

    Default

    Chiwawa's post might be helpful for the next searcher that finds this thread.
    Was it marked 'Solved?'

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,309
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by hosscomp View Post
    Chiwawa's post might be helpful for the next searcher that finds this thread.
    Was it marked 'Solved?'
    Given the (short) attention span of nowadays posters it was.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    Quote Originally Posted by hosscomp View Post
    Chiwawa's post might be helpful for the next searcher that finds this thread.
    Was it marked 'Solved?'
    Certainly not nearly as helpful as Fubarable's advice much higher up in the thread.
    Quote Originally Posted by Fubarable View Post
    db

  15. #15
    hosscomp is offline Member
    Join Date
    Oct 2010
    Posts
    63
    Rep Power
    0

Similar Threads

  1. how do i get componet event in Panel ?
    By pandar2 in forum New To Java
    Replies: 3
    Last Post: 11-05-2009, 04:20 PM
  2. Redraw panel in timer event
    By knuth in forum Advanced Java
    Replies: 6
    Last Post: 10-03-2009, 07:39 PM
  3. How can I catch the radio button action in jsp?
    By srinivas2828 in forum JavaServer Pages (JSP) and JSTL
    Replies: 2
    Last Post: 09-18-2009, 04:05 PM
  4. AWT - catching click button event
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-11-2008, 11:02 PM
  5. How to perform some event to button click
    By eva in forum AWT / Swing
    Replies: 2
    Last Post: 01-16-2008, 12:27 AM

Posting Permissions

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