Add ActionListener to JButton

Hi, i am creating some buttons to be added to a grid layouy content pane. The buttons are added like this:
for (int i = 0; i < 400; i++)
gamePanel.add(new JButton("" + i));
How do i add an action listener to each button?

I don't really understand what your problem is but here goesJPanel gamePanel = new JPanel(new GridLayout(400, 1));
ActionListener actionListener = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
          Object source = e.getSource();
          if (source instanceof JButton) {
               System.out.println("button " + ((JButton)source).getText() + " clicked");
for (int i = 0; i < 400; i++) {
     JButton button = new JButton("" + i);
     button.addActionListener(actionListener);
     gamePanel.add(button);
}

Similar Messages

  • How to add ActionListener to ButtonGroup

    I had a ClassA that calls ClassB to display a ButtonGroup of buttons. How can I add ActionListener in ClassA for the buttons in ClassB to listen for button events in ClassB ? Thanks.

    Thank you for your reply.
    I know your suggestion for JButton works.
    But my problem is with a ButtonGroup. The JButtons in the group is generic and I do not know how to add the ActionListener for each of the JButtons in the ButtonGroup.

  • How to add actionlistener to JTable?

    I have created a JTable. and I would like to while I double-click any row of JTable, I go to next frame. How can I add actionlistener to each row?

    Here's an example:
    TableF modeltable = new TableF();
    JTable FuncsTable = new JTable(modeltable);
    FuncsTable.addMouseListener(mlTable);
    MouseListener mlTable = new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    if ( e.getClickCount() == 2 ) {
    System.out.println( FuncsTable.getSelectedRow());
    your code

  • ActionListener with JButton and JMenu

    How do I implement actions for both a JButton and a JMenuItem? Would I have to set it in the actionPerformed method(Action e), because that doesn't seem to work, or else I don't know how to do it. Help would be appreciated.

    But the thing is that I don't want the same action for both the Button and MenuItem.Then create separate ActionListeners for each component.
    button.add(new ActionListener()
        public void actionPerformed(ActionEvent e)
            // add your code here
    }Or test which button was pressed in the actionPerformed method. The Swing tutorial on How to Use Buttons, gives example of this:
    http://java.sun.com/docs/books/tutorial/uiswing/components/button.html

  • Didn't add actionListener to JTextField, but it works anyway.  Why?

    Now this is a new one. I'm not asking why it doesn't work, but why it does work. I wrote up the following code:
    red =  new JTextField (5);
                 red.addActionListener (new inputListener());
              green = new JTextField(3);
              blue = new JTextField(3);
    private class inputListener implements ActionListener
              public void actionPerformed (ActionEvent event)
                   String rText = red.getText();
                   redInput = Integer.parseInt(rText);
                   String gText = green.getText();
                   greenInput = Integer.parseInt(gText);
                   String bText = blue.getText();
                   blueInput = Integer.parseInt(bText);
                   c = new Color(redInput, greenInput, blueInput);
         }I was planning to add listeners for the green and blue text field, but I ran the program first to make sure it was working so far. The strange thing is that the green and blue text fields were listening, even though I hadn't added listeners to them. I don't get it. How are they working?
    Edited by: codinatrix on Jan 11, 2008 4:52 PM
    Because...my cat came onto the keyboard and pressed tab and enter so it posted before I was done writing. Damn cat.

    Okay, I guess I should do a compilable example. What I'm trying to do is let the user input a number into each of the three text fields: red, green, blue, which will then be used to change the background colour of the panel. I added the listener to the red text field, but not the green and blue. Putting in 0 into red, 255 into green, and 0 into blue, for example succeeds in turning the background green, even though the green text field doesn't have a listener.
    public class ColorDisplayPanelTest extends JPanel {
         JPanel displayPanel, textPanel, buttonPanel;
         JLabel displayLabel, redText, greenText, blueText;
         JTextField red, green, blue;
         Color c;
         JButton button;
         int redInput = 0;
         int greenInput = 0;
         int blueInput = 0;
         public ColorDisplayPanelTest() {
              displayPanel = new JPanel();
              textPanel = new JPanel();
              buttonPanel = new JPanel();
              add(displayPanel);
              add(textPanel);
              add(buttonPanel);
             //  Display Panel.
              displayLabel = new JLabel("Colour Display");
              displayPanel.add(displayLabel);
             //  Text Panel.
              red =  new JTextField (5);
                 red.addActionListener (new inputListener());
              green = new JTextField(3);
              blue = new JTextField(3);
              redText = new JLabel("R?d");
              greenText = new JLabel("Gr?n");
              blueText = new JLabel("Bl?");
              textPanel.add(redText);
              textPanel.add(red);
              textPanel.add(greenText);
              textPanel.add(green);
              textPanel.add(blueText);
              textPanel.add(blue);
             //  Button Panel.
              button = new JButton("Visa f?rg");
              buttonPanel.add(button);
             button.addActionListener (new colorButtonListener());
        //  Button Listener class.
         private class colorButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                   displayPanel.setBackground(c);     
         private class inputListener implements ActionListener
              public void actionPerformed (ActionEvent event)
                   String rText = red.getText();
                   redInput = Integer.parseInt(rText);
                   String gText = green.getText();
                   greenInput = Integer.parseInt(gText);
                   String bText = blue.getText();
                   blueInput = Integer.parseInt(bText);
                   c = new Color(redInput, greenInput, blueInput);
    }

  • ActionListener of Jbutton Question

    Hi there,
    I am trying to perform a command via JButton by adding an ActionListener to the frame'instance' of my Pointframe:
    public class MainClass {
      public static void main(String[] args)  {
      try {
      byte[] datasend = new byte[50];
      byte[] tempdatareceive= new byte[1000];
      int incomingPackageSize = 0;
      //create instance of GUI
      Pointframe frame = new Pointframe();
      frame.pack();
      frame.show();
      //add Action Listener stuff
          ActionListener SendStream = new ActionListener()
          public void actionPerformed( ActionEvent e ) {
          System.out.println("this works");
      frame.jButton1.addActionListener( SendStream );
      //create Socket to Connect to EmScon-Server
      Socket connectToEsServer = new Socket ("192.168.0.5",700);
      //create Output Stream to send data to Server
      DataOutputStream StreamtoEsServer
      = new DataOutputStream(connectToEsServer.getOutputStream());
      //create Input Stream to send data to Server
      DataInputStream StreamfromEsServer
      = new DataInputStream(connectToEsServer.getInputStream());
    ................Sending commands like above to the console works fine so far.
    But as long as i start to try invoking variable relatedcommands.
    public class MainClass {
      public static void main(String[] args)  {
      try {
      byte[] datasend = new byte[50];
      byte[] tempdatareceive= new byte[1000];
      int incomingPackageSize = 0;
      //create instance of GUI
      Pointframe frame = new Pointframe();
      frame.pack();
      frame.show();
      //add Action Listener stuff
          ActionListener SendStream = new ActionListener()
          public void actionPerformed( ActionEvent e ) {
         StreamtoEsServer.write(datasend);
      frame.jButton1.addActionListener( SendStream );
      //create Socket to Connect to EmScon-Server
      Socket connectToEsServer = new Socket ("192.168.0.5",700);
      //create Output Stream to send data to Server
      DataOutputStream StreamtoEsServer
      = new DataOutputStream(connectToEsServer.getOutputStream());
      //create Input Stream to send data to Server
      DataInputStream StreamfromEsServer
      = new DataInputStream(connectToEsServer.getInputStream());
    ................I receive errmessages like:
    "MainClass.java": Error #: 480 : local variable datasend is accessed from within inner class; needs to be declared final
    "MainClass.java": Error #: 300 : variable StreamtoEsServer not found in anonymous class of method main(java.lang.String[])
    Can please somebody bring light into that?
    What is the best way to implement such stuff in general?
    Any ideas are greatly appreciated.
    Best regards,
    stonee

    Hi,
    try instantiaitng your variable datasend as private variable in the class outside your main-method

  • Bug? Unable to add ActionListener using Anonymous class.

    Hi,
    I come accross one strange behaviour while adding ActionListener to RCF component.
    I am trying to add the ActionListener in the managed bean using the Anonymous.
    We can add the actionListener to a button using following methods. I am talking about the the first case. Only this case is not working. Rest other 2 cases are working properly.
    Case 1:
    class MyClass {
         RichCommmandButton btnTest = new RichCommmandButton();
         public MyClass(){
              btnTest.addActionListener(new ActionListener(){
                   public void processAction(ActionEvent event){
    Case 2:
    class MyClass implements ActionListener {
         RichCommmandButton btnTest = new RichCommmandButton();
         public void processAction(ActionEvent event){
    <af:button binding="#{myClassBean.btnTest}" actionListener="#{myClassBean.processAction}"/>
    Case 3:
    class MyClass implements ActionListener {
         RichCommmandButton btnTest = new RichCommmandButton();
         public void addActionLister(){
              //Use EL to add processAction(). Create MethodBinding
              FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory exprfactory = facesContext.getApplication().getExpressionFactory();
              MethodExpression actionListener =
    exprfactory.createMethodExpression(elContext, "#{myClassBean.processAction}", null, new Class[] { ActionEvent.class });
              btnTest.setActionListener(actionListener);
         public void processAction(ActionEvent event){
    Java has provided good way to use the Anonymous classes while adding the listeners. It should work with the RCF also.
    Some how i found the case 1 usefull, as i can have as many buttons in my screen and i can add the actionListener in one method. Also it is easy to read. I dont have to see the JSPX page to find the associated actionListener method.
    Is it a bug or i am wrong at some point?
    Any sujjestions are welcome.
    - Sujay.

    Hello Sujay,
    As I said in my previous reply, you can try with request scope. In JSF you shouldn't use the binding attribute very often. I agree that anonymous class is nice, but don't forget that you might be dealing with client state saving here so it cannot be perfectly compared with Swing that maintains everything in RAM. What I think happens with you currently is the following:
    1. Bean is created and the button instance as well. The ActionListener is added to the button;
    2. The view is rendered and while it is, the binding attribute is evaluated, resulting in the get method of your bean being called;
    3. Since the method returns something different than null, the button instance created in 1. get used in the component tree;
    4. The tree's state is saved on the client, since your class isn't a StateHolder, nor Serializable, the StateManager doesn't know how to deal with it so it gets discarded from the saved state and maybe from the component itself (would have to debug the render view phase to be sure);
    5. The postback request arrives, the tree is restored. When the handler reaches the button, it call the bean that returns the same instance that was used in the previous tree (since not request scoped), which is BAD because the remaining of the tree is not made of the same object instances, but rather new deserialized ones. The component then gets updated from the client state saved in 4, this might also be where the listener get removed (again debugging would tell you this, but I would tend more with the previous possibility). Note that with a request scoped bean you would have to add the listener during the first get method call (by checking if the component is null) or in the constructor as you're doing right now. It would be a very clean way and you could give the request bean (and thus the listener) access to the conversation scoped bean through injection which is very nice as well.
    6. The invoke application phase occurs and the listener is no longer there.
    Btw, this isn't a rich client issue, more a specification one. I'm curious if it works in a simple JSF RI application, if it does then I guess it would be a bug in Trinidad and/or rich client state handling architecture (using FacesBean).
    Regards,
    ~ Simon

  • Cannot dynamically add actionlistener to Tab or TabSet

    Hello,
    I have a custom component that must create a Tabbed look. I'm using the Studio Creator TabSet with Tabs. I cannot for the life of me get it to register and use an actionListener. I've done this with other components, but this plain doesn't work (for me). Has anyone been able to use it this way? I've tried numerous approaches and here is the one that's worked for me in other components....
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    ELContext elContext = FacesContext.getCurrentInstance().getELContext();
    ExpressionFactory expressionFactory = application.getExpressionFactory();
    MethodExpression myActionListener = expressionFactory.createMethodExpression(elContext, "#{SCTabsBean.tabClicked}", null, new Class[] {ActionEvent.class});
    And oh yes, I have used the example code for the Woodstock version and also the old fashioned SC version and neither of them worked in my local environment.
    It is not an option for me to use WoodStock at this time. The woodstock components have a new way of registering the themes and it is too risky for an interim build to do this.
    ..\wb

    Hi,
    I use forms in my tabNavigator:
                    <mx:TabNavigator id="tabNavigator"
                                      creationPolicy="all"
                                      styleName="myTabStyle"
                                      click="selectProfile()"
                                      >
                         <mx:Form id="A" label="A" name="very blue" hideEffect="{hideEffect}"  showEffect="{showEffect}" visible="false" >
                             <mx:Label text="Point" />
                             <mx:NumericStepper id="PointA" name="PointA"  minimum="0" maximum="120" styleName="numStepper" color="white" />   
                         </mx:Form>
                 </mx:TabNavigator>
    This is how I access the form and add values to my UI controls:
                            //find child controls dynamically
                            var formObj:Object = tabNavigator.getChildAt(i);
                            var formPoint:Object = formObj.getChildByName("Point" + "A");
                            formPoint.value = 55;
    I hope this can help put you towards the right direction. This was not easy and tabNavigator is not my friend.

  • How can i add an actionlistener to a JButton?

    I tried b1.addActionListener()But I need to put something in the brackets.
    To which class does add ActionListener belong?

    here is a small program ,,, you can run it and understand it ....
    some people understand the code faster than actual description
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class MyListeningProg1 {
    public static void main(String[] args) {
      JFrame frame = new JFrame("HelloButton");
      Container pane = frame.getContentPane();
      JButton hello = new JButton("Hello, World");
      JButton goodbye = new JButton("Goodbye, World");
      JLabel lab = new JLabel("This is a label");
      ResponseHandler handler = new ResponseHandler();
      hello.addActionListener(handler);
      goodbye.addActionListener(handler);
      pane.setLayout(new GridLayout(3,1));
      pane.add(hello);
      pane.add(goodbye);
      pane.add(lab);
      frame.pack();
      frame.setSize(300, 200);
      frame.show();
    class ResponseHandler implements ActionListener
            public void actionPerformed(ActionEvent e)
       if (e.getActionCommand().equals("Hello, World"))
           System.out.println("This is the first button");
          else
           System.out.println("This is the second button");
    } //end of class ResponseHandlerhope this helped you a little

  • How at add closd function in the JButton??

    Hi, sir:
    I hope to add a closd function in the JButton, ie, like a JPanel or JFrame, there is a "X" sign icon on the right upper coner, when we click this X sign,
    whole window or JPanel or JFrame will be closed, here I hope to add a "x" sign in JButton, when I click it, itthis button b2 will be vanished.
    I update following code, but looks like not work, I hope Text and its icon on the leading Left, but closed sign is on the extreme end of right.
    Can guru help??
    Thanks
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    import javax.swing.SwingConstants;
    import javax.swing.GroupLayout.Alignment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    * ButtonDemo.java requires the following files:
    *   images/right.gif
    *   images/middle.gif
    *   images/left.gif
    public class ButtonDemo2 extends JPanel  implements ActionListener {
        protected JButton  b2,bclosed;
        public ButtonDemo2() {
             Icon closedIcon  = new ImageIcon("images/ActionButton/closed.PNG");
            ImageIcon middleButtonIcon = new ImageIcon("images/little.gif");
            JLabel label1 = new JLabel("Image and Text", middleButtonIcon, JLabel.CENTER);
            bclosed = new JButton(closedIcon);
            bclosed.setBorder(null);
            bclosed.setToolTipText("closed");
            b2 = new JButton("Middle button", middleButtonIcon);
            b2.setText("Middle button");
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.add(bclosed, -1);
            b2.setIcon(middleButtonIcon);
            b2.setHorizontalTextPosition(AbstractButton.LEFT);
            b2.setAlignmentX(LEFT_ALIGNMENT);
            b2.setMnemonic(KeyEvent.VK_M);
              b2.setToolTipText("This middle button does nothing when you click it.");
            //Add Components to this container, using the default FlowLayout.
            add(label1);
            add(b2);
        public void actionPerformed(ActionEvent e) {
            if ("disable".equals(e.getActionCommand())) {
                b2.setEnabled(false);
            } else {
                b2.setEnabled(true);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("ButtonDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            ButtonDemo2 newContentPane = new ButtonDemo2();
            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) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Thanks, I add as follows:
    package a.border;
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    import javax.swing.SwingConstants;
    import javax.swing.GroupLayout.Alignment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    * ButtonDemo.java requires the following files:
    *   images/right.gif
    *   images/middle.gif
    *   images/left.gif
    public class ButtonDemo2 extends JPanel  implements ActionListener {
        protected JButton  b2,bclosed;
        public ButtonDemo2() {
             Icon closedIcon  = new ImageIcon("images/ActionButton/closed.PNG");
            ImageIcon middleButtonIcon = new ImageIcon("images/little.gif");
            JLabel label1 = new JLabel("Image and Text", middleButtonIcon, JLabel.CENTER);
            bclosed = new JButton(closedIcon);
            bclosed.setBorder(null);
            bclosed.setToolTipText("closed");
            bclosed.setActionCommand("closed");
            b2 = new JButton("Middle button", middleButtonIcon);
            b2.setText("Middle button");
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.add(bclosed, -1);
            b2.setIcon(middleButtonIcon);
            b2.setHorizontalTextPosition(AbstractButton.LEFT);
            b2.setAlignmentX(LEFT_ALIGNMENT);
            b2.setMnemonic(KeyEvent.VK_M);
            bclosed.addActionListener(this);
            b2.setToolTipText("This middle button does nothing when you click it.");
            //Add Components to this container, using the default FlowLayout.
            add(label1);
            add(b2);
        public void actionPerformed(ActionEvent e) {
            if ("disable".equals(e.getActionCommand())) {
                b2.setEnabled(!b2.isEnabled());
            if             ("closed".equals(e.getActionCommand())) {
                  System.out.println("OK closed is pressed");
                  remove(b2);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("ButtonDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            ButtonDemo2 newContentPane = new ButtonDemo2();
            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) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }But I cannot see the First Image I add in b2 such as little.gif and "Image and Text" on it, only I can see bclosed icon.
    what is wrong here??
    Thanks a lot
    Good weekend

  • How can I add  several  JButton into JList?

    I want to add several button into a Jlist. I tried this method, list.add(button,1),nothing shows up.I am not sure whether jList has the function.If it is,please show me how to achieve that.Thanks in advance!

    A JList is used to display text Strings. You should be able to add a JButton to the JList but all you will see is the toString() representation of the JButton. You will not see a button or be able to click on it.
    Try creating a panel using a GridLayout with a single column and add all you JButtons to the panel.

  • How do i use jbutton for mutiple frames(2frames)???

    im an creating a movie database program and i have a problem with the jButtons on my second frame i dont know how to make them work when clicked on. i managed to make the jButtons work on my first frame but not on the second....
    here is that code so far----
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    * real2.java
    * Created on December 7, 2007, 9:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author J
    public class real2 extends JPanel  implements ActionListener{
        private JButton addnew;
        private JButton help;
        private JButton exit;
        private JFrame frame1;
        private JButton save;
        private JButton cancel;
        private JButton save2;
        private JLabel moviename;
        private JTextField moviename2;
        private JLabel director;
        private JTextField director2;
        private JLabel year;
        private JTextField year2;
        private JLabel genre;
        private JTextField genre2;
        private JLabel plot;
        private JTextField plot2;
        private JLabel rating;
        private JTextField rating2;
        /** Creates a new instance of real2 */
        public real2() {
            super(new GridBagLayout());
            //Create the Buttons.
            addnew = new JButton("Add New");
            addnew.addActionListener(this);
            addnew.setMnemonic(KeyEvent.VK_E);
            addnew.setActionCommand("Add New");
            help = new JButton("Help");
            help.addActionListener(this);
            help.setActionCommand("Help");
            exit = new JButton("Exit");
            exit.addActionListener(this);
            exit.setActionCommand("Exit");
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(600, 100));
            table.setFillsViewportHeight(true);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 1;
            c.gridx = 0;
            c.gridy = 1;
            add(addnew, c);
            c.gridx = 0;
            c.gridy = 2;
            add(help, c);
            c.gridx = 0;
            c.gridy = 3;
            add(exit, c);
        public static void addComponentsToPane(Container pane){
            pane.setLayout(null);
            //creating the components for the new frame
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            JButton cancel = new JButton("Cancel");
            JLabel moviename= new JLabel("Movie Name");
            JTextField moviename2 = new JTextField(8);
            JLabel director = new JLabel("Director");
            JTextField director2 = new JTextField(8);
            JLabel genre = new JLabel("Genre");
            JTextField genre2 = new JTextField(8);
            JLabel year = new JLabel("year");
            JTextField year2 = new JTextField(8);
            JLabel plot = new JLabel("Plot");
            JTextField plot2 = new JTextField(8);
            JLabel rating = new JLabel("Rating(of 10)");
            JTextField rating2 = new JTextField(8);
            //adding components to new frame
            pane.add(save);
            pane.add(save2);
            pane.add(cancel);
            pane.add(moviename);
            pane.add(moviename2);
            pane.add(director);
            pane.add(director2);
            pane.add(genre);
            pane.add(genre2);
            pane.add(year);
            pane.add(year2);
            pane.add(plot);
            pane.add(plot2);
            pane.add(rating);
            pane.add(rating2);
            //setting positions of components for new frame
                Insets insets = pane.getInsets();
                Dimension size = save.getPreferredSize();
                save.setBounds(100 , 50 ,
                         size.width, size.height);
                 size = save2.getPreferredSize();
                save2.setBounds(200 , 50 ,
                         size.width, size.height);
                 size = cancel.getPreferredSize();
                cancel.setBounds(400 , 50 ,
                         size.width, size.height);
                 size = moviename.getPreferredSize();
                moviename.setBounds(100 , 100 ,
                         size.width, size.height);
                size = moviename2.getPreferredSize();
                moviename2.setBounds(200 , 100 ,
                         size.width, size.height);
                 size = director.getPreferredSize();
                director.setBounds(100, 150 ,
                         size.width, size.height);
                 size = director2.getPreferredSize();
                director2.setBounds(200 , 150 ,
                         size.width, size.height);
                size = genre.getPreferredSize();
                genre.setBounds(100 , 200 ,
                         size.width, size.height);
                 size = genre2.getPreferredSize();
                genre2.setBounds(200 , 200 ,
                         size.width, size.height);
                 size = year.getPreferredSize();
                year.setBounds(100 , 250 ,
                         size.width, size.height);
                size = year2.getPreferredSize();
                year2.setBounds(200 , 250 ,
                         size.width, size.height);
                 size = plot.getPreferredSize();
                plot.setBounds(100 , 300 ,
                         size.width, size.height);
                 size = plot2.getPreferredSize();
                plot2.setBounds(200 , 300 ,
                         size.width, size.height);
                size = rating.getPreferredSize();
                rating.setBounds(100 , 350 ,
                         size.width, size.height);
                 size = rating2.getPreferredSize();
                rating2.setBounds(200 , 350 ,
                         size.width, size.height);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            frame.add(new real2());
            //Display the window.
            frame.setSize(600, 360);
            frame.setVisible(true);
            frame.pack();
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void actionPerformed(ActionEvent e) {
            if ("Add New".equals(e.getActionCommand())){
               frame1 = new JFrame("add");
               frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
               addComponentsToPane(frame1.getContentPane());
               frame1.setSize(600, 500);
               frame1.setVisible(true);
                //disableing first frame etc:-
                if (frame1.isShowing()){
                addnew.setEnabled(false);
                help.setEnabled(false);
                exit.setEnabled(true);
                frame1.setVisible(true);
               }else{
                addnew.setEnabled(true);
                help.setEnabled(true);
                exit.setEnabled(true);           
            if ("Exit".equals(e.getActionCommand())){
                System.exit(0);
            if ("Save".equals(e.getActionCommand())){
                // whatever i ask it to do it wont for example---
                help.setEnabled(true);
            if ("Save" == e.getSource()) {
                //i tried this way too but it dint work here either
                help.setEnabled(true);
    }so if someone could help me by either telling me what to type or by replacing what iv done wrong that would be great thanks...

    (1)Java class name should begin with a capital letter. See: http://java.sun.com/docs/codeconv/
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            // ... etc. ...(2)Don't redeclare class members in a method as its local variable. Your class members become eternally null, a hellish null.
    how to make them work when clicked on(3)Add action listener to them.

  • Please add keyboard focus events to swing calculator.  Its very argent.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    A frame with a calculator panel.
    class CalculatorFrame1 extends JFrame
         private static final long serialVersionUID=0;
    public CalculatorFrame1()
    setTitle("Calculator");
    Container contentPane = getContentPane();
    CalculatorPanel panel = new CalculatorPanel();
    contentPane.add(panel);
    pack();
    setVisible(true);
    public static void main(String[] args)
    CalculatorFrame1 frame = new CalculatorFrame1();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.show();
    A panel with calculator buttons and a result display.
    class CalculatorPanel extends JPanel implements KeyListener
    private static final long serialVersionUID=0;
    private JTextField display;
    private JPanel panel;
    private double result;
    private String lastCommand;
    private boolean start;
    public CalculatorPanel()
    setLayout(new BorderLayout());
    result = 0;
    lastCommand = "=";
    start = true;
    // add the display
    display = new JTextField("");
    // display.addKeyListener(this);
    // display.addKeyListener(this);
    add(display, BorderLayout.NORTH);
    display.setFocusable(true);
    ActionListener insert = new InsertAction();
    ActionListener command = new CommandAction();
    // add the buttons in a 4 x 4 grid
    panel = new JPanel();
    panel.setLayout(new GridLayout(5, 4));
    addButton("7", insert);
    addButton("8", insert);
    addButton("9", insert);
    addButton("/", command);
    addButton("4", insert);
    addButton("5", insert);
    addButton("6", insert);
    addButton("*", command);
    addButton("1", insert);
    addButton("2", insert);
    addButton("3", insert);
    addButton("-", command);
    addButton("0", insert);
    addButton(".", insert);
    addButton("=", command);
    addButton("+", command);
    addButton("Clear", command);
    add(panel, BorderLayout.CENTER);
    //this.addKeyListener(this);
    Adds a button to the center panel.
    @param label the button label
    @param listener the button listener
    private void addButton(String label, ActionListener listener)
    JButton button = new JButton(label);
    button.addActionListener(listener);
    panel.add(button);
    This action inserts the button action string to the
    end of the display text.
    private class InsertAction implements ActionListener
    public void actionPerformed(ActionEvent event)
    String input = event.getActionCommand();
    if (start)
    display.setText("");
    start = false;
    display.setText(display.getText() + input);
    This action executes the command that the button
    action string denotes.
    private class CommandAction implements ActionListener
    public void actionPerformed(ActionEvent evt)
    String command = evt.getActionCommand();
    // System.out.println("The value clear"+command);
    if (command.equals("Clear"))
              display.setText("");
              start = false;
    else
    if (start)
    if (command.equals("-"))
    display.setText(command);
    start = false;
    else
    lastCommand = command;
    else
    calculate(Double.parseDouble(display.getText()));
    lastCommand = command;
    start = true;
    Carries out the pending calculation.
    @param x the value to be accumulated with the prior result.
    public void calculate(double x)
    if (lastCommand.equals("+")) result += x;
    else if (lastCommand.equals("-")) result -= x;
    else if (lastCommand.equals("*")) result *= x;
    else if (lastCommand.equals("/")) result /= x;
    else if (lastCommand.equals("=")) result = x;
    display.setText("" + result);
    public void keyTyped(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         int id = e.getID();
         String keyString="";
         System.out.println("The value KeyEvent.KEY_TYPED"+KeyEvent.KEY_TYPED);
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    //System.out.println("The value c"+c);
    if(c=='*' || c=='/' || c=='-'||c=='+' || c=='=')
         start = true;
    else
         start = false;
         keyString = display.getText()+ c ;
         System.out.println("The value keyString"+keyString);
    else {
    calculate(Double.parseDouble(display.getText()));
    start = true;
    display.setText(keyString);
    public void keyPressed(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         String keyString;
    int id = e.getID();
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    keyString = "key character = '" + c + "'";
    } else {
    int keyCode = e.getKeyCode();
    keyString = "key code = " + keyCode
    + " ("
    + KeyEvent.getKeyText(keyCode)
    + ")";
    display.setText("keyPressed:::"+keyString);**/
    public void keyReleased(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         String keyString;
    int id = e.getID();
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    keyString = "key character = '" + c + "'";
    } else {
    int keyCode = e.getKeyCode();
    keyString = "key code = " + keyCode
    + " ("
    + KeyEvent.getKeyText(keyCode)
    + ")";
    display.setText("keyReleased:::"+keyString);**/
    }

    Please state why the question is urgent?
    You where given a suggestion 7 minutes after you posted the question, yet it has been over 2 hours and you have not yet responded indicating whether the suggest helped or not.
    So I gues its really not the urgent after all and therefore I will ignore the question.
    By the way, learn how to use the "Code Formatting Tags" when you post code, so the code you post is actually readable.

  • How can I associate an ActionListener with a specific button

    I modified the code a lot. Everything works except that it does not associate the actionListener with the button. It will do the action when the window is minimized or maximized, but not when the button is clicked.
    //July 2, 2011
    //Multiplication Tables
    import java.applet.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MultTables extends JApplet implements ActionListener
         //Create Variables for Multiplication Problems
         int factorX = 1;
         int factorY = 1;
         int productZ = 1;
         int productReply;
         //Create the TextField
              JTextField answer = new JTextField(10);
         //Create Labels and buttons
              JLabel productZLabel = new JLabel(factorX + " * " + factorY + " = ");
              JButton checkAnswer = new JButton("Check Answer");
         //Create a container
              Container con = getContentPane();
              FlowLayout flow = new FlowLayout();
         public void init()
              //What goes init? What needs to be added to the interface?
              con.setLayout(flow);
              //Add Components and create interface
              con.add(productZLabel);
              con.add(answer);
              con.add(checkAnswer);
              //Add ActionListener to button
              checkAnswer.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              productZ = factorX * factorY;
              String productReplyString = (answer.getText());
              productReply = (Integer.valueOf(productReplyString));
              for(int sub = 1; sub <= 9; ++sub);
              if (productReply == productZ)
                   JLabel correct = new JLabel("That is correct!");
                   con.remove(productZLabel);
                   con.remove(answer);
                   con.remove(checkAnswer);
                   con.add(correct);
                   ++factorX;
              else
                   JLabel incorrect = new JLabel("The correct answer is " + productZ);
                   con.remove(productZLabel);
                   con.remove(answer);
                   con.remove(checkAnswer);
                   con.add(incorrect);
                   ++factorX;
    }

    EJP wrote:
    Are you sure you're running that code? It should work. ActionListeners don't respond to min/max events.Yup. But the repaint triggered by resizing updates the display.
    db

  • How to add an image to JFrame....

    Hello evryone,
    Here i'm posting my code..and in this i would like to add a .jpg file as background..I hav tried for imageicon and Bufferdimage...
    Help me out...
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    import java.lang.*;
    import java.awt.image.*;
    import java.awt.Container.*;
    import java.io.FileInputStream.*;
    import java.io.*;
    import javax.imageio.*;
    public class Kbc extends JFrame implements ActionListener
    Container c;
    JButton b1,b2,b3;
    JLabel l;
    public Kbc()
    c = getContentPane() ;
    c.setLayout(null) ;
    l=new JLabel("--:WeLcoMe :--");
    Font f = new Font("Dialog", Font.PLAIN, 24);
    l.setFont(f);
    l.setBounds(300,30,1100,20);
    c.add(l);
    b1=new JButton("START");
    b1.setFont(f);
    b1.setPreferredSize( new Dimension(200,100) ) ;
    b1.setSize( b1.getPreferredSize() ) ;
    b1.setLocation(350,100) ;
    b1.addActionListener(this) ;
    c.add(b1) ;
    b2=new JButton("QUIT");
    b2.setFont(f);
    b2.setPreferredSize( new Dimension(200,100) ) ;
    b2.setSize( b2.getPreferredSize() ) ;
    b2.setLocation(350,210) ;
    b2.addActionListener(this) ;
    c.add(b2) ;
    b3=new JButton("HELP");
    b3.setFont(f);
    b3.setPreferredSize( new Dimension(200,100) ) ;
    b3.setSize( b3.getPreferredSize() ) ;
    b3.setLocation(350,320) ;
    b3.addActionListener(this) ;
    c.add(b3) ;
    setSize(1100,700);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if(e.getSource()==b1)
    new Start1();
    this.hide();
    else
    if(e.getSource()==b2)
    System.exit(0);
    if(e.getSource()==b3)
    JOptionPane.showMessageDialog(c,"RuLes"");
    public static void main(String args[])
    Kbc k=new Kbc();
    /*<applet code="Kbc" height=500 width=900>
    </applet>*/
    {code}{code}

    Hi,
    extends JFrame is application.
    If applet extends JApplet.
    Here is an example of the application.
    Please run this way java Kbc test.jpg
    test.jpg is the background image. Please change file name.
    public class Kbc extends JPanel implements ActionListener {
    private JButton b1, b2 , b3 ;
    private JLabel l ;
    static private String filename ;
    private Image image ;
    private JLayeredPane layeredPane ;
    public Kbc() {
         layeredPane = new JLayeredPane() ;
         layeredPane.setPreferredSize( new Dimension(1100,700) ) ;
    l=new JLabel(":Wellcome :");
    Font f = new Font("Dialog", Font.PLAIN, 24);
    l.setFont(f);
    l.setBounds(300,30,1100,20);
    layeredPane.add(l, new Integer( 3 ) );
    b1=new JButton("START");
    b1.setFont(f);
    b1.setPreferredSize( new Dimension(200,100) ) ;
    b1.setSize( b1.getPreferredSize() ) ;
    b1.setLocation(350,100) ;
    b1.addActionListener(this) ;
    layeredPane.add(b1,new Integer( 1 ) ) ;
    b2=new JButton("QUIT");
    b2.setFont(f);
    b2.setPreferredSize( new Dimension(200,100) ) ;
    b2.setSize( b2.getPreferredSize() ) ;
    b2.setLocation(350,210) ;
    b2.addActionListener(this) ;
    layeredPane.add(b2, new Integer( 2 ) ) ;
    b3=new JButton("HELP");
    b3.setFont(f);
    b3.setPreferredSize( new Dimension(200,100) ) ;
    b3.setSize( b3.getPreferredSize() ) ;
    b3.setLocation(350,320) ;
    b3.addActionListener(this) ;
    layeredPane.add(b3, new Integer( 5 )) ;
    add( layeredPane);
    public void paintComponent (Graphics g) {
              super.paintComponent(g);
    try {
    File f = new File(filename);
    BufferedImage image = ImageIO.read(f);
    g.drawImage(image, 0, 0, this);
    } catch (Exception ex) {
    ex.printStackTrace();
    public void actionPerformed(ActionEvent e) {
    if (e.getSource()==b1)
    // new Start1();
    this.setVisible(false) ;
    else if (e.getSource()==b2) {
    System.exit(0);
    } else if (e.getSource()==b3) {
    JOptionPane.showMessageDialog(this,"RuLes");
    public static void main(String args[]) {
    filename = args[0] ;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    private static void createAndShowGUI() {
    System.out.println("Created GUI on EDT? "+
    SwingUtilities.isEventDispatchThread());
         Kbc k=new Kbc();
    JFrame frame = new JFrame("Kbc");
         frame.add(k);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(1100, 700 ) );
    frame.setVisible(true);
    }

Maybe you are looking for