JButton with both ActionListener / MouseListener - java

Is it possible to create a Jbutton with both an ActionListener and MouseListener
Meaning so i create a button and then when i press it ( throught actionListener) it changes the frame so that AFTER then button was pressed i can press anywhere on the frame and MouseListener would in use.
JButton button = new JButton();//Creates Button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Insert MouseListener
//Then do something with mouseListener
}
});
Heres the curent code: however they're now in sync when i try to click the button and i cannot call mouseListener a 2nd time
JButton button2 = new JButton("Click");
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked the button");
newCube.stopCube();
}
});
button2.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mousePressed(java.awt.event.MouseEvent evt)
{
double x = evt.getX();
double y = evt.getY();
newCube.setCube(x,y);
}
});

If you want to move something by clicking on it, you can use a mouse listener on that node directly, instead of using it on the button.
To add both the action listener and a mouse listener on a button, you can use the addActionListener and addMouseListener methods on the button.
Look at the api for information about these methods... http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html

If I understood you correctly, this sample might help you (add this to your own ActionListener)
#Override
public void actionPerformed(ActionEvent e) {
((JButton)e.getSource()).addMouseListener(yourMouseListener);
}
I tried this, it works.

Here is example with JToggleButton which add/remove MouseListener to JFrame.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class Example extends JFrame {
private MouseAdapter mouseListener;
public Example(){
init();
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void init() {
mouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("clicked");
}
};
setLayout(new FlowLayout());
JToggleButton b = new JToggleButton("add listener");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(((JToggleButton)e.getSource()).isSelected()){
Example.this.addMouseListener(mouseListener);
((JToggleButton)e.getSource()).setText("remove listener");
} else {
Example.this.removeMouseListener(mouseListener);
((JToggleButton)e.getSource()).setText("add listener");
}
}
});
add(b);
}
public static void main(String... s){
new Example();
}
}
EDIT: examle with JButton:
public class Example extends JFrame {
private MouseAdapter mouseListener;
public Example(){
init();
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void init() {
mouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("clicked");
}
};
setLayout(new FlowLayout());
JButton b = new JButton("add listener");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(((JButton)e.getSource()).getText().equals("add listener")){
Example.this.addMouseListener(mouseListener);
((JButton)e.getSource()).setText("remove listener");
} else {
Example.this.removeMouseListener(mouseListener);
((JButton)e.getSource()).setText("add listener");
}
}
});
add(b);
}
public static void main(String... s){
new Example();
}
}

What you want to do is still not clear to me. Though this can help you. It will add a mouse listner to the component when the start button is clicked and remove the mouse listner when stop button is clicked. Thus you can stop the two listeners from working in sync..
JButton startButton = new JButton();
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Add MouseListener to move the component
}
});
JButton stopButton = new JButton();
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Remove the MouseListener
}
});

Related

Keybinding not calling AbstractAction

I am making a game where the user has to press keys to move around. I am using keybindings but they are not working. The keybindings are supposed to call the Wp class and print "W pressed", but nothing happens. Here's the code:
public class SO extends JFrame {
public static void main(String[] args) {
new SO();
}
C c;
public SO(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
c=new C();
c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("W"), "wp");
c.getActionMap().put("wp", new Wp());
this.setVisible(true);
}
private class C extends JComponent {
public void paint(Graphics g){}
}
private class Wp extends AbstractAction {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("W pressed");
}
}
}
Use Action to call like component.getActionMap().put("doSomething", anAction);
Refer Key Binding for more information. Below is a sample code I have referred in another Stackoverflow Question reference link SO Ref link
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonBinding {
private JPanel contentPane;
private JTextField tField;
private JButton button;
private KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
private Action action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Action Performed");
contentPane.setBackground(Color.BLUE);
}
};
private MouseAdapter mouseActions = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent me) {
System.out.println("Mouse Entered");
JButton button = (JButton) me.getSource();
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "enter");
button.getActionMap().put("enter", action);
}
#Override
public void mouseExited(MouseEvent me) {
System.out.println("Mouse Exited");
JButton button = (JButton) me.getSource();
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "none");
contentPane.setBackground(Color.RED);
}
};
private void displayGUI() {
JFrame frame = new JFrame("Button Binding Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
tField = new JTextField(10);
button = new JButton("Click Me");
button.addMouseListener(mouseActions);
contentPane.add(tField);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ButtonBinding().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

How do make a button set a variable

I'm coding something to work on a game and I've been having trouble trying to make a button set the variable "weapon".
import static java.lang.System.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UntitledProject {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public UntitledProject() {
prepareGUI();
}
public static void main(String[] args) {
UntitledProject prepare = new UntitledProject();
String weapon = prepare.weapon();
}
private void prepareGUI() {
mainFrame = new JFrame("Untitled Project");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public String weapon() {
headerLabel.setText("Pick Weapon");
JButton button1 = new JButton("Sword");
JButton button2 = new JButton("Lance");
JButton button3 = new JButton("Axe");
JButton submitButton = new JButton("Submit");
String weapon = "";
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Sword selected.");
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
weapon = "Sword";
exit(0);
}
});
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Lance selected.");
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
weapon = "Lance";
exit(0);
}
});
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Axe selected.");
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
weapon = "Axe";
exit(0);
}
});
}
});
controlPanel.add(button1);
controlPanel.add(button2);
controlPanel.add(button3);
controlPanel.add(submitButton);
mainFrame.setVisible(true);
}
I need for when the submit button is pressed the weapon variable is changed to what button was pressed before the submit button.
Make an instance variable.
private JPanel controlPanel; // under this line
private String weapon;
Then everywhere else, remove String in front of weapon because this makes a new, local variable.
Then, you can remove this line
String weapon = "";
To set the sword, for example, use UntitledProject.this.weapon to explicitly set the instance variable.
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Sword selected.");
UntitledProject.this.weapon = "sword";
Do the same for the other buttons.
Then, additionally, the submit button only needs it's action to be set once, not everytime you set a weapon.
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Axe selected.");
UntitledProject.this.weapon = "Axe";
}
});
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exit(0);
}
});
And, does this app only pick one weapon, then exit?
exit(0);
This tells your whole app to quit with a 0 (success) code, not just close the current window
And since weapon is moved to an instance variable, you can change this to a void method (you weren't returning anything anyways)... Change
public String weapon() {
To
public void weapon() {
You will need to create a temp weapon variable to record the previously selected choice. Once a user selects a weapon update the weapon varible and the temp. Once submit is clicked assign temp to weapon variable and visa versa

Enable one JButton and disable another

There are two buttons in my ui which re-directs to two JFrames. 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 JFrames 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);
}
}
In your ActionListener for Button One, add
ButtonTwo.setEnabled(false);
and in the ActionListenerfor 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.
Check out the ButtonGroup for a more elegant solution.
http://docs.oracle.com/javase/tutorial/uiswing/components/buttongroup.html

How to count rightmouse clicks on java?

public class ClickButtonClass implements ActionListener
{
public void actionPerformed(ActionEvent cbc)
{
clickcounter++;
clicklabel.setText("Clicks: "+clickcounter);
}
}
I did this code for counting clicks. But it only counts left mouse clicks. How do I add right mouse clicks too?
Use MouseListener. Here is an example:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
JLabel label = new JLabel("click me");
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent me) {
if (SwingUtilities.isRightMouseButton(me)) {
System.out.println("right click");
} else {
System.out.println("left click");
}
});
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
Don't use an ActionListener.
Instead you should be using a MouseListener. Read the section from the Swing tutorial on How to Write a MouseListener for more information and examples.
To count rightclicks:
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Demo extends Frame {
Integer counter=0;
Button btn;
Label label;
public Demo() {
setLayout(new FlowLayout());
btn = new Button("OK");
label= new Label("Number of rightclicks: "+counter);
btn.addMouseListener(new MouseAdapter(){
public void mouseClicked (MouseEvent e) {
if (e.getModifiers() == MouseEvent.BUTTON3_MASK) {
counter++;
label.setText("Number of rightclicks: " +counter.toString());} }
});
add(btn);
add(label);
setSize(300,300);
setVisible(true);
}
public static void main(String args[]) {
new Demo();
}
}

Java JTextArea KeyListener

When I pressed the ENTER my JTextArea starts a new row and I only want do to the doClick() method nothing else.
How should I do that?
textarea.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
button.doClick();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Use .consume():
Consumes this event so that it will not be processed in the default
manner by the source which originated it.
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
e.consume();
button.doClick();
}
}
Documentation
You should use KeyBindings with any JTextComponent in question. KeyListeners are way too low level from Swing's perspective. You are using the concept which was related to AWT, Swing uses KeyBindings to do the same task with more efficiency and provides desired results :-)
A small program for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyBindingExample {
private static final String key = "ENTER";
private KeyStroke keyStroke;
private JButton button;
private JTextArea textArea;
private Action wrapper = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
button.doClick();
}
};
private void displayGUI() {
JFrame frame = new JFrame("Key Binding Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
textArea = new JTextArea(10, 10);
keyStroke = KeyStroke.getKeyStroke(key);
Object actionKey = textArea.getInputMap(
JComponent.WHEN_FOCUSED).get(keyStroke);
textArea.getActionMap().put(actionKey, wrapper);
button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.format("Button Clicked :-)%n");
}
});
contentPane.add(textArea, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new KeyBindingExample().displayGUI();
}
};
EventQueue.invokeLater(r);
}
}

Categories