Remove button with ActionListener from JFrame - java

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..."

Related

JButton doClick() performs the last clicked button

This is the block of code that I am using to check for key presses. If I press the 'esc' key then the JFrame closes. But, if I press the 'space' bar the listener performs the last JButton pressed, NOT the specific button I am telling it to click. The doClick() also does not run unless a JButton was previously clicked.
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
SaveScripts.saveData(player);
dispose();
}
if(ke.getKeyCode() == KeyEvent.VK_SPACE) {
center.buttonMenuAttack.doClick();
}
}
});
Edit 1: Ok after some more testing, the issue seems to be that the listener breaks when anything in the frame is clicked.
Program Launches
Listener is active and working.
Any component of the frame is clicked, the listener breaks
Edit 2: I ended up going with camickr's solution, its much easier to set up and I haven't had any issues with using it.
InputMap events = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actions = getRootPane().getActionMap();
events.put(KeyStroke.getKeyStroke("SPACE"), "click");
actions.put("click", new AbstractAction() {
public void actionPerformed(ActionEvent event) {
center.bAttack.doClick();
}
});
events.put(KeyStroke.getKeyStroke("ESCAPE"), "click");
actions.put("click", new AbstractAction() {
public void actionPerformed(ActionEvent event) {
manage.bDataExit.doClick();
}
});
I figured out the issue. The Listener stopped working because when a button is clicked, it becomes the focused. I made a class that extends JButton so that all my buttons have the same behavior and added the following line of code to its constructors;
setRequestFocusEnabled(false);
This way, after a button is clicked the JFrame remains focused, allowing the Listener to behave as intended.

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);

How to disable the process of JComponents

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

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