java swing events - java

I want when I enter a button, text to appear in the console. How can I combine the methods there is my comfusing, can someone explain and give example.

Try
JButton button = new JButton("Button1");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button1 was Clicked!");
}
});
// add button to a container

Use a MouseListener. For example:
JComponent button = new JButton();
component.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered the button");
}
});
MouseAdapter is a special MouseListener that has default empty implementations of all the other methods that the MouseListener provides, so you don't have to override them. You may want to look at the Javadoc for MouseAdapter, MouseListener, and MouseEvent.

Add an ActionListener to the button. In the actionPerformed() method print text on the console or whatever else you want.

Related

Swing Java how to make multiple buttons That do different tasks on Click

I am a studying programming we just started Swing I have to make a simple boat management I need about 20 buttons. I am using the setVisible() method for every button I just wonder if is there another way of doing that.
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
button.setVisible(false);
button1.setVisible(false);
button2.setVisible(true);
button3.setVisible(true);
}
});
If I understand your question, you could define two utility methods like
static void setVisible(JButton... btns) {
for (JButton btn : btns) {
btn.setVisible(true);
}
}
static void setInvisible(JButton... btns) {
for (JButton btn : btns) {
btn.setVisible(false);
}
}
Then you could call those with any number of buttons; like
setInvisible(button, button1);
setVisible(button2, button3);
As for making different buttons do different things, define an ActionListener per button (or per unique action).
Just add another new ActionListener(){....} to each button and modify the actionPerformed(ActionEvent e) method accordingly
You can just implement the action listener in your class like:
public class XYZ implements ActionListener
Then add it to your buttons like:
b1.addActionListener(this);
b2.addActionListener(this);
...
Then override the actionPerformed method:
public void actionPerformed(ActionEvent e) {
//Here do your tasks.
// To identify the button, use : e.getSource();
}

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

Java - Call Method via JButton

How can I call a method by pressing a JButton?
For example:
when JButton is pressed
hillClimb() is called;
I know how to display messages etc when pressing a JButton, but want to know if it is possible to do this?
Many thanks.
If you know how to display messages when pressing a button, then you already know how to call a method as opening a new window is a call to a method.
With more details, you can implement an ActionListener and then use the addActionListener method on your JButton. Here is a pretty basic tutorial on how to write an ActionListener.
You can use an anonymous class too:
yourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hillClimb();
}
});
Here is trivial app showing how to declare and link button and ActionListener. Hope it will make things more clear for you.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonSample extends JFrame implements ActionListener {
public ButtonSample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(100, 100);
setLocation(100, 100);
JButton button1 = new JButton("button1");
button1.addActionListener(this);
add(button1);
setVisible(true);
}
public static void main(String[] args) {
new ButtonSample();
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
}
}
Fist you initialize the button, then add ActionListener to it
JButton btn1=new JButton();
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hillClimb();
}
});
You need to add an event handler (ActionListener in Java) to the JButton.
This article explains how to do this.
btnMyButton.addActionListener(e->{
JOptionPane.showMessageDialog(null,"Hi Manuel ");
});
with lambda

ChangeListener JButton Issue

I am trying to create buttons that change the color of an object when they are pressed. However the object changes color whenever my mouse merely hovers over the button. Am I using the wrong listener? I'm not sure where I'm going wrong. Thanks in advance.
blue.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
object.setColor(color.blue);
objectIcon.repaint();
}
}
);
Try to use an ActionListener on the button.
E.g.
blue.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
object.setColor(color.blue);
objectIcon.repaint();
}
});

KeyListener not reacting

Im trying to use a KeyListener to do something when the button m is pressed, it needs to add an image to a JPanel, however it doesn't do anything :/
I use :
public void keyPressed(KeyEvent e) {
if(e.getKeyChar()==('m')){
panel.add(mario);
Thread marioS = new AePlayWave("sm64itsamemario.wav");
marioS.start();
}
}
});
Edit:
The answer is to set the focus to the panel before trying to invoke the listener :)
so I added a mouselistener that sets the focus to the panel on click :
panel.addMouseListener( new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
panel.requestFocusInWindow();
});

Categories

Resources