Reputation: 47
There are two buttons in my ui which re-directs to two JFrame
s. I am trying to make that if user press button one, button two becomes disabled, and if the user presses button two, button one becomes disabled, so that the user cannot open both the JFrame
s at the same time.
import java.awt.*;
import java.awt.event.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class Main extends JFrame {
public Main() {
JPanel panel = new JPanel();
getContentPane().add (panel,BorderLayout.NORTH);
JButton button1 = new JButton("One");
panel.add(button1);
JButton button2 = new JButton("Two");
panel.add(button2);
button1.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
button2.setEnabled(false);
One f = new One();
f.setSize(350,100);
f.setVisible(true);
}
});
button2.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
button1.setEnabled(false);
Two fr = new Two();
fr.setSize(350,100);
fr.setVisible(true);
}
});
public void enableButtons()
{
button1.setEnabled(true);
button2.setEnabled(true);
}
}
public static void main(String[] args) {
Main frame = new Main();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
enableButtons();
System.exit(0);
}
});
frame.setSize(300,200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
Upvotes: 1
Views: 2364
Reputation: 1283
Check out the ButtonGroup for a more elegant solution.
http://docs.oracle.com/javase/tutorial/uiswing/components/buttongroup.html
Upvotes: 0
Reputation: 3938
In your ActionListener
for Button One, add
ButtonTwo.setEnabled(false);
and in the ActionListener
for Button Two add
ButtonOne.setEnabled(false);
Don't forget to add the corresponding enables (button.setEnable(true)
) otherwise you will be left with two disabled buttons. Maybe in an event for closing the JFrames
.
EDIT:
You can write a method like this
public void enableButtons()
{
button1.setEnabled(true);
button2.setEnabled(true);
}
Call this method in an event of JFrame closing. This tutorial explains the JFrame closing event.
Upvotes: 1