Search code examples
javaswingjbutton

How to display a JButton and give it functionality?


Two questions.
Firstly I'm trying to display a JButton on a JFrame, so far I've managed to display the JFrame with nothing on it.
Secondly how would one add functionality to a button? Would you pass it a method? Any feedback is appreciated.

           <code>
           //imports SWING etc...
           //global variables...

            public class FahrenheitGUI {
            public static void main(String args[]){
            prepareGUI();
            }

            private static void prepareGUI(){
            JFrame frame = new JFrame("Temp");
            JPanel panel = new JPanel();
            JLabel temperatureLabel;
            int h = 300; int w = 300;
            frame.setSize(h,w);

            JButton one = new JButton( "0" );
            JButton two = new JButton( "1" );
            JButton three = new JButton( "2" );
            JButton four = new JButton( "3" );
            JButton five = new JButton( "4" );
            JButton six = new JButton( "5" );
            JButton seven = new JButton( "6" );
            JButton eight = new JButton( "7" );
            JButton nine = new JButton( "8" );
            JButton ten = new JButton( "9" );
            JButton negative = new JButton( "-" );
            JButton dot = new JButton( "." );
            JButton reset = new JButton( "reset" );

            one.setBounds(10,10,20,20);

            //one.addActionListener(onButtonPress);
            //creates an error

            frame.setVisible(true);
            }

            }



            class Keypad implements ActionListener{

            public void actionPerformed( ActionEvent one){
            // guessing 
            }
            public void actionPerformed( ActionEvent two){
            // guessing 
            }    
            }


Solution

  • You could create JPanel, add buttons to your panel and then and the whole panel to your JFrame like this:

    JPanel panel = new JPanel(); //by default it will has FlowLayout
    panel.add(yourButton);
    frame.add(yourJPanel);
    frame.setVisible(true);
    

    Personally I create class that extends JPanel, and inside of it I set size for panel (not for frame) and then, after adding panel to my frame I call pack() method which will resize your frame in reference of the size of your panel. If you want to change default layout manager just call setLayout(LayoutManager) Edit: If you want to add functionality to your button just use:

     yourButton.addActionListener(new ActionListener() 
     {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                //button logic
            }
     });