I have a bunch of JLabels and i would like to trap mouse click events. at the moment i am having to use:
public void mouseClicked(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
System.out.println("Welcome to Java Programming!");
}
I was wondering if there is a tidier way of doing this instead of having a bunch of events I do not wish trap?
EDIT:
class MyAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent event) {
System.out.println(event.getComponent());
}
}
the above works but netBeans says add #override anotation. what does this mean?
EDIT: ok got it. fixed and solved.
Use MouseAdapter()
An abstract adapter class for receiving mouse events. The methods in this class are empty. This class exists as convenience for creating listener objects.
So you need to implement only the method you like such as following example:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
public MainClass() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
System.out.println(me);
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
One could use a MouseAdapter class, which implements the MouseListener interface, so one does not need to implement all the methods.
However, by overriding the methods of interest, one can get the desired behavior. For example, if one overrides the mouseClicked method, then one can define some behavior for the mouse click event.
For example (untested code):
JLabel label = new JLabel("Hello");
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Clicked!");
}
});
In the code above, the JLabel will print "Clicked!" to the console upon being clicked on.
You can extend MouseAdapter instead, and just override the events you're really interested in.
You can inherit from java.awt.event.MouseAdapter and only override the methods for the event(s) you are interested in.
some example of mouse event clicked,
in the same way you can use mousePressed or other mouse events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Work1 extends JFrame{
private JPanel panelNew;
public Work1(){
super("Work 1");
// create Panel
panelNew = new JPanel();
panelNew.setLayout(null);
panelNew.setBackground(Color.cyan );
add(panelNew);
// create Button
JButton btn = new JButton("click me");
// position and size of a button
btn.setBounds(100, 50, 150, 30);
panelNew.add(btn);
// add event to button
btn.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
// change text of button after click
if (btn.getText() == "abraCadabra"){
btn.setText("click me again") ;
}
else btn.setText("abraCadabra");
}
});
}
public static void main(String[] args){
Work1 go1 = new Work1();
go1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go1.setSize(320,200);
go1.setVisible(true);
}
}
Related
I have a main window:
public class MainPanel extends JFrame implements MouseListener {
public MainPanel() {
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(this);
ChildPanel child = new ChildPanel();
add(child);
JPanel spacer = new JPanel();
spacer.setPreferredSize(new Dimension(50, 50));
add(spacer);
pack();
setLocationRelativeTo(null);
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse click event on MainPanel");
}
}
And a child JPanel:
public class ChildPanel extends JPanel implements MouseListener {
public ChildPanel() {
setBackground(Color.RED);
setPreferredSize(new Dimension(200, 200));
//addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse click event on ChildPanel");
}
}
With the call to addMouseListener commented out in the child panel, the parent receives click events when I click anywhere in the window, including on the child. If I uncomment that call and click on the child panel, only the child receives the click event and it doesn't propagate to the parent.
How do I stop the event from being consumed by the child?
In Swing, you generally want the clicked component to respond; but you can forward the mouse event to the parent, as shown below. Here's a related example.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/questions/3605086 */
public class ParentPanel extends JPanel {
public ParentPanel() {
this.setPreferredSize(new Dimension(640, 480));
this.setBackground(Color.cyan);
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked in parent panel.");
}
});
JPanel child = new JPanel();
child.setPreferredSize(new Dimension(320, 240));
child.setBackground(Color.blue);
child.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked in child panel.");
ParentPanel.this.processMouseEvent(e);
}
});
this.add(child);
}
private void display() {
JFrame f = new JFrame("MouseEventTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ParentPanel().display();
}
});
}
}
I don't think you can. I believe it's a Swing design principle that only one component receives an event.
You can get the behavior you want, however, but pass the JFrame to the ChildPanel and calling its mouseClicked(MouseEvent) or whatever method you want. Or just get the parent component.
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse click event on ChildPanel");
this.frame.mouseClicked(e);
getParent().mouseClicked(e);
}
I have a jframe that includes JButton.I have six buttons in this frame, but I don't know how to define action listener for this buttons.please help to solve this problem.
First you have to import the package java.awt.event.* to enable events. After the class name you have to add implements ActionListener so that the class can handle events. When you have created the buttons you have to add an actionlistener to each button. Since you haven't showed which code you use I make an example with a simple program that counts votes, if the user clicks the yesButton the votes are increased with 1 and if the user clicks the noButton the votes are decreased with 1.
Here is the code to add an ActionListener to each button:
yesButton.addActionListener(this);
noButton.addActionListener(this);
Then write the following code to handle the events:
public void actionPerformed(ActionEvent e) {
JButton src = (JButton) e.getSource();
if(src.getActionCommand().equals("Yes")) {
yesCount++;
} else {
noCount++;
}
label.setText("Difference: " + (yesCount - noCount));
}
If you have 6 buttons you need to have an if statement and then 5 "else if" statements instead of only an if and an else statement.
Have a look at the Java tutorials on how to use ActionListeners:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Here's a simple example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Hello extends JPanel implements ActionListener {
JButton button;
public Hello() {
super(new BorderLayout());
button = new JButton("Say Hello");
button.setPreferredSize(new Dimension(180, 80));
add(button, BorderLayout.CENTER);
button.addActionListener(this); // This is how you add the listener
}
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e) {
System.out.println("Hello world!");
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Hello");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Hello();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
buttons have a method called addActionListener, use that for adding the action listener that you can implement for the click...
Example:
dummyButton = new JButton("Click Me!"); // construct a JButton
add(dummyButton); // add the button to the JFrame
dummyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(" TODO Auto-generated method stub");
}
});
It's really simple.
I suppose you have an instance of your button, right? Let's say that instance is called myButton.
You can just add an action listener by calling addActionListener:
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do whatever you like here
}
});
Protip: next time you don't know what method to call, just type the instance name and .. Then, your IDE will show you all the methods you can call, unless you are not using an IDE. If that is the case, download one.
I am currently having trouble with being able to change the choiceDeclaration JLabel. My mindset behind the choiceDeclaration JLabel is to simply display text based on which JButton is clicked.
Here is my current code for the project:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.event.*;
public class prompt {
public static void main(String []args) {
/* Setting up the JPanel and its necessities for this program */
JFrame choicePrompt = new JFrame("Rock, Paper, Scissors Game");
JPanel choicePanel = new JPanel();
JButton rockButton = new JButton("ROCK");
JButton scissorsButton = new JButton("SCISSORS");
JButton paperButton = new JButton("PAPER");
JLabel choiceDeclaration = new JLabel();
choicePrompt.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
choicePrompt.setResizable(false);
choicePrompt.setSize(300, 300);
choicePrompt.setVisible(true);
choiceDeclaration.setVisible(true);
choicePrompt.add(choicePanel);
choicePanel.add(choiceDeclaration);
choicePanel.add(rockButton);
choicePanel.add(scissorsButton);
choicePanel.add(paperButton);
choiceDeclaration.setVerticalTextPosition(JLabel.TOP);
choiceDeclaration.setHorizontalTextPosition(JLabel.CENTER);
/* ActionListeners for the JButtons */
rockButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
/*I have not placed any code in here because I have not gotten that far*/
}
});
scissorsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
/*I have not placed any code in here because I have not gotten that far*/
}
});
paperButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
/*I have not placed any code in here because I have not gotten that far*/
}
});
}
}
I cannot use a setText method in my ActionListeners as shown below because it conflicts with my main class method a line below the declaration of my class. They are both using String in their parameters.
public static void main(String []args) {
rockButton.addActionListener(new ActionListener() {
setText(String text) {
}
}
}
My concluding thought was to make another class that could use the setText method to change the JLabel on that frame. However, since JLabels cannot be called from one class to another like variables or methods, I am having trouble trying to implement this idea.
Have a separate method for it...
public static void settext() {
setText(String text)
}
then call it in your action listener...
rockButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
settext();
}
});
I hope this is what you meant! :)
I want to be able to add the ActionListener to the JButton but cannot seem to get it to work properly.
I have tried to add the ActionListeneer and also the ActionEvent and neither seems to fire the ActionPerformed method.
I did not one curious aspect was the the compiler made me take off the #Override keyword since the interface is used to create a variable and not implemented.
Does this make a difference? I am certain that you can do it this way but I think I am just a bit off the mark.
Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class testInterfaces2 {
static ActionListener m;
static ActionEvent me;
testInterfaces2() {
}
public void actionPerformed(ActionEvent e) {
System.out.println("Mouse Clicked");
}
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JButton pButton = new JButton("Print");
pButton.addActionListener(m);
//pButton.addActionListener(m.actionPerformed(me));
f.add("Center", pButton);
f.pack();
f.setVisible(true);
}
}
It should be like this and remove ActionListener and ActionEvent variables that is not needed.
public class testInterfaces2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Mouse Clicked");
}
...
JButton pButton = new JButton("Print");
pButton.addActionListener(this);
}
#Override doesn't do any thing extra other than compile time checking of the overridden method.
In simple term, You need a class that implements ActionListener and obviously implements actionPerformed() method. Simply create a object of that class and pass in addActionListener() method.
I did not one curious aspect was the the compiler made me take off the
#Override keyword since the interface is used to create a variable and
not implemented.
This should have highlighted your first problem, your testInterfaces2 class can't override actionPerformed as it's not defined in any part of the parent class or it's parents. This is because testInterfaces2 doesn't implement ActionListener directly or indirectly (via inheritance).
Your second problem is m is null, you've never initialised it
Take a closer look at How to write ActionListeners for more details
I think it's best to define a new ActionListener for each button. Like this
JButton pButton = new JButton();
pButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
System.exit(0);
}
});
I have added JLabel on my JFrame object. I want to implement a key listener on JLabel. Can I implement it? If yes, how can I do that?
You might not want to add a KeyListener on a JLabel. It would be better if you would add it to the JFrame.
Supposing you have the following code structure, then it should work:
public class MyFrame extends JFrame {
private JLabel jLab;
//...fields, getters, setters whatever...
private int i;
public MyFrame()
{
i = 0;
jLab = new JLabel("Example");
addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent ke) {
//doSomething(); - this may create confusion.
}
#Override
public void keyReleased(KeyEvent ke) {
//doSomething(); - this may create confusion.
}
#Override
public void keyTyped(KeyEvent ke) {
doSomething();
}
});
add(jLab);
pack();
setVisible(true);
}
private void doSomething() {
i++;
jLab.setText(i + "");
}
}
And, don't forget to import!
import javax.swing.*;
import java.awt.event.*;
RESULT: when you create a new MyFrame in the main() method. This is what you see at first:
After five random key-strokes,
Guess I'm a bit too late but calling label.requestFocus(); after adding the key listener to the label works for me!
Key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys.
BUT JLabel is not one of those components.