Problem handling ActionEvent in JButton

I am having a peculiar while handling an ActionEvent associated with a JButton okB.
Here is the code:
okB.addActionListener (
     new ActionListener()
          public void actionPerformed(ActionEvent e)
               System.out.println("Triggering Action");
               saveProgress();
               controlPanel.remove(buttonPanel);
               controlPanel.remove(slider);
               messageLabel.setText("Click on a button to perform an operation");
               repaint();
);Here I am trying to call a method to perform some operations and then remove some components from the panel containing them.
Everything is working fine except one peculiar problem. The code inside the actionPerformed method is running more than once. When I click "OK" button for the first time, the actionPerformed is looping 1 time, when I click it for the second time, its looping 2 times. I confirmed this through the println code. I removed the problem through a loop control variable as follows:
loopCOntrol = true;
okB.addActionListener (
     new ActionListener()
          public void actionPerformed(ActionEvent e)
               if(loopControl)
                    loopControl = false;
                    saveProgress();
                    controlPanel.remove(buttonPanel);
                    controlPanel.remove(slider);
                    messageLabel.setText("Click on a button to perform an operation");
                    repaint();
);Though this code is working correctly, still it is sort of a patch to the problem which I dont like. Is there any explanation for the problem?

You are probably re-adding the listener somewhere. This would cause you to get one more event notice each time

Similar Messages

  • Problem with setCursor for JButton in cell on JTable

    i have a problem with setCursor to JButton that is in a cell of the JTable}
    this is the code
    public class JButtonCellRenderer extends JButton implements TableCellRenderer {
    public JButtonCellRenderer() {
    setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    else {
    setForeground(table.getForeground());
    setBackground(Color.WHITE);
    setBorder(null);
    if(table.getValueAt(row,column) == null){
    setText("");
    if(isSelected){
    setBackground(table.getSelectionBackground());
    }else{
    setBackground(Color.WHITE);
    }else{
    if(table.getValueAt(row,column) instanceof JButton){
    JButton _button = (JButton)table.getValueAt(row,column);
    if(_button.getText().trim().equals("")){
    setText("<html>"+ "<font size=\"3\" COLOR=\"#0000FF\"><u><b>Ver...</b></u></font>"+"");
    }else{
    setText("<html>"+ "<font size=\"3\" COLOR=\"#0000FF\"><u><b>" + _button.getText() + "</b></u></font>"+"");
    return this;
    }

    Not quite sure I understand the problem, but I guess you have tried to call setCursor on your renderer and found it didn't work? The reason, I think, is that the renderer only renders a JButton. The thing that ends up in the table is in fact only a "picture" of a JButton, and among other things it won't receive and interact with any events, such as MouseEvents (so it wouldn't know that the cursor should change).
    There are at least two alternatives for you: You can perhaps use a CellEditor instead of a CellRenderer. Or you can add a MouseListener to the table and then use the methods column/rowAtPoint to figure out if the cursor is over your JButton cell and change the cursor yourself if it is.

  • Problem while creating a JButton with an Icon

    Hello,
    I'm experiencing a problem while setting an Icon to a JButton. Here is my code :
    Icon icon = new ImageIcon("TRONCONCIRC1.gif");
            JButton switchTypeButton = new JButton();
            switchTypeButton.setIcon(icon);
            switchTypeButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        // Some Action
         });The button works well, but there is no icon on it.
    Does anyone have an idea ?
    thanks,

    Icon icon = new ImageIcon("TRONCONCIRC1.gif");
       //I thinks that the only problem it can be is that there is a wrong path
       //to your icon. Try tthe following. I am right if this will write null.
    System.out.println(icon);
    JButton switchTypeButton = new JButton();
    switchTypeButton.setIcon(icon);
    switchTypeButton.addActionListener(new
    ener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        // Some Action
         });

  • Problem with KeyAdapter and JButtons in a Jframe

    yes hi
    i have searched almost most of the threads here but nothing
    am trying to make my frame accepts keypress and also have some button on the frame here is the code and thank you for the all the help
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPg extends JFrame implements ActionListener
                private int width;
                private int hight;
                public    JPanel north;
                public    JPanel se;
                public    JButton start;
                public    JButton quit;
                public    Screen s;//a Jpanel
                public    KeyStrokeHandler x;
        public RPg() {
               init();
               setTitle("RPG");
               setSize(width,hight);
               setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               setResizable(false);
               setVisible(true);
               x=new KeyStrokeHandler();
             addKeyListener(x);
             public void init() {
               north=new JPanel();
               Container cp = getContentPane();
               s=new Screen();
               this.width=s.width;
               this.hight=s.hight+60;
              start=new JButton("START");
                  start.addActionListener(this);
              quit=new JButton("QUIT");
                  quit.addActionListener(this);
              north.setBackground(Color.DARK_GRAY);
              north.setLayout(new FlowLayout());
              north.add(start);
              north.add(quit);
              cp.add(north, BorderLayout.NORTH);
              cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPg rpg = new RPg();
       public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
       class KeyStrokeHandler extends KeyAdapter {
               public void keyTyped(KeyEvent ke) {}
               public void keyPressed(KeyEvent ke){
                  int keyCode = ke.getKeyCode();
                  if ((keyCode == KeyEvent.VK_M)){
                     System.out.println("it works");
               public void keyReleased(KeyEvent ke){}

    Use the 'tab' key to navigate through 'contentPane > start > quit' focus cycle. 'M' key works when focus is on contentPane (which it is on first showing). See tutorial pages on 'Using Key Bindings' and 'Focus Subsystem' for more.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPG extends JFrame implements ActionListener {
        private int width;
        private int hight;
        public JPanel north;
        public JPanel se;
        public JButton start;
        public JButton quit;
        public Screen s;    //a Jpanel
        public RPG() {
            init();
            setTitle("RPG");
            setSize(width,hight);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setResizable(false);
            setVisible(true);
        public void init() {
            north=new JPanel();
            Container cp = getContentPane();
            registerKeys((JComponent)cp);
            s=new Screen();
            this.width=s.width;
            this.hight=s.hight+60;
            start=new JButton("START");
                start.addActionListener(this);
            quit=new JButton("QUIT");
                quit.addActionListener(this);
            north.setBackground(Color.DARK_GRAY);
            north.setLayout(new FlowLayout());
            north.add(start);
            north.add(quit);
            cp.add(north, BorderLayout.NORTH);
            cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPG rpg = new RPG();
        public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
        private void registerKeys(JComponent jc)
            jc.getInputMap().put(KeyStroke.getKeyStroke("M"), "M");
            jc.getActionMap().put("M", mAction);
        Action mAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("it works");
    class Screen extends JPanel {
        int width, hight;
        public Screen() {
            width = 300;
            hight = 300;
            setBackground(Color.pink);
    }

  • Problem handling JFileChooser events...

    The problem I have is rather tricky to explain. I feel maybe I'm treading on an area I'm not ready for yet... but here goes:
    I have a JInternalFrame with an "open" button which triggers the JFileChooser and underneath a text field to log activity. My goal is simply to have a String array of all the filenames selected ( one at a time, whilst adding to the array ).
    All seems well to start with. I have a System.out.println running after each filename is added to the array, and it verifies that they are being added successfully.
    The problem comes just after that... When I call for the String array, it appears to be empty!
    I'm sure that this will be a foolish mistake on my behalf, but still, I'm yet to spot it!
    this is the code where the filenames are added to the array:
    public void actionPerformed(ActionEvent e) {
                if (e.getSource() == openButton) {
                int returnVal = fc.showOpenDialog(FileSelector.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                str[a] = file.getName();
                a++;
                   log.append("File: " + file.getName() + " added to list" + newline);
            } else {
                   log.append("Open command cancelled by user." + newline);
               log.setCaretPosition(log.getDocument().getLength());
         System.out.println(str);
    }I'm not sure what other bits of code are needed, so ill hold fast.
    cheers in advance for any help.
    John.

    The error message says it all:
    "java.lang.IllegalArgumentException: cannot add to layout: constraints must be a GridBagConstraint"
    You are apparently adding something to a panel that uses a GridBagLayout, but the constraint you are specifying is not a GridBagConstraints.
    JPanel pnl = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    pnl.add(new JLabel("correct"), c);
    pnl.add(new JLabel("wrong"), BorderLayout.CENTER);The second add in the above code will cause the error you are getting. This would also explain why it works when you are using a BorderLayout.
    Here is the relevant code:The code you posted was not the relevant code. The relevant code is what takes place in your button's ActionListener. There you call the method gotoNextSection(), which you did not post.

  • Problem handling error messages in Axis

    I am consuming a web service, and all calls work fine. However, when the web service raises an error (for example I pass the wrong login), my Java application returns the following:
    java.lang.ClassCastException: org.apache.axis.message.Text
    The error soap packet that gets returned looks fine, but the Java (or Axis) can't seem to parse out the error message. I am doing a simple catch
    catch(Exception e){
              System.out.print(e.getCause());
    Here is an example of a Soap message it couldn't parse:
    HTTP/1.1 500 Internal Server Error
    Connection: close
    Date: Tue, 16 Aug 2005 19:59:50 GMT
    Server: Microsoft-IIS/6.0
    X-Powered-By: ASP.NET
    Content-Type: text/xml
    Connection: Keep-Alive
    Content-Length: 366
    <SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP:Body>
    <SOAP:Fault>
    <faultcode>SOAP:Server</faultcode>
    <faultstring>Unable to authenticate technician. Either the Technician ID or password is incorrect, or there is more than one technician with submitted credentials.</faultstring>
    <detail>1030</detail>
    </SOAP:Fault>
    </SOAP:Body></SOAP:Envelope>
    I've tried all versions of Axis and keep getting the same problem. Am I catching the wrong type of Exception? Does the SOAP packet look weird? Is there something special I need to do when creating the classes from the WSDL2Java? Some setting?
    I don't know. Thanks.

    The format of the SOAP Fault is valid, and can be properly deserialized using oc4j DP4 release.
    Maybe you are having trouble in the processing of the detail element; the message.Text axis is complening about.
    Instead of catching a generic Exception, try catching javax.xml.rpc.soap.SOAPFaultException. Then, you will have accessor for each part of the fault. Based on your sample fault, the following code:
    } catch (SOAPFaultException sfe) {
    System.out.println("Expected error: " + sfe.getFaultString());
    outputs:
    Expected error: Unable to authenticate technician. Either the Technician ID or password is incorrect, or there is more than one technician with submitted credentials.
    Process exited with exit code 0.
    Hope this helps,
    eric

  • ITunes 8.2 has problems handling larger music files

    Hi,
    After upgrading to iTunes 8.2, I have begun to notice that the program is halted with larger mp3 files. I have quite a lot of music files with size 200MB and above and before opening them, iTunes stops for about 10-15 seconds (with "beach ball" on the screen), then the playback starts normally. This is not an actual problem, but pretty annoying though. iTunes 8.2 behaves in the same way both on my black MacBook, as well as on my oldie G4 iMac running Tiger. Never noticed such a behaviour with earlier 8.1 version of iTunes.
    Has anyone encountered similar problem and could there be any remedy? Thanks in advance.
    Cheers,
    Matt

    iso_omena,
    I can't duplicate your problem here, so maybe there's something about your machine or the software installed on it. Do you have any iTunes plugins installed?
    You can also take a sample of iTunes while it's hung and send it to our good buddy, Roy, who will forward it to the right Apple engineers. To sample iTunes:
    1. Open the terminal app in /Applications/Utilities
    2. Get iTunes into the state where you have the spinning cursor and the music's not playing.
    3. At the command prompt in the terminal window, type in "sample iTunes 10". This will sample iTunes for 10 seconds and then tell you where it put the output file.
    4. You need to send that file to <[email protected]>. Make sure that you include:
    (1) the sample file.
    (2) the link to this thread.
    (3) a one line description of your problem, i.e. "iTunes crashes on launch".
    (4) the username that you're using here in the discussion boards.
    Roy is getting a little swamped with messages and needs to make sure he gets all the information. And if he doesn't get that information, the message is just going to get dropped on the floor.

  • ActionListener: Thread problem in JApplet with JButton?

    Sorry for crossposting, this is my first question on this list, and I posted my question in the "Applet Development" section first. Then I discovered that there is a SWING category as well, which is closer to my problem. So please read about my problem behind this link:
    http://forum.java.sun.com/thread.jspa?threadID=634757
    Thank you very much
    Jan

    Marcin,
    you pointed me in the right direction: I put the .java file in a fresh project and checked the bin folder: And there it was: The missing (second) file the VM was complaining about. I had just forgotten to put all the respective .class files in the webdirectory. Now it works (for a start) with these two files in the webdirectory. I will improve this by creating a jar and Manifest file soon.
    Thanks again
    Jan
    PS: This was truly an (applet) newbie mistake, sorry :-(

  • Problem handling data_changed event in OO ALV

    I'm displaying my internal table with an OO ALV and I'm trying to handle the data_changed event in order to do some checking before actually modify my internal table.
    this is the code of how I was planing to do that:
    handle_data_changed
            FOR EVENT data_changed OF cl_gui_alv_grid
                IMPORTING er_data_changed
                          e_onf4
                          e_onf4_before
                          e_onf4_after
                          e_ucomm.
    METHOD handle_data_changed.
    *    IF er_data_changed->mt_mod_cells-fieldname = 'COD_M'.
    *         do something
    *    else if er_data_changed->mt_mod_cells-fieldname = 'QUANTIDADE'.
    *         do something else
    *    endif.
    *  alv->refresh_table_display.
      ENDMETHOD.                           "handle_data_changed
    but it gives me this error:
    "MT_MOD_CELLS" is a table without a header line and therefore has no component called "FIELDNAME".
    My question is, how can access the cell that is being modified, and the new data?

    Dont know if this is the most clever way to do it but i solved it like this
    DATA: wa_data_changed TYPE lvc_s_modi,
              wa_tabi TYPE zsl_mat_c.
        READ TABLE er_data_changed->mt_mod_cells INDEX 1
                                                 INTO wa_data_changed.
        IF wa_data_changed-fieldname = 'COD_M'.
    *     do something
        ELSEIF wa_data_changed-fieldname = 'QUANTIDADE'.
    *     do something else
        ENDIF.
    thanks for your help

  • Problem handling SMTP address with OIM 11gR2 Exchange connector

    Hello,
    I have a problem in regarding the primary SMTP address with the Exchange connector. The connector doesn't seem to be able to update it. Changing a user's primary SMTP address from its account details in OIM creates a new secondary address in Exchange. It does not change the current primary SMTP address. This does not look like a normal behavior... Any ideas on how to fix this?
    I'm using OIM 11gR2 with BP10 with AD 11.1.1.5.0A and Exchange 11.1.1.5.0.
    Thanks,
    --jtellier

    Yes, you can try out few things suggested in below thread
    Re: Exchange Provisioning
    The error looks like form exchange server side but still not sure about it.
    Meantime open Service Request with oracle about the same as I can see other developers are also facing same issue.

  • Spark Datagrid on a mobile application, problem handling scrolling

    I  have a spark datagrid on a mobile application, I set the
    interactionMode="touch"
    and the dataGrid scrolling is good, I got some problems adding a selectionChange eventListener to it, because scrolling the dataGrid will automatically change the selection and instead simply scrolling it, the function binded will start...
    How can I prevent that?
    <s:DataGrid id="lista"  top="350" bottom="50" right="0" left="0"
    dataProvider="{listaPdv}"
    verticalScrollPolicy="auto"
    rowHeight="100"
    selectionColor="#b64947"
    skinClass="skins.dataGridSkin"
    itemRenderer="components.dataGridItemRendererText"
    fontFamily="Verdana"
    fontSize="30"
    interactionMode="touch"
    horizontalScrollPolicy="auto"
    selectionChange="datagrid_select(event)">
    Help... It's really annoying and I cannot scroll the datagrid...

    I solved using a workaround... instead of binding the selectionChange event, I binded the mouseDown and mouseUp then check the time between the two actions and if the time is less then a defined value the selectionChange event is dispatched...
    <s:DataGrid id="grigliaData"
       sortableColumns="false"
       rowHeight="100"
       interactionMode="touch"
       mouseDown="grigliaData_mouseDownHandler(event)"
       mouseUp="grigliaData_mouseUpHandler(event)"
       top="230" left="5" right="5" bottom="50"
       dataProvider="{listaEventi}" width="100%" height="100%">
      //AS Code
            private var _lastClickEvent:int;
            protected function grigliaData_mouseDownHandler(event:MouseEvent):void
                _lastClickEvent = getTimer();
            protected function grigliaData_mouseUpHandler(event:MouseEvent):void
                if (getTimer() < _lastClickEvent + 200) // 200 = Dalay
                                   // return selectedIndex

  • Why is my Mac having problems handling ProTools?

    Hello, I had a Mac-Mini built last year with their available I7 processor and I have installed 16gb of RAM and installed an Samsung Evo-Pro 840 SSD. The unit works very smoothly with noticeable differences with the upgrades.
    This was built for audio production using ProTools 11, different plug-ins and virtual instruments using software to program or the use of a USB to MIDI keyboard.
    Within the great big world of audio production I am not using, or so I think, a large amount programs running at the same time. By that I mean PT and 2 to 3 plugins and a virtual instrument. The interface is a Mackie 1640I for A to D conversion. I also use a Kemper Modeling amp where all of the programming and hardware are fully separated from my DAW.
    The problem. It is very simple. This amount of demand seems to be too much for the hardware as I experience increased latency and very slow response at times from programs that work just fine until another plug-in is added.
    I have gone into my start up program list to find it strangely very short, listing only a few very basic programs running in the background. There is NO way I could get into a full fledged Mac at $3000 for what I am doing and quite frankly I think that I am missing something very basic here or I just am not informed enough to make an intelligent assessment.
    What about over clocking this machine? Is this possible and or desirable?
    Thank you to anyone who might take time to add their comments, opinions and experience.

    For one thing, you posted in the 10.4 forum.   Since that can't run on a Mac made last year, and your signature says 2013, I take it you are running a more modern version of Protools.   I suggest visiting this website to see what minimum hardware you can use depending on your version of Protools:
    http://avid.force.com/pkb/articles/en_US/Compatibility/en352429?retURL=%2Fpkb%2F articles%2Fen_US%2Fcompatibility%2Fen419171&popup=true
    And then visit the Protools forum:
    http://duc.avid.com/

  • WebLogic Handler Problem - Handler handleMessage is not getting invoked!

    Hi, I am using weblogic 11g and trying to register a handler to log my requests/responses to and from the service. I use Maven to build the project and register the handler as described in the Oracle documents. Here is the handler declaration in the server class that implements the port interface
    @HandlerChain(file="handlers.xml")Here is the declaration of the handler class in the handlers.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
      <handler-chain>
        <handler>
          <handler-class>com.mycompany.service.handlers.LogHandler</handler-class>
        </handler>
      </handler-chain>
    </handler-chains>handlers.xml has been put in a folder structure under resources so that when the war file is generated, it is placed in the same folder as the server class. LogHandler implements SOAPHandler<SOAPMessageContext>
    When I deploy the application, the handler gets invoked and the getHeaders method gets called multiple times. But when I call the service with any operation, the handleMessage method is not invoked and the service acts like it doesn't have any handler. Please note that there are other projects that exist in my workspace and use handlers with the same configuration without any issues. As the handler is required for this project and I am running out of options to fix this matter, I appreciate your feedback. Thanks in advance!

    Your web.xml file need a servlet-mapping section:<web-app>
    <servlet>
    <!-- Servlet alias -->
    <servlet-name>Registration</servlet-name>
    <!-- Fully qualified Servlet class -->
    <servlet-class>GreetingServlet</servlet-class>
    </servlet>
        <servlet-mapping>
            <servlet-name>GreetingServlet</servlet-name>
            <url-pattern>/servlet/GreetingServlet</url-pattern>
        </servlet-mapping>
    </web-app>Also, you probably need to put your servlet in a package.

  • Problems handling motion in Compressor

    Dear All,
    I was disappointed to find that Compressor did a poor job in two short sections of a dvd where motion was involved. Not ultra fast motion, just arm movement and a person moving in front of a bright screen in a dark room. I re-burned the dvd using Quicktime and the problems did not appear. I sent the file to Compressor from Final Cut Pro and burned it using the best quality video and dolby audio for a 90 minute movie. The over-all quality from the Compressor version seemed slightly better, except for the two short segments (about 5 seconds each) where the artifacts appeared when the movement occurred. Any thoughts as to what I can do to correct this, or is it a common problem with Compressor? Thanks for your help.
    Barbara

    The preferences file is here: Your Home folder > Library > Preferences and is called "com.apple.compressor.Compressor.plist".
    See also here: http://support.apple.com/kb/TS1888?viewlocale=en_US

  • Problems handling xml data for tree control.

    Hi,
    I have tried using tree control for displaying my xml data
    but I had a problem that i did not have labels in my xml data. A
    sample xml data is attached. So it displays the whole data at each
    level in the tree. The root label will be the entire the xml data
    and then one level down the remaining xml data and so on...
    How do i solve this issue i,e get the tags names itself as
    labels..
    Thanks in advance....

    An update after some efforts..
    Could get the folders perfectly i.e until the level of
    CPUTime perfectly but could not get the leaf: 32 since i used the
    following to set the label.
    I would like to know if there is a way to find out if a node
    is a leaf or folder and according set the label

Maybe you are looking for