Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Disable JButton/Jlabel click

807569Jun 5 2006 — edited Jun 6 2006
Dear all,

I would want to disable click event after one click on my jbutton/jlabel in order to prevent from multiple clicking. setEnable() do nothing with several events.

I don't know where all events are stored but when i pressed the button ( and it still remain pressed ) i perform other click on this button and all click are performed and not only one....WHY???

I have tried this :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class MulitpleButtonClick {
	
	private static JEditorPane editorPane;
	
    public static void main(String[] args) {
    	
    	JFrame f = new JFrame("Multiple Click Button");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        
        editorPane = new JEditorPane();
        
        JButton button = new JButton("Multiples clicks");
        button.addActionListener(new ButtonListener(button));
        
        mainPanel.add(editorPane, BorderLayout.CENTER);
        mainPanel.add(button, BorderLayout.SOUTH);
        
        f.setContentPane(mainPanel);
        f.setSize(new Dimension(500,500));
        f.setVisible(true);
    }
    
    private final static class ButtonListener implements ActionListener{
    	
    	private JButton button;
    	
    	public ButtonListener(JButton button){
    		this.button = button;
    	}
    	public void actionPerformed(ActionEvent e){
    		
    		synchronized(this){
//    			button.setEnabled(false);
    			button.removeActionListener(this);
    			clickFilter();
    			button.addActionListener(this);
//    			button.setEnabled(true);
    		}
    	}
    	
    	public static void clickFilter(){
    		
    		Document document = editorPane.getDocument();
    		try {
				document.insertString(document.getLength(), "click \n", null);
			} catch (BadLocationException e1) {
				e1.printStackTrace();
			}
			
			int i=0;
    		while (i< 50000) {
    			System.out.println("i = "+i);
				i++;
			}
    		
    	}
    }
}
Thanks in advance for any helps...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 4 2006
Added on Jun 5 2006
6 comments
1,265 views