Jbutton disabling

how to stop the action of a jbutton while executing the process
i had a problem the button action was performed and continuing the process
i want to disable the button when the process is executing
plz help me

Goyyaala
I'm blocking your posts and user account for violating Section 1.4 of the Code of Conduct that you agreed to when you signed up to this site.
1.4 You agree not to post messages that are clearly outside of the stated topic of any forums nor disrupt a forum by deliberately posting repeated irrelevant messages or copies of identical messages (also known as "flooding").
You agree not to post or store on Sun.com or any of its affiliated sites any Content that is intentionally off-topic, repetitive, inaccurate, or irrelevant.
db

Similar Messages

  • JButton disable issue

    I have a small swing app, which have couple of buttons. One of the button involves a five minute processing. During this time, I have disabled the button and removed the action Listener. Even though the button remains faded during the process, If the user clicks on the button ( while remaining faded) , the proces starts all over again, after the end of the current process.
    button.removeActionListerner(listener)
    button.setEnabled(false)
    paint(getGraphics())
    processData()
    button.setEnabled(true)
    button.addActionListener(listener)
    paint(getGraphics())
    Any ideas ? Thanks

    Thought this would be a good time to learn and try to use a background thread in Swing. Never done this before, but the code works. If no one else finds fault with it (not unlikely given my novice status), you might want to try to use something like this in your program.
    Please anyone, let me know if this is messed up or if it is ok. Thanks!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class SwingBckGround extends JFrame implements ActionListener
        private JPanel mainPanel = new JPanel();
        private JPanel buttonPanel = new JPanel();
        private JButton noThreadButton = new JButton("No Background Thread");
        private JButton yesThreadButton = new JButton("With Background Thread");
        private JPanel redPanel = new JPanel();
        private JLabel redPanelLabel = new JLabel("Press Buttons to turn panel red");
        private Color redPanelBkGrndColor;
        public SwingBckGround()
            super("Brief Swing App");
            createWidgets();
            getContentPane().add(mainPanel);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        private void createWidgets()
            // create buttonPanel
            int edgeSize = 10;
            FlowLayout fLayO = new FlowLayout();
            fLayO.setHgap(2* edgeSize);
            buttonPanel.setLayout(fLayO);
            buttonPanel.add(noThreadButton);
            buttonPanel.add(yesThreadButton);
            buttonPanel.setBorder(BorderFactory.createEmptyBorder(edgeSize, edgeSize, edgeSize, edgeSize));
            noThreadButton.addActionListener(this);
            yesThreadButton.addActionListener(this);
            // create redPanel
            redPanel.setPreferredSize(new Dimension(40, 80));
            redPanel.add(redPanelLabel);
            // create mainPanel
            mainPanel.setLayout(new BorderLayout());
            mainPanel.add(buttonPanel, BorderLayout.NORTH);
            mainPanel.add(redPanel, BorderLayout.SOUTH);
        // any method that will take some time to finish
        private void busyWork()
            int loopSize = 1000;
            for (int i = 0; i < loopSize; i++)
                for (int j = 0; j < loopSize; j++)
                    for (int k = 0; k < loopSize; k++)
                        int foo = i + j + k;
        public void actionPerformed(ActionEvent e)
            JButton myBtn = (JButton)e.getSource();
            if (myBtn.equals(noThreadButton))
                yesThreadButton.setEnabled(false);
                redPanelBkGrndColor = redPanel.getBackground();
                redPanel.setBackground(Color.red);
                busyWork();
                yesThreadButton.setEnabled(true);
                redPanel.setBackground(redPanelBkGrndColor);
            else if (myBtn.equals(yesThreadButton))  // the if not needed but here for clarity
                noThreadButton.setEnabled(false);  // disable the other button
                redPanelBkGrndColor = redPanel.getBackground();  // store original panel color
                redPanel.setBackground(Color.red); // set redpanel to red
                // create our background thread.  Needs Java 6 to work
                SwingWorker<Void, Void> mySW = new SwingWorker<Void, Void>()
                    @Override  // do our busy work here in the background
                    protected Void doInBackground() throws Exception
                        busyWork();
                        return null;
                    @Override
                    public void done()
                        // when done reset button to enabled, and 
                        // change redPanel color back to original color
                        // I'm not sure if tricky GUI calls here would require a
                        // call through the Swing event thread with
                        // SwingUtilities.invokeLater(new Runnable()....?
                        noThreadButton.setEnabled(true);
                        redPanel.setBackground(redPanelBkGrndColor);
                mySW.execute();  // lets call our SwingWorker object here
        private static void createAndShowGUI()
            SwingBckGround swngBckGrnd = new SwingBckGround();
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
            { public void run() { createAndShowGUI();}});
    }

  • Keeping text intact in disabled checkbox

    hi all,
    If I disable a checkbox, I want to keep it's name/text not disabled
    (normal) would it be possible?
    Thanks

    You could probably get into overriding paint methods or creating a new UI delegate for the checkbox, but both of those are going to be fairly daunting. One solution would be to just create a label and place it next to a 'blank' checkbox. Change the foreground color to the same color you would expect the checkbox to use (I did it the sloppy way, I hardcoded it) and your set. If you run this little app you'll notice that the label doesn't quite line up like it would with a real checkbox, but it won't be noticeable as long as you don't have any other checkboxes nearby.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CheckBoxTestFrame extends JFrame
       private JCheckBox _chkDummy;
       private JCheckBox _chkDisablingCheckbox;
       public CheckBoxTestFrame()
          super("Checkbox test frame");
          Container content = getContentPane();
          content.add(getCheckboxComponent(), BorderLayout.NORTH);
          content.add(getButtonPanel(), BorderLayout.SOUTH);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          pack();     
          setVisible(true);
       private Component getCheckboxComponent()
          JPanel panel = new JPanel(new GridBagLayout());
          GridBagConstraints gbc = new GridBagConstraints();
          _chkDisablingCheckbox = new JCheckBox();
          _chkDisablingCheckbox.setMnemonic('n');
          gbc.anchor = gbc.WEST;
          panel.add(_chkDisablingCheckbox, gbc);
          JLabel lblNonDisablingLabel = new JLabel("Non disabling label");
          lblNonDisablingLabel.setForeground(Color.black);
          lblNonDisablingLabel.setLabelFor(_chkDisablingCheckbox);
          lblNonDisablingLabel.setDisplayedMnemonic(_chkDisablingCheckbox.getMnemonic());
          gbc.gridx = 1;
          gbc.weightx = 1.0;
          gbc.weighty = 1.0;
          panel.add(lblNonDisablingLabel, gbc);
          _chkDummy = new JCheckBox("Dummy checkbox for comparison");
          gbc.gridy = 1;
          gbc.gridx = 0;
          gbc.gridwidth = 2;
          gbc.weightx = 0.0;
          gbc.weighty = 0.0;
          panel.add(_chkDummy, gbc);
          return panel;     
       private Component getButtonPanel()
          JPanel panel = new JPanel();
          final JButton btnDisableEnable = new JButton("Disable");
          btnDisableEnable.setMnemonic('a');
          btnDisableEnable.addActionListener(new ActionListener()
             public void actionPerformed(ActionEvent e)
                boolean isDisable = btnDisableEnable.getText().startsWith("Dis");
                _chkDisablingCheckbox.setEnabled(!isDisable);
                _chkDummy.setEnabled(!isDisable);
                btnDisableEnable.setText(isDisable ? "Enable" : "Disable");
          panel.add(btnDisableEnable);
          return panel;
       public static void main(String[] args)
          new CheckBoxTestFrame();
    }

  • How to change the location of JButton

    b1 = new JButton("Disable middle button");
    b1.setVerticalTextPosition(AbstractButton.CENTER);
    b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
    b1.setMnemonic(KeyEvent.VK_D);
    b1.setActionCommand("disable");
    b1.setPreferredSize(new Dimension(300, 30));
    I have got this far and now i want to change the physical location of the the 'b1' button any idea ?

    now i want to change the physical location of the the 'b1' button use the appropriate layout manager (or nested managers)
    (it is rarely a good idea to use a null layout)
    http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html

  • Disabled foreground color in JComboBox

    what's the correct way to set the disabled foreground color of a jcombobox? i don't want to set the disabled color for the entire ui to the same color, but for one jcombobox specifically. i searched the web and found many posts with the same question, but no real solution. this one has been giving me nightmares and i thought i'd share what i've found. the solution seems to be quite simple: wrap the combobox label in a panel. that way the panel gets the disabled colors, but the coloring of the label of the combobox remains. here's the solution in short in case others need it:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.ListCellRenderer;
    public class MyComboBox extends JComboBox {
      public MyComboBox() {
        super();
        setRenderer( new ColorCellRenderer());
      public static void main(String s[]) {
        JFrame frame = new JFrame("ComboBox Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JComboBox cb = new MyComboBox();
        cb.addItem( "ComboBox Item 1");
        cb.addItem( "ComboBox Item 2");
        cb.addItem( "ComboBox Item 3");
        cb.setForeground( Color.blue);
        final JButton bt = new JButton ("disable");
        bt.addActionListener( new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            cb.setEnabled( !cb.isEnabled());
            if( !cb.isEnabled()) {
              cb.setForeground( Color.red);
              bt.setText( "enable");
            } else {
              cb.setForeground( Color.blue);
              bt.setText( "disable");
        frame.getContentPane().setLayout( new FlowLayout());
        frame.getContentPane().add( bt);
        frame.getContentPane().add( cb);
        frame.pack();
        frame.setVisible(true);
      class ColorCellRenderer implements ListCellRenderer {
        protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
        public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
          JLabel label = (JLabel) defaultRenderer
              .getListCellRendererComponent(list, value, index,
                  isSelected, cellHasFocus);
          JPanel wrapper = new JPanel();
          wrapper.setLayout( new BorderLayout());
          wrapper.add( label, BorderLayout.CENTER);
          return wrapper;
    }if anyone knows a way to remove the dropdown button of a disabled combobox without leaving a blank space when you simply hide the button, feel free to extend this :-)
    Edited by: Lofi on Mar 20, 2010 10:46 PM

    i thought i'd share what i've found. the solution seems to be quite simple: wrap the combobox label in a panel.Brilliant! I'm sure this will be useful to others who find this solution here.
    Your code does have some unnecessary overheads though, like constructing a new JPanel in every call to getListCellRendererComponent, and holding a separate renderer as a field. I've attempted to clean it up for brevity and efficiency.import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class DisabledForegroundListCellRenderer extends DefaultListCellRenderer {
      private final JPanel wrapper = new JPanel(new BorderLayout());
      public DisabledForegroundListCellRenderer() {
        wrapper.add(this);
      @Override
      public Component getListCellRendererComponent(JList list, Object value,
              int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value,
                index, isSelected, cellHasFocus);
        return wrapper;
      // Test rig
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new DisabledForegroundListCellRenderer().makeUI();
      public void makeUI() {
        String[] data = {"One", "Two", "Three"};
        final JComboBox combo = new JComboBox(data);
        combo.setRenderer(new DisabledForegroundListCellRenderer());
        final JCheckBox check = new JCheckBox("Combo enabled");
        check.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            boolean selected = check.isSelected();
            combo.setForeground(selected ? Color.BLUE : Color.RED);
            combo.setEnabled(selected);
        check.doClick();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(check, BorderLayout.NORTH);
        frame.add(combo, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }I've also changed the class name, as to me "ColorCellRenderer" would rather imply something that renders either the foreground or the background (or both) on the basis of the value parameter.
    if anyone knows a way to remove the dropdown button of a disabled combobox without leaving a blank space when you simply hide the buttonThat would require a custom UI delegate, not a custom renderer. And really, I wouldn't bother -- I would just use a JComboBox and a disabled (or maybe uneditable) JTextField, held in a CardLayout, and swap them instead of disabling the combo.
    Shall take a look at how the combo UIs reserve space for the button though :)
    luck, db
    Edited by: DarrylBurke -- changed wrapper to private final, it shouldn't be static

  • Disappearing Images on JButtons using JDK 1.4.0

    Here is the Java Swing Button example from java.sun.com:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.AbstractButton;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    public class ButtonDemo extends JPanel
    implements ActionListener {
    protected JButton b1, b2, b3;
    public ButtonDemo() {
    ImageIcon leftButtonIcon = new ImageIcon("images/right.gif");
    ImageIcon middleButtonIcon = new ImageIcon("images/middle.gif");
    ImageIcon rightButtonIcon = new ImageIcon("images/left.gif");
    b1 = new JButton("Disable middle button", leftButtonIcon);
    b1.setVerticalTextPosition(AbstractButton.CENTER);
    b1.setHorizontalTextPosition(AbstractButton.LEFT);
    b1.setMnemonic(KeyEvent.VK_D);
    b1.setActionCommand("disable");
    b2 = new JButton("Middle button", middleButtonIcon);
    b2.setVerticalTextPosition(AbstractButton.BOTTOM);
    b2.setHorizontalTextPosition(AbstractButton.CENTER);
    b2.setMnemonic(KeyEvent.VK_M);
    b3 = new JButton("Enable middle button", rightButtonIcon);
    //Use the default text position of CENTER, RIGHT.
    b3.setMnemonic(KeyEvent.VK_E);
    b3.setActionCommand("enable");
    b3.setEnabled(false);
    //Listen for actions on buttons 1 and 3.
    b1.addActionListener(this);
    b3.addActionListener(this);
    b1.setToolTipText("Click this button to disable the middle button.");
    b2.setToolTipText("This middle button does nothing when you click it.");
    b3.setToolTipText("Click this button to enable the middle button.");
    //Add Components to this container, using the default FlowLayout.
    add(b1);
    add(b2);
    add(b3);
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("disable")) {
    b2.setEnabled(false);
    b1.setEnabled(false);
    b3.setEnabled(true);
    } else {
    b2.setEnabled(true);
    b1.setEnabled(true);
    b3.setEnabled(false);
    public static void main(String[] args) {
    JFrame frame = new JFrame("ButtonDemo");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.getContentPane().add(new ButtonDemo(), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    Do the following:
    1. Compile and run this example using JDK 1.4.0.
    2. While the frame is up hit the Control + Alt + Delete key sequence.
    3. Now hit the Escape Key.
    4. You will notice that atleast one of the buttons on the Java Swing Example will not have the image painted.
    Now if you force a repaint then the image(s) gets painted correctly.
    Any ideas?

    i've got exactely the same problem in a gui application running on windows nt 4, service pack 6. the problem of the disappearing icons occurs also after returning from the screen lock.
    if you got a solution in the mean time please let me know, thanks a lot
    matthiaszimmermann at yahoo.com

  • Change color of disabled JTabbedPane

    Hi everybody,
    I have a disabled JTabbedPane and now I need to change the color of the text in the Tab.
    Default it is a grey color.
    I know you normally can do something like:
    UIManager.set("ComboBox.disabledForeground", Color.red);But this isn&#8217;t working for a TabbedPane
    Somebody has any suggestions?
    Regards,
    Remco

    try this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setLocation(300,200);
        setSize(400,250);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        final JTabbedPane tp = new JTabbedPane();
        tp.addTab("tab 1",new JPanel());
        tp.addTab("tab 2",new JPanel());
        tp.addTab("tab 3",new JPanel());
        getContentPane().add(tp,BorderLayout.CENTER);
        JButton btn = new JButton("Disable/Enable \"Tab 2\"");
        getContentPane().add(btn,BorderLayout.SOUTH);
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tp.setEnabledAt(1,!tp.isEnabledAt(1));
            tp.setTitleAt(1,"<html><font color="+(tp.isEnabledAt(1)? "black":"red")+">tab 2</font></html>");}});
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • How do I make a JTextArea invisible to the mouse?

    Consider the applet below. There is a small JTextArea sitting in the glass pane. There are 3 JButtons sitting in a JPanel that is sitting in the content pane. One is completely under the JTextArea, one is half in and half out, & the last is completely outside it (at least I hope thats what it looks like on your machine.) The idea is when you click the disable button the JTextArea is disabled and you can click on the button that's underneath it.
    But it doesn't work that way. even when the JTextArea is disabled the mouse still cant click through it.
    Is there some way to make the JTextArea completely invisible to the mouse so I can click through it? I know setVisible(false) on the glass panel will work but I only want it to be invisible to the mouse, not my eyes.
    Thanks.
    /*  <applet code="MyTest14" width="400" height="100"></applet>  */
    // testing glass panes
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class MyTest14 extends JApplet implements MouseListener
    TextPanel textPanel;
    JPanel buttonPanel;
    JButton underButton, enableButton, disableButton;
    JTextArea jta;
    public void init()
      Container contentPane = getContentPane();
      contentPane.setLayout(new FlowLayout());
      contentPane.setBackground(Color.WHITE);
      underButton = new JButton("Under textarea");
      underButton.addMouseListener(this);
      enableButton = new JButton("Enable textarea");
      enableButton.addMouseListener(this);
      disableButton  = new JButton("Disable textarea");
      disableButton.addMouseListener(this);
      buttonPanel = new JPanel(new BorderLayout());
      buttonPanel.add(underButton, "West");
      buttonPanel.add(enableButton, "Center");
      buttonPanel.add(disableButton, "East");
      jta = new JTextArea();
      jta.setPreferredSize(new Dimension(200,80));
      jta.setOpaque(false);
      jta.setLineWrap(true);
      jta.setWrapStyleWord(true);
      textPanel = new TextPanel();
      textPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
      textPanel.add(jta);
      jta.setBorder(BorderFactory.createLineBorder(Color.black));
      contentPane.add(buttonPanel);
      setGlassPane(textPanel);
      textPanel.setVisible(true);
    public void mouseClicked(MouseEvent e)
      if (e.getSource() == enableButton) { jta.setEnabled(true); }
      else if (e.getSource() == disableButton) { jta.setEnabled(false); }
      else if (e.getSource() == underButton) { System.out.println("You reached the under button!"); }
    public void mouseExited(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    class TextPanel extends JPanel
      public TextPanel()
       super();
       setOpaque(false);
      public void paintComponent(Graphics g) { super.paintComponent(g); }
    }

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
      Container content = getContentPane();
      JButton jb = new JButton("Press"), disenable = new JButton("Enable");
      JTextArea jta = new JTextArea("Now is the time for all google men to come to the aid of their browser");
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel jp = new JPanel();
        content.add(jp, BorderLayout.CENTER);
        jp.add(jb);
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) { System.out.println("Click!"); }
        jta.setLineWrap(true);
        jta.setWrapStyleWord(true);
        jta.setOpaque(false);
        jta.setEnabled(false);
        JScrollPane jsp = new JScrollPane(jta);
        jsp.setOpaque(false);
        jsp.getViewport().setOpaque(false);
        jsp.setPreferredSize(new Dimension(130,130));
        JPanel glass = (JPanel)getGlassPane();
        glass.add(jsp);
        glass.setVisible(true);
        jta.addMouseListener(new MouseListener() {
          public void mouseReleased(MouseEvent me) { mousy(me); }
          public void mouseClicked(MouseEvent me) { mousy(me); }
          public void mouseEntered(MouseEvent me) { mousy(me); }
          public void mouseExited(MouseEvent me) { mousy(me); }
          public void mousePressed(MouseEvent me) { mousy(me); }
        content.add(disenable, BorderLayout.SOUTH);
        disenable.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            jta.setEnabled(!jta.isEnabled());
            disenable.setText(jta.isEnabled()?"Disable":"Enable");
        setSize(200,200);
        setVisible(true);
      void mousy(MouseEvent me) {
        if (jta.isEnabled()) return;
        Point p = SwingUtilities.convertPoint((Component)me.getSource(), me.getPoint(), content);
        Component c = content.findComponentAt(p);
        if (p!=null) c.dispatchEvent(SwingUtilities.convertMouseEvent((Component)me.getSource(), me, c));
      public static void main(String[] args) { new Test(); }
    }

  • Help needed in activating and deactivating a window

    In my GUI, I have created a window, that is having one textfield, one label and 2 buttons named "Enabled" & "Disabled" .
    MY requirement is: After execution of the window when I will click "Disabled" button, the window should be deactivated, even I can't type in the textfield and then clicking the " Enabled" button the window should be activated, then I can access the textfield.
    Here bellow,I have written the code for visibility of the window, but I haven't written code for the action to be performed by the 2 buttons.
    Can anyof you please write me the updated code satisfying my requirement, sothat I'll proceed further.
    Regards.
    MY CODE:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Test7 extends JFrame
         public Test7()
              Container con=getContentPane();
              addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              JPanel p1=new JPanel();
              p1.setBackground(Color.white);
              JPanel p2=new JPanel();
              JPanel p3=new JPanel();
              JTextField txt=new JTextField(10);
              JLabel l=new JLabel("hello world");;
              JButton b1=new JButton("Enable");
              b1.addFocusListener(new FocusAdapter(){
                   public void focusGained(FocusEvent evt)
              System.out.println("gained");
         // The component gained the focus
              JButton b2=new JButton("Disable");
              b2.addFocusListener(new FocusAdapter(){
                   public void focusLost(FocusEvent evt)
              System.out.println("lost");
         // The component lost the focus
              p1.add(txt);
              p2.add(l);
              p3.add(b1);
              p3.add(b2);
              con.add(p1,"North");
              con.add(p2,"Center");
              con.add(p3,"South");
              setSize(300,200);
              show();
         public static void main(String arg[])
              new Test7();

    try modifying code for the button listeners
    JButton b1=new JButton("Enable");
    b1.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt)
    System.out.println("gained");
    // The component gained the focus
    txt.setEnabled(true);
    JButton b2=new JButton("Disable");
    b2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt)
    System.out.println("lost");
    txt.setEnabled(false);
    // The component lost the focus
    Hope this helps

  • Interrupting program execution

    Hello, I want to interrupt/stop my program execution when a certain button is clicked. I want to implement the cancellation button in another GUI which is independent of the parent GUI that contains my running thread. However, when i invoke "Thread.currentThread().interrupt()" to cancel, it doesn't seem to work, and neither does "Thread.currentThread().stop()" of which I understand stop is deprecated. Any help will be appreciated.

    call setEnabled(false) on the enclosing window. Maybe I'm over-simplifying things, but it could work in certain situations. For e.g.,
    import java.awt.BorderLayout;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class SetEnabledTest {
      private static void createAndShowUI() {
        final WindowOne winOne = new WindowOne();
        JFrame frame = new JFrame("SetEnabledTest");
        frame.getContentPane().add(winOne.getMainPanel());
        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();
    class WindowOne {
      private static final String DISABLED = "Disabled";
      private static final String DISABLE = "Disable for 5 seconds";
      protected static final int DISABLE_TIME = 5000;
      private JPanel mainPanel = new JPanel();
      private JButton controllerBtn = new JButton(DISABLE);
      public WindowOne() {
        controllerBtn.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            final Window win = SwingUtilities.getWindowAncestor(mainPanel);
            if (controllerBtn.getText().equals(DISABLE)) {
              controllerBtn.setText(DISABLED);
              win.setEnabled(false);
              new Timer(DISABLE_TIME, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  win.setEnabled(true);
                  controllerBtn.setText(DISABLE);
                  ((Timer)e.getSource()).stop();
              }).start();
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(controllerBtn);
        JPanel topPanel = new JPanel();
        topPanel.add(new JTextField(10));
        topPanel.add(new JButton("Button"));
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);
      public void setEnabled(boolean enabled) {
        Window win = SwingUtilities.getWindowAncestor(mainPanel);
        win.setEnabled(enabled);
      public JPanel getMainPanel() {
        return mainPanel;
    }Edited by: Encephalopathic on Mar 12, 2010 3:11 PM

  • Loosing & gaining focus of a window.

    In my GUI, I have created a window, that is having 2 buttons named "Enabled" & "Disabled".
    MY requirement is: After execution of the window when I will click "Disable" button, the window should loose its focus and then clicking the " Enable" button the window should gain its focus.
    Here I have written the code bellow for visibility of the window, but I haven't written code for the action to be performed by the 2 buttons.
    If any of you have the idea about my requirement, please write me the updated code satisfying my requirement, sothat I'll proceed further.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class window extends JFrame
         public window()
              Container con=getContentPane();
              addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              JPanel p1=new JPanel();
              JPanel p2=new JPanel();
              JButton b1=new JButton("Enable");
              JButton b2=new JButton("Disable");
              p2.add(b1);
              p2.add(b2);
              con.add(p1,"Center");
              con.add(p2,"South");
              setSize(300,200);
              show();
         public static void main(String arg[])
              new window();
    Regards.
              

    Use a JDialog as the secondary window and make sure you specify the frame as the owner when you create the dialog.

  • Can i change the color of the text of a JButton, when it is disabled?

    Hi,
    I want to keep the black foreground of my JButton even after I disable it. I have tried using:
    .setForeground(Color.black);
    but it remains gray. Is there anyway to do this?
    thanks!

    just a thought...
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing extends JFrame
      public Testing()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel jp = new JPanel(new GridLayout(2,1));
        final JButton btn = new JButton("Enabled");
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            JOptionPane.showMessageDialog(getContentPane(),"Hello World");}});
        JCheckBox cbx = new JCheckBox("Enable/Disable",true);
        cbx.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            btn.setEnabled(!btn.isEnabled());
            //btn.setText(btn.isEnabled()? "Enabled":"Disabled");}});//toggle these lines
            btn.setText(btn.isEnabled()? "Enabled":"<html><font color=black>Disabled</font></html>");}});
        jp.add(btn);
        jp.add(cbx);
        getContentPane().add(jp);
        pack();
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Problem disabling JButton in ActionListener after setText of JLabel

    What i want is when i click View to see the label say "Viewing ..." and in the same time the btnView (View Button) to be disabled.
    I want the same with the other 2 buttons.
    My problem is in ActionListener of the button. It only half works.
    I cannot disable (setEnabled(false)) the button after it is pressed and showing the JLabel.
    The code i cannot run is the 3 buttons setEnabled (2 in comments).
    Any light?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class BTester extends JFrame implements ActionListener { 
         JButton btnView, btnBook, btnSearch;
         BTester(){     //Constructor
              JPanel p = new JPanel();
         JButton btnView = new JButton( "View" );
         btnView.setActionCommand( "View" );
         btnView.addActionListener(this);
         JButton btnBook = new JButton( "Book" );
         btnBook.setActionCommand( "Book" );
         btnBook.addActionListener(this);
         JButton btnSearch = new JButton( "Search" );
         btnSearch.setActionCommand( "Search" );
         btnSearch.addActionListener(this);
         p.add(btnView);
         p.add(btnBook);
         p.add(btnSearch);
         getContentPane().add(show, "North"); //put text up
    getContentPane().add(p, "South"); //put panel of buttons down
    setSize(400,200);
    setVisible(true);
    setTitle("INITIAL BUTTON TESTER");
    show.setFont(new Font("Tahoma",Font.BOLD,20));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
         //actionPerformed implemented (overrided)
         public void actionPerformed( ActionEvent ae) {
    String actionName = ae.getActionCommand().trim();
    if( actionName.equals( "View" ) ) {
    show.setText("Viewing ...");
         btnView.setEnabled(false); // The line of problem
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Book" ) ) {
    show.setText("Booking ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(false);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Search" ) ) {
    show.setText("Searching ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(false);
    } //end actionPerformed
         private JLabel show = new JLabel( "Press a button ... " );
    public static void main(String[] args) { 
         new BTester();
    } // End BTester class

    1. Use code formatting when posting code.
    2. You have a Null Pointer Exception since in your constructor you create the JButtons and assign them to a local variable instead of the class member.
    Change this
    JButton btnView = new JButton( "View" );to:
    btnView = new JButton( "View" );

  • How to disable the highlight i get on a JButton when it's helddown\pressed?

    couldn't find it anywhere..is there a way to disable the blueish highlight i get when it's pressed?or is the only option to make a glass pane over it?

    setUI of the JButton and override paintButtonPressed with an empty method:JButton button = new JButton ("Click");
    button.setUI (new MetalButtonUI () {
        protected void paintButtonPressed (Graphics g, AbstractButton b) { }
    });Suitable for Metal L&F only.
    May I ask the reason behind this requirement?
    db

  • Disabled JButtons without grayed-out images

    Hello,
    I have a disabled button, and when I put an image in it, the image is grayed out. Is there anyway I can have the image remain as normal instead of becoming grayed-out?
    Thanks in advance.
    Troy

    Just use the setDisabledIcon(Icon) method:
    import javax.swing.*;
    public class JButtonTest extends JFrame {
         private Icon icon = new ImageIcon("img.gif");
         private JButton button = new JButton(icon);
         public JButtonTest() {
              this.getContentPane().add(this.button);
              this.button.setDisabledIcon(this.icon);
              this.button.setEnabled(false);
              this.setSize(600, 400);
              this.setVisible(true);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public static void main(String[] args) {
              new JButtonTest();
    }

Maybe you are looking for

  • Portal using Webdynpro for ABAP

    Hi Gurus!     I am using one portal using 'Webdynpro For ABAP'. It contains Contextual Panel as well as ViewUIContainer. Contextual Panel contains all the reqd options available for user; while ViewUIContainer contains diff views as requested.    Now

  • Aperture 3.2.3 displays only 1000 pictures in photo stream

    I updated the software to 3.2.2 then to 3.2.3 and performed repair of the database but Aperture continues to display only 1000 pictures in photostream

  • CTI Configuration

    Hi Can anyone help me out with CTI vendors? Also tell me the various steps that I need to take in order to configure CTI? Thanks Tarang

  • Help my Mac pro is showing 'AFP CONNECTION STATUS" looking up "wildlife"

    hi I am facing a problem that in some of my clients after about every 2 to 3 sec. a massage pop up on finder that "AFP CONNECTION STATUS" LOOKING UP "WILDLIFE" and it keeps on coming . First it was coming on My Xserve (after i delete some footage fro

  • Can content in deleted apps be retrieved?

    I was going to transfer some images to my iPad through iTunes. So I selected the photos I wanted and clicked "Apply" (at least I think that's the english translation). I went away from my computer so I don't know what happened, but after I got back t