How to disable the process of JComponents - java

savebtn.setEnabled(false);
Using the above code i disable my save button.But when i click that button the save process will work. How to stop that process when clicking disabled button.

If you disable a JButton with setEnabled(false), its registered ActionListeners will not be called when you click on the button.
However if you added a MouseListener to it with addMouseListener() method, even if the button is disabled, the registered MouseListener will still be called.
You should register an ActionListener to do the job that is required when the button is pressed/clicked. That way if you disable the button, the ActionListener will not be called if the button is clicked.
See the following example: if you click on the button, it will only print "clicked" but it will not print "action performed".
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Test");
b.setEnabled(false);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("action performed");
}
});
b.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
System.out.println("clicked");
}
});
f.add(b);
f.pack();
f.setVisible(true);
If you remove the b.setEnabled(false); line and you click on the button output will be :
clicked
action performed

Related

How to run method in the JFrame by clicking button in JDialog?

I have a JFrame (called FTask) with public void method. Example code:
public void clear() {
jTable1.clearSelection();
jButton1.setEnabled(false);
jButton3.setEnabled(false);
jButton2.setEnabled(false);
jTextArea1.setText(null);
}
Then, I have JDialog with a button. I want when I click the button, frame do the 'clear' method to the frame.
I've tried:
FTask ft = new FTask();
ft.clear();
But it didn't work.
I've tried:
FTask ft = new FTask();
ft.clear();
But it didn't work.
No, it wouldn't. This code is creating a new (2nd instance) of the frame that is not set visible. What you need is a reference to the original frame.
This can be fixed in a number of ways, too broad to go into here, and is Object Oriented Programming 101 that should be mastered before trying to write GUI'd apps. - which add their own complications.
You have to use actionlistener in order to run the code when the button is clicked.
JButton button = new JButton("Click me");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
if(e.getSource() == button){
System.out.println("You clicked the button");
//In your case:
ft.clear();
}
}
});
As #Menno said, you have to use ActionListener in order to detect Button Clicks
Here is the Java 8 Style:
JButton button = new JButton("Click me");
//Add action listener to button
button.addActionListener(
ae -> ft.clear();
);
// Add button to frame
add(button);

Remove button with ActionListener from JFrame

Basically I have a class that extends JFrame, and I'm trying to have an ActionListener remove a button after another button has been clicked, it doesn't seem to be working...
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("Registered existing character click...");
getContentPane().remove(loginButton);
frame.remove(newAccountButton);
frame.revalidate();
frame.repaint();
//add(lookUp);
//add(searchButton);
bg.setIcon(rsLgn);
// lookUp.requestFocus();
// setComponentZOrder(searchButton, 0);
// setComponentZOrder(lookUp, 0);
}
});
EDIT: Currently, the button is invisible, so I wouldn't technically know if it was removed or not, but the System.out.println is definitely still outputting the original message of "Registered existing character click..."

Disable a JButton on click and re-enable it 1 second later?

I need to disable a JButton on on click and enable it again 2 seconds later, so for I've tried sleeping the ui thread from the event handler, but that leaves the button in a selected state where you can't read the text of the disabled button.
The code looks something like this:
JButton button = new JButton("Press me");
button.addActionListener(new ActionListener{
public void actionPerformed(ActionEvent ae) {
JButton button = ((JButton)e.getSource());
button.setEnabled(false);
button.setText("Wait a second")
button.repaint();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
}
button.setEnabled(true);
button.setText("");
}
What happens is the button remains in a "being selected" state with no text for the 2 seconds and instantly disables and re-enables the button at the end, which isn't what I want, what I'm aiming for is the button to stay in a disabled state with text on it for two seconds and then re-enable.
What do I do?
As user2864740 indicated - "Don't use Thread.sleep on the UI thread (the UI "freezes" and does not have a chance to repaint). Use a Timer class."
Here's an example of the kind of thing he was referring to. Should be close to what you want to do:
JButton button = new JButton("Press me");
int delay = 2000; //milliseconds
Timer timer = new Timer(delay, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
button.setEnabled(true);
button.setText("");
}
});
timer.setRepeats(false);
button.addActionListener(new ActionListener {
public void actionPerformed(ActionEvent ae) {
JButton button = ((JButton)e.getSource());
button.setEnabled(false);
button.setText("Wait a second")
timer.start();
}
}

How to open a JDialog

I am creating an application that has 1 JFrame java file and 1 JDialog java file.
In the JFrame, I have a button and when pressed I want it to display what I have designed in the JDialog.
So for example, my JFrame java file is called MMainView.java and my JDialog is called OptionView.java. So when the button in MMainView.java is pressed I want to display the JDialog I have designed in OptionView.java.
So in my MMainView.java file, I have a function that is called when that button is pressed. How do I display the dialog in OptionView.java?
SOLVED
For those wondering. This is what I did:
private JDialog optionView; ~~> JDialog Declaration
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (optionView == null) {
JFrame mainFrame = myApp.getApplication().getMainFrame();
optionView = new OptionView(mainFrame, true);
optionView.setLocationRelativeTo(mainFrame);
}
myApp.getApplication().show(optionView);
}
Sounds like you want to create an ActionListener for your button, and set the visibility of the JDialog to true when you press the button.
Something on these lines:
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionevent)
{
//set the visibility of the JDialog to true in here
}
});
Let's say your button is called myBtn.
The class should look like this.
public class MMainView extends JFrame
implements ActionListener
You should use a listener for the button.
JButton myBtn = new JButton();
myBtn.addActionListener(this);
And finally:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myBtn) {
new OptionView();
You don't really need the if, it's just in case you want to add more buttons for the actionPerformed.
First register the button in "MainView.java", like below.
b1.addActionListener(this);
b1.setName("OpenJDialog");
//this is to read in actionperformed method incase you have more than one button
// in action performed method call the dialogue class
public void actionPerformed(ActionEvent ae){
JButton jb = (JButton)ae.getSource();
String str = jb.getName();
if(str.equals("OpenJDialog"){
new OptionView();
//I am assuming u are configuring jdialog content in OptionView constructor
}
}

Enable only mouse event over a jbutton - Disable keyboard event for jbutton

I have a problem.
I created a game. When I open it I must press ENTER to start the game (just enter).
Now I upgraded the game with one button named "EXIT GAME". I don't know why my enter key doesn't work anymore because of this button. If i remove it then Ican press enter again and play the game.
I must set only click pressed event to that button or something like this? Please help me.
public class LeftPanel extends JPanel implements ActionListener {
JButton ExitGame;
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
add(new JButton("Exit Game"));
{
ExitGame.addActionListener(this);
}
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
Problem 1 - The JButton is the only focusable component within your UI. Therefore, when you start you program, it gains default focucs. While it has default focus. It will consume the Enter key strokes.
Problem 2 - JPanel is not focusable, meaning it can never receive key board focus. From your description, I would assume you are using a KeyListener, which leads to
Problem 3 - Using KeyListener...KeyListener will only respond to key events when the component it is registered to is focusable and has focus. You can over come this by using Key Bindings.
...Solutions...
Use JLabel instead of JButton. This will require you to register a MouseListener to the label in order to recieve notification of the mouse clicks, but it won't respond to key events...
Better still, add a "Start" button as well...
You can try:
public class LeftPanel extends JPanel implements ActionListener {
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
JButton ExitGame = new JButton("Exit Game");
ExitGame.addActionListener(this);
ExitGame.setActionCommand("Exit");
add(ExitGame );
}
public void actionPerformed(ActionEvent e) {
if("Exit".equals(e.getActionCommand())
System.exit(0);
}
}
This line looks like a syntax error:
add(new JButton("Exit Game"));
{
ExitGame.addActionListener(this);
}
I think it should be something like this:
ExitGame= new JButton("Exit");
this.add(ExitGame);
ExitGame.addActionListener(this);
I haven't tested this, but I think with some tweaking you should be able to get it to do what you want it to. I hope that works!
-Frank
public void actionPerformed(ActionEvent e) {
if("Exit".equals(e.getActionCommand())
System.exit(0);
}
As ActionlListener can be triggered by both Mouse and Keyboard, but now user only want to response mouse event, so change the action listener to mouselistener. Tested and passed.
public class LeftPanel extends JPanel implements ActionListener {
JButton ExitGame;
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
ExitGame= new JButton("Exit Game")
add(ExitGame);
ExitGame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
}
}

Categories

Resources