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();
}
}
Related
I am trying to get the buttons to at least execute something when they are pressed and BlueJ doesn't show any errors, but when I execute the Program and I try to press the buttons, nothing happens. I am really unsure why that is the case. I would appreciate any help!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MainMenu
{
JFrame frame= new JFrame();
JButton button = new JButton("Singleplayer");
JButton button2 = new JButton("Multiplayer");
MainMenu(){
prepareGUI();
}
public void prepareGUI(){
frame.setTitle("Game");
frame.getContentPane().setLayout(null);
frame.add(button);
frame.add(button2);
button.setBounds(100,200,100,40);
button2.setBounds(200,200,100,40);
frame.setVisible(true);
frame.setBounds(200,200,400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setUpButtonListeners(){
ActionListener buttonlistener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.green);
System.out.println("Singleplayer Selected");
}
};
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame.getContentPane().setBackground(Color.red);
System.out.println("Multiplayer Selected");
}
};
button.addActionListener(buttonlistener);
button2.addActionListener(buttonlistener2);
}
public class MainClass {
public void main(String args[] )
{
new MainMenu();
}
}
}
setUpButtonListeners() are not executed in the program. So action listeners are not available. you can include setUpButtonListeners() in prepareGUI method.
I would like to create the simple window where one button will be.
When I will press him is supposed to be printed out "test" and when I will press F5 "F5".
I don't know what I am doing badly
I apologize for my English I still studying
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Okienko extends JFrame implements ActionListener , KeyListener
{
static Okienko frame;
JButton bTest;
public Okienko()
{
setLayout(null);
frame = this;
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setTitle("test");
frame.setLocation(150, 150);
frame.setSize(200, 400);
bTest = new JButton("Test");
bTest.setBounds(20, 50, 120, 20);
frame.add(bTest);
bTest.addActionListener(this);
frame.addKeyListener(this);
//frame.setFocusable(false);
//frame.requestFocus();
requestFocusInWindow();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == bTest)
{
System.out.println("Test");
}
}
#Override
public void keyPressed(KeyEvent e)
{
int id = e.getKeyCode();
if (id == KeyEvent.VK_ESCAPE)
{
this.dispose();
}
if (id == KeyEvent.VK_F5)
{
System.out.println("F5");
}
}
#Override
public void keyReleased(KeyEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
public static void main(String[] args)
{
new Okienko();
}
}
For example, you can enable keyboard focus for a component by calling the setFocusable(true) method on it.
Add in constructor:
setFocusable(true);
More info here: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
add
btest.setFocusable(false);
So I am trying to make a menu in swing of 8 functions. This code i have right now.
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Menu extends JFrame {
public Menu(){
init();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
Menu menu = new Menu();
menu.setVisible(true);
}
});
}
private void init() {
setTitle("Group 2");
setSize(300, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton quitButton = new JButton("E(X)it");
quitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
createLayout(quitButton);
JButton nameAsk = new JButton("What is your name?");
nameAsk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
}
});
createLayout(nameAsk);
}
private void createLayout(JComponent... arg){
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(arg[0]));
gl.setVerticalGroup(gl.createSequentialGroup().addComponent(arg[0]));
}
}
The problem is when i add one more button the other one goes away. I think its on top of other button but i am confused now.
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
}
});
Is it possible to check if a jtextfield has been selected / de-selected (ie the text field has been clicked and the cursor is now inside the field)?
//EDIT
thanks to the help below here is a working example
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class test extends JFrame {
private static JPanel panel = new JPanel();
private static JTextField textField = new JTextField(20);
private static JTextField textField2 = new JTextField(20);
public test() {
panel.add(textField);
panel.add(textField2);
this.add(panel);
}
public static void main(String args[]) {
test frame = new test();
frame.setVisible(true);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
System.out.println("selected");
}
#Override
public void focusLost(FocusEvent e) {
System.out.println("de-selected");
}
});
}
}
You will need to use the focusGained and focusLost events to see when it has been selected, and when it is deselected (i.e. gained/lost focus).
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class Main {
public static void main(String args[]) {
final JTextField textField = new JTextField();
textField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
//Your code here
}
#Override
public void focusLost(FocusEvent e) {
//Your code here
}
});
}
}
You may try isFocusOwner()
Is it possible to check if a jtextfield has been selected / de-selected
Yes, use focusGained and focusLost events.
the text field has been clicked and the cursor is now inside the field ?
Use isFocusOwner() which returns true if this Component is the focus owner.
if( ((JFrame)getTopLevelAncestor()).getFocusOwner() == textField ) {
....
}