Results 1 to 20 of 20
  1. #1
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default JButton Action Listner

    so here is my calculator, i am trying to get it to have action listners for all the buttons. i have tried and tried many tutorials online and cannot figure out how to successfully add action listeners to all the buttons and detect them. Any Ideas?

    Java Code:
    package Calculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    public class Main {
    
    JFrame frame;
    JPanel panel;
    JPanel screen;
    JTextField number;
    JButton one;
    JButton two;
    JButton three;
    JButton four;
    JButton five;
    JButton six;
    JButton seven;
    JButton eight;
    JButton nine;
    JButton ten;
    JButton zero;
    JButton plus;
    JButton minus;
    JButton divide;
    JButton multiply;
    JButton decmal;
    JButton equals;
    JLabel blank1;
    JLabel blank2;
    JLabel blank3;
    public Main() {
    	//Create and set up the window.
    	frame = new JFrame("Calculator by: Isaac Flaum");
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	frame.setSize(new Dimension(300, 300));
            screen = new JPanel (new GridLayout(2,1));
            	number = new JTextField("Number");
                    JLabel space = new JLabel("");
            number.setBackground(Color.WHITE);
    	screen.add(number);
            screen.add(space);
    	panel = new JPanel(new GridLayout(4,4));
    	addItems();
    	frame.getContentPane().add(screen, BorderLayout.NORTH);
            frame.getContentPane().add(panel, BorderLayout.CENTER);
    	frame.pack();
    	frame.setVisible(true);
           
    }
    private void addItems() {
            seven = new JButton("7");
            panel.add(seven);
            eight = new JButton("8");
            panel.add(eight);
            nine = new JButton("9");
            panel.add(nine);
            divide = new JButton("/");
            panel.add(divide);
            four = new JButton("4");
            panel.add(four);
            five = new JButton("5");
            panel.add(five);
            six = new JButton("6");
            panel.add(six);
            multiply = new JButton("*");
            panel.add(multiply);
            one = new JButton("1");
            panel.add(one);
            two = new JButton("2");
            panel.add(two);
            three = new JButton("3");
            panel.add(three);
            minus = new JButton("-");
            panel.add(minus);
            zero = new JButton("0");
            panel.add(zero);
            decmal = new JButton(".");
            panel.add(decmal);
            equals = new JButton("=");
            panel.add(equals);
            plus = new JButton("+");
            panel.add(plus);
    }
    private static void createAndShowGUI() {
    	Main converter = new Main();
    }
    public static void main(String[] args) {
    	javax.swing.SwingUtilities.invokeLater(new Runnable() {
    		public void run() {
    			createAndShowGUI();
    		}
    	});
    }
    }

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

    Default

    Your problem is that you are trying to do this on too complex a program. Just try adding an actionlistener to a very simple program that has say only one button on it. I'd recommend that you give it a try, then come back.

    Also, consider using a 2-D array of String to hold your button texts, and then creating the buttons is as easy as nesting two for loops, looping through the Strings and creating the buttons with the appropriate String. An array like so would work well:
    Java Code:
      private String[][] buttonStrings =
      {
          {"7", "8", "9", "/"},
          {"4", "5", "6", "*"},
          {"1", "2", "3", "-"},
          {"0", ".", "=", "+"}
      };
    This would greatly simplify the above code.

    Also, you want to read and study these tutorials:
    How to Use Buttons, Check Boxes, and Radio Buttons (The Java™ Tutorials > Creating a GUI with JFC/Swing > Using Swing Components)
    How to Write an Action Listener (The Java™ Tutorials > Creating a GUI with JFC/Swing > Writing Event Listeners)

    Good luck!
    Last edited by Fubarable; 09-30-2008 at 07:51 AM. Reason: Additional information provided.

  3. #3
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    yea i can do that with the array, i just want to make it so taht when you press one, 1 comes up on the screen, the rest i can easily do by myself, im just confuzed as to how i can get multiple action listners.

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

    Default

    In this situation, I'd use two or more actionlistener classes:
    1) one to handle the number and "." buttons -- the buttons that cause a number to be displayed in the textfield, and
    2) the other to handle the operations buttons ("/", "*", "-", "=", "+") -- the buttons that cause an operation to occur.

    Again, if I were doing this, I'd make the two ActionListener-implementing classes private inner classes (though this is certainly not a necessity), and I'd create one object for each class before the nested loops that created my buttons. Then inside the loops that create the buttons, I'd test which type of String is being added to the button -- number or operation -- and add the appropriate actionlistener object then. This testing could be done with a simple Regex and a call to String#match(...), or if you can't use that, then just test if numberString = "012345679." contains your string with the String#contains(...) method.

    but again, this presupposes that you know how to use ActionListeners. If not, again first create a simple program with a single button and see if you can get it to work. Come on back with your new code if you have further questions.

    Good luck.

  5. #5
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default Working!

    so it works now!! the only problem is i would like to center the display at teh top, and make the buttons look like a normal calculator. how can i change the positions of them, like the gridlayout thingy?

    Java Code:
    package ButtonDemo;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.math.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class Main extends JPanel implements ActionListener {
          double firstnum;
            double secondnum;
            double answer;
            String sanswer;
            int operation = 0;
        protected JButton zero, one, two,three,four,five,six,seven,eight,nine,equal,multiply,decmal,minus,plus,divide;
        protected JTextField screen;
        public Main() {
            screen = new JTextField(20);
            add(screen);
            seven = new JButton("7");
            seven.setActionCommand("eseven");
            add(seven);
            eight = new JButton("8");
            eight.setActionCommand("eeight");
            add(eight);
            nine = new JButton("9");
            nine.setActionCommand("enine");
            add(nine);
            divide = new JButton("/");
            divide.setActionCommand("edivide");
            add(divide);
            four = new JButton("4");
            four.setActionCommand("efour");
            add(four);
            five = new JButton("5");
            five.setActionCommand("efive");
            add(five);
            six = new JButton("6");
            six.setActionCommand("esix");
            add(six);
            multiply = new JButton("*");
            multiply.setActionCommand("emultiply");
            add(multiply);
            one = new JButton("1");
            one.setActionCommand("eone");
            add(one);
            two = new JButton("2");
            two.setActionCommand("etwo");
            add(two);
            three = new JButton("3");
            three.setActionCommand("ethree");
            add(three);
            minus = new JButton("-");
            minus.setActionCommand("eminus");
            add(minus);
            zero = new JButton("0");
            zero.setActionCommand("ezero");
            add(zero);
            decmal = new JButton(".");
            decmal.setActionCommand("edecmal");
            add(decmal);
            equal = new JButton("=");
            equal.setActionCommand("eequals");
            add(equal);
            plus = new JButton("+");
            plus.setActionCommand("eplus");
            add(plus);
    
            //Listen for actions on buttons 1 and 3.
            one.addActionListener(this);
            two.addActionListener(this);
            three.addActionListener(this);
            four.addActionListener(this);
            five.addActionListener(this);
            six.addActionListener(this);
            seven.addActionListener(this);
            eight.addActionListener(this);
            nine.addActionListener(this);
            zero.addActionListener(this);
            plus.addActionListener(this);
            minus.addActionListener(this);
            equal.addActionListener(this);
            divide.addActionListener(this);
            multiply.addActionListener(this);
            decmal.addActionListener(this);
     
        }
    
        public void actionPerformed(ActionEvent e) {
            if ("eone".equals(e.getActionCommand())) {
                String pnum = screen.getText();
                screen.setText(pnum + '1');
            }
            if ("etwo".equals(e.getActionCommand())) {
                          String pnum = screen.getText();
                screen.setText(pnum + '2');  
            }
            if ("ethree".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '3');
            }
            if ("efour".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '4');
            }
            if ("efive".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '5');
            }
            if ("esix".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '6');
            }
            if ("eseven".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '7');
            }
            if ("eeight".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '8');
            }
            if ("enine".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '9');
            }
            if ("ezero".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '0');
            }
            if ("eplus".equals(e.getActionCommand())) {
                firstnum = (Double.parseDouble(screen.getText()));
                operation = 1;
                screen.setText("");
            }
            if ("eminus".equals(e.getActionCommand())) {
                firstnum = (Double.parseDouble(screen.getText()));
                operation = 2;
                screen.setText("");
            }
            if ("emultiply".equals(e.getActionCommand())) {
                            firstnum = (Double.parseDouble(screen.getText()));
                operation = 3;
                screen.setText("");
            }
            if ("edivide".equals(e.getActionCommand())) {
                firstnum = (Double.parseDouble(screen.getText()));
                operation = 4;
                screen.setText("");
            }
            if ("eequals".equals(e.getActionCommand())) {
                secondnum = (Double.parseDouble(screen.getText()));
                
                    if (operation == 1)
                    {
                    screen.setText("");
                    answer = firstnum + secondnum;
                    sanswer = Double.toString(answer);
                    screen.setText(sanswer);
                    }
     if (operation == 2)
                    {
                    screen.setText("");
                    answer = firstnum - secondnum;
                    sanswer = Double.toString(answer);
                    screen.setText(sanswer);
     }
              if (operation == 3)
                    {
                    screen.setText("");
                    answer = firstnum * secondnum;
                    sanswer = Double.toString(answer);
                    screen.setText(sanswer);
              }
              if (operation == 4)
                    {
                    screen.setText("");
                    answer = firstnum / secondnum;
                    sanswer = Double.toString(answer);
                    screen.setText(sanswer);
               
                    }
                }
            if ("edecmal".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '.');
            }
        }
        private static void createAndShowGUI() {
    
            //Create and set up the window.
            JFrame frame = new JFrame("Main");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            //Create and set up the content pane.
            Main newContentPane = new Main();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
    
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI(); 
                }
            });
        }
    }

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,792
    Rep Power
    25

    Default

    To position components in a container, you'll need to read about how to use layout managers. There are several and you can use different ones in different sub containers like a JPanel in a JFrame.
    For a calculator you'll probably want rows of buttons so the GridLayout or GridBagLayout classes could be the ones. You'll find a list of the layout managers in the API doc for LayoutManager.
    There are many coding examples around if you use Search.

  7. #7
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    so i added the layout, but i can't seem to make the screen show up on the top center, and the rest of the buttons have a regular grid layout. I tried to make a JPanel and put just the screen on it, but it failed. Any ideas?

    Java Code:
    package Calculator1;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.*;
    public class Main extends JPanel implements ActionListener {
          double firstnum;
            double secondnum;
            double answer;
            String sanswer;
            int operation = 0;
        protected JButton zero, one, two,three,four,five,six,seven,eight,nine,equal,multiply,decmal,minus,plus,divide;
        JTextField screen;
        public Main() {
             screen = new JTextField(20);
            add(screen);
            setLayout(new GridLayout(4,4));
            seven = new JButton("7");
            seven.setActionCommand("eseven");
            add(seven);
            eight = new JButton("8");
            eight.setActionCommand("eeight");
            add(eight);
            nine = new JButton("9");
            nine.setActionCommand("enine");
            add(nine);
            divide = new JButton("/");
            divide.setActionCommand("edivide");
            add(divide);
            four = new JButton("4");
            four.setActionCommand("efour");
            add(four);
            five = new JButton("5");
            five.setActionCommand("efive");
            add(five);
            six = new JButton("6");
            six.setActionCommand("esix");
            add(six);
            multiply = new JButton("*");
            multiply.setActionCommand("emultiply");
            add(multiply);
            one = new JButton("1");
            one.setActionCommand("eone");
            add(one);
            two = new JButton("2");
            two.setActionCommand("etwo");
            add(two);
            three = new JButton("3");
            three.setActionCommand("ethree");
            add(three);
            minus = new JButton("-");
            minus.setActionCommand("eminus");
            add(minus);
            zero = new JButton("0");
            zero.setActionCommand("ezero");
            add(zero);
            decmal = new JButton(".");
            decmal.setActionCommand("edecmal");
            add(decmal);
            equal = new JButton("=");
            equal.setActionCommand("eequals");
            add(equal);
            plus = new JButton("+");
            plus.setActionCommand("eplus");
            add(plus);
    
            //Listen for actions on buttons 1 and 3.
            one.addActionListener(this);
            two.addActionListener(this);
            three.addActionListener(this);
            four.addActionListener(this);
            five.addActionListener(this);
            six.addActionListener(this);
            seven.addActionListener(this);
            eight.addActionListener(this);
            nine.addActionListener(this);
            zero.addActionListener(this);
            plus.addActionListener(this);
            minus.addActionListener(this);
            equal.addActionListener(this);
            divide.addActionListener(this);
            multiply.addActionListener(this);
            decmal.addActionListener(this);
     
        }
    
        public void actionPerformed(ActionEvent e) {
            if ("eone".equals(e.getActionCommand())) {
                String pnum = screen.getText();
                screen.setText(pnum + '1');
            }
            if ("etwo".equals(e.getActionCommand())) {
                          String pnum = screen.getText();
                screen.setText(pnum + '2');  
            }
            if ("ethree".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '3');
            }
            if ("efour".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '4');
            }
            if ("efive".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '5');
            }
            if ("esix".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '6');
            }
            if ("eseven".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '7');
            }
            if ("eeight".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '8');
            }
            if ("enine".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '9');
            }
            if ("ezero".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '0');
            }
            if ("eplus".equals(e.getActionCommand())) {
                firstnum = (Double.parseDouble(screen.getText()));
                operation = 1;
                screen.setText("");
            }
            if ("eminus".equals(e.getActionCommand())) {
                firstnum = (Double.parseDouble(screen.getText()));
                operation = 2;
                screen.setText("");
            }
            if ("emultiply".equals(e.getActionCommand())) {
                            firstnum = (Double.parseDouble(screen.getText()));
                operation = 3;
                screen.setText("");
            }
            if ("edivide".equals(e.getActionCommand())) {
                firstnum = (Double.parseDouble(screen.getText()));
                operation = 4;
                screen.setText("");
            }
            if ("eequals".equals(e.getActionCommand())) {
                secondnum = (Double.parseDouble(screen.getText()));
                
                    if (operation == 1)
                    {
                    screen.setText("");
                    answer = firstnum + secondnum;
                    sanswer = Double.toString(answer);
                    screen.setText(sanswer);
                    }
     if (operation == 2)
                    {
                    screen.setText("");
                    answer = firstnum - secondnum;
                    sanswer = Double.toString(answer);
                    screen.setText(sanswer);
     }
              if (operation == 3)
                    {
                    screen.setText("");
                    answer = firstnum * secondnum;
                    sanswer = Double.toString(answer);
                    screen.setText(sanswer);
              }
              if (operation == 4)
                    {
                    screen.setText("");
                    answer = firstnum / secondnum;
                    sanswer = Double.toString(answer);
                    screen.setText(sanswer);
               
                    }
                }
            if ("edecmal".equals(e.getActionCommand())) {
                            String pnum = screen.getText();
                screen.setText(pnum + '.');
            }
        }
        public static void createAndShowGUI() {
    
            //Create and set up the window.
            JFrame frame = new JFrame("Main");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            //Create and set up the content pane.
            Main newContentPane = new Main();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
            
        }
    
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI(); 
                }
            });
        }
    }

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,792
    Rep Power
    25

    Default

    Have you tried a Borderlayout for the first layout and add a JPanel in the NORTH for the screen and put the buttons in another JPanel in the CENTER using a grid?

    In your actionPerformed method, can more than one if condition be true at the same time? You have a series of if statements that look like only one will be true at a time. For that case use if{}else if()else if{} ...

    For the if tests for operation == #, it looks like a switch statement would be better.

  9. #9
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    can u show me how to create the two different jpanels in this script, because i cannot seem to do so myself. I implemented your switch statement as that seemed alot smarter, thanks!

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

    Default

    First I recommend that you show us your attempt. You always learn more by trying first, and we will better be able to explain what you need to know if we can see where your mistakes are. Again, it will be better for you to try this in a small test program that doesn't have all the overhead that your main program currently has.

    Also, I'll emphasize again, that by using arrays, you could vastly simplify this program. The ActionListener will know which button was pressed via the ActionEvent's getSource() method, and with the button, you can get the button string. So all those if statements can be done away with again vastly simplifying your program.
    Last edited by Fubarable; 10-01-2008 at 05:09 AM.

  11. #11
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    i try to add

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

    Default

    Quote Originally Posted by 2o2 View Post
    i try to add
    Here may be found the last words of 2o2. He who is valiant and pure of spirit may find the answer to this question in the class of Aaauuuggghhh...

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

    Default

    Here is a brief example of how using arrays and smart ActionListeners you can shorten your code, and make it much easier to read and debug:
    Java Code:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    
    public class SimpleButtonGrid
    {
      private JPanel mainPanel = new JPanel(); // panel holds the button grid
      String[][] buttonStrings = // use these Strings to create a JButton grid
      {
          {"A", "B", "C"},
          {"D", "E", "F"},
          {"G", "H", "I"}
      };
    
      public SimpleButtonGrid()
      {
        int rowLength = buttonStrings.length;
        int colLength = buttonStrings[0].length;
        mainPanel.setLayout(new GridLayout(rowLength, colLength));
        ButtonListener buttonListener = new ButtonListener(); // create our ActionListener
        for (int row = 0; row < rowLength; row++)
        {
          for (int col = 0; col < colLength; col++)
          {
            // for each String in the array, create a button that holds the string
            String buttonString = buttonStrings[row][col];
            JButton button = new JButton(buttonString); // this button here
            button.addActionListener(buttonListener); // add the listener
            mainPanel.add(button); // and add it to the panel
          }
        }
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
      
      // here's the button listener class that of course implements action listener
      private class ButtonListener implements ActionListener
      {
        public void actionPerformed(ActionEvent e)
        {
          // we can easily extract the String held by the button pressed 
          String actionCommand = e.getActionCommand(); // here's the string
          System.out.println("Button Selected: " + actionCommand);  // let's show it
        }
      }
    
      // this calls our Swing code in a thread-safe manner  
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("SimpleButtonGrid");
        frame.getContentPane().add(new SimpleButtonGrid().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

  14. #14
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    i took your advice and made this much better gui, thanks! but now i cannot get the screen to show up on the gui, i created and added the jpanel to the jframe, but it won't show. any reason why?

    Java Code:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    
    public class Simplebuttongrid
    {
      private JPanel mainPanel = new JPanel(); // panel holds the button grid
      private JPanel screenPanel = new JPanel(); //panel to hold screen
      String[][] buttonStrings = // use these Strings to create a JButton grid
      {
          {"7", "8", "9", "/"},
          {"4", "5", "6", "*"},
          {"1", "2", "3", "-"},
          {"0", ".", "=", "+"},
      };
    
      public Simplebuttongrid()
      {
        int rowLength = buttonStrings.length;
        int colLength = buttonStrings[0].length;
        mainPanel.setLayout(new GridLayout(rowLength, colLength));
        screenPanel.setLayout(new GridLayout(1,1));
        ButtonListener buttonListener = new ButtonListener(); // create our ActionListener
        for (int row = 0; row < rowLength; row++)
        {
          for (int col = 0; col < colLength; col++)
          {
            // for each String in the array, create a button that holds the string
            String buttonString = buttonStrings[row][col];
            JButton button = new JButton(buttonString); // this button here
            button.addActionListener(buttonListener); // add the listener
            mainPanel.add(button); // and add it to the panel
          }
        }
       JTextField screen = new JTextField(20);
       screenPanel.add(screen);
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
      public JComponent getComponent2()
      {
      	return screenPanel;
      }
      
      // here's the button listener class that of course implements action listener
      private class ButtonListener implements ActionListener
      {
        public void actionPerformed(ActionEvent e)
        {
          // we can easily extract the String held by the button pressed 
          String actionCommand = e.getActionCommand(); // here's the string
          if (actionCommand == "5"){
          	 System.out.println("you pressed 5");  // let's show it
          }
         
        }
      }
    
      // this calls our Swing code in a thread-safe manner  
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("Calculator");
        frame.getContentPane().add(new Simplebuttongrid().getComponent2());
        frame.getContentPane().add(new Simplebuttongrid().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

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

    Default

    Quote Originally Posted by 2o2 View Post
    i took your advice and made this much better gui, thanks! but now i cannot get the screen to show up on the gui, i created and added the jpanel to the jframe, but it won't show. any reason why?
    When you add to a JFrame contentPane, you are adding to a component that by default uses BoderLayout. This is a good thing as you can use BorderLayout to your advantage, but when you add components to a borderlayout using container, you have to tell the container where to place the components. Have a look at the Sun layout tutorial, and it will tell you how to do this.

  16. #16
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,792
    Rep Power
    25

    Default

    when you add components to a borderlayout using container, you have to tell the container where to place the components
    Look at the add() method. It has parameters for this.

  17. #17
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    in the layout tutorial, i coudlnt find out where this was. all i am trying to do is to get both JPanels to show. i tried to add the screenPanel.add(screen,BorderLayout.NORTH); and stuff, but it still doesnt show this other panel. how do i tell the container where to place the components?? i thought that's what the .NORTH thing was.

  18. #18
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    i figured out what it's doing, its adding only one of the components, as when i flip the order of these two lines, it swithes between adding the screen and the buttons, how do i get it to add both the screen and the buttons?
    Java Code:
    frame.getContentPane().add(new Simplebuttongrid().getComponent2());
        frame.getContentPane().add(new Simplebuttongrid().getComponent());

  19. #19
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,792
    Rep Power
    25

    Default

    Can you post the code where you are building the GUI and the definitions for the GUI components? Hard to understand exactly what is happening from your text.

  20. #20
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

Similar Threads

  1. Call action of JButton from another class
    By geckolux in forum AWT / Swing
    Replies: 5
    Last Post: 08-04-2014, 07:17 PM
  2. Run RCP action from outside of the Eclipse RCP
    By leonbandas in forum Eclipse
    Replies: 1
    Last Post: 01-07-2008, 08:15 AM
  3. jsp:forward action
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-24-2007, 11:04 AM
  4. jsp:param action
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-24-2007, 11:03 AM
  5. Few action in one Jbutton
    By kubiasty in forum New To Java
    Replies: 0
    Last Post: 07-25-2007, 11:19 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
  •