Kind of a noob question, but then again, I am a noob. I'm trying to implement a sort of "universal" mouse listener. That is, when I click any of the objects on screen, it runs a specific amount of code. I have the current solution below, but the code I want to run is the same for 10 different objects, so this gets rather tedious.
difference2 = new JLabel(new ImageIcon("transparent.png"));
difference2.setBounds(645,490,10,10); //left, top, width, height
contentPane.add(difference2);
difference2.setVisible(true);
difference2.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
//code
}
});
I am aware I can create a separate method such as the following
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(null,"this would be nice");
}
But I can't figure out how to set up a mouse listener on every object for it. The JOptionPane currently does nothing.
I might have misread your question, but if you want the same mouselistener on various objects,you could store the instance of your listener in a variable once and then add it to whatever gui object you want it added to.
MouseListener ml = new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {//code}
#Override
public void mousePressed(MouseEvent e) {//code}
#Override
public void mouseExited(MouseEvent e) {//code}
#Override
public void mouseEntered(MouseEvent e) {//code}
#Override
public void mouseClicked(MouseEvent e) {//code}
};
JLabel j1 = new JLabel("Label1");
j1.addMouseListener(ml);
JLabel j2 = new JLabel("Label2");
j2.addMouseListener(ml);
You can create an instance of an anonymous class that extends MouseAdapter and assign it to a variable that you can reuse (myMouseListener in this case):
MouseListener myMouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(null,"this would be nice");
}
};
difference2.addMouseListener(myMouseListener);
aSecondObject.addMouseListener(myMouseListener);
aThirdObject.addMouseListener(myMouseListener);
...
Related
I am trying to connect a button to say "Hi" when the mouse enters it and "Bye" when the mouse leaves. I have been using mouse events with a MouseListener but to no avail.
I'm new to Java and this question has been plaguing me for the last 2 days and I just have not been able to figure it out. Any help would be greatly appreciated.
private abstract class HandlerClass implements MouseListener {
}
private abstract class Handlerclass implements MouseListener {
#Override
public void mouseEntered(java.awt.event.MouseEvent e) {
mousebutton.setText("Hi");
}
#Override
public void mouseExited(java.awt.event.MouseEvent e) {
mousebutton.setText("Bye");
}
}
Try like this. It is working for me.
public class ChangeTextMouseEvent extends Frame
{
static JButton btn;
public ChangeTextMouseEvent()
{
setTitle("ChangeText");
btn = new JButton("SSS");
add(btn);
setVisible(true);
setBounds(0, 0, 100, 100);
}
public static void main(String[] args)
{
ChangeTextMouseEvent frame = new ChangeTextMouseEvent();
btn.addMouseListener(new MouseAdapter(){
#Override
public void mouseExited(MouseEvent e)
{
btn.setText("Bye");
}
#Override
public void mouseEntered(MouseEvent e)
{
btn.setText("Hi");
}
});
}
}
Updating the UI component alone is often not enough; you also have to trigger a repaint action.
In other words: there are two "layers" here. One is the "data model" (where some button knows about its text); the other is the actual "graphical content". The later one comes into existence by somehow displaying the first parts. Therefore both layers need to be addressed in order to make your chances visible to the user.
See here for some examples around that.
(Note: I am aware of the existence of the MouseAdapter-class, but since I am probably overriding all methods later on, the advantage of it is lost?)
I have a class MainProgram.java in which I'm adding several components. Most of them have a Listener (ActionListener, MouseListener, ...), which get's a bit crowded in my main class.
Therefore I am trying to "externalize" those Listeners into their own classes. So far I have used inner classes in my main-class, which makes accessing the variables, components, ... pretty easy and straightforward.
But with the external Listeners I am not sure what is the best way to implement them.
For example, when I want to find out, which of the lables has been clicked, I am getting the event, get the source of the event, cast it to a JLabel and then get the text on the label with which I compare a string!
This works, but seems very prone to errors (what if I change the JLabel-text in my main-class? -> Listener breaks) and pretty unclean.
I've tried to search via google and on StackOverflow for better ways to do this, but only found the inner class approach.
So is there a better way to get access to my components / externalize my listeners?
public class MainProgram extends JFrame {
public MainProgram() {
super("Landing Page");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel westPanel = new JPanel();
JLabel lbl_orderStatus = new JLabel("Order Status");
JLabel lbl_technicalDocu = new JLabel("Technical Documentation");
JLabel lbl_checkReport = new JLabel("Check Report");
MouseListenerBoldFont mouseListenerLabelBoldPlain = new MouseListenerBoldFont();
lbl_orderStatus.addMouseListener(mouseListenerLabelBoldPlain);
lbl_technicalDocu.addMouseListener(mouseListenerLabelBoldPlain);
lbl_checkReport.addMouseListener(mouseListenerLabelBoldPlain);
westPanel.add(lbl_orderStatus);
westPanel.add(lbl_technicalDocu);
westPanel.add(lbl_checkReport);
add(westPanel);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MainProgram window = new MainProgram();
window.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
The MouseListenerBoldFont.java:
public class MouseListenerBoldFont implements MouseListener{
Object lbl_westPanel;
#Override
public void mouseClicked(MouseEvent e) {
if(((JLabel)e.getSource()).getText().equals("Order Status")){
System.out.println("Order Status clicked");
};
if(((JLabel)e.getSource()).getText().equals("Technical Documentation")){
System.out.println("Technical Documentation clicked");
};
if(((JLabel)e.getSource()).getText().equals("Check Report")){
System.out.println("Check Report clicked");
};
}
#Override
public void mouseEntered(MouseEvent e) {
lbl_westPanel = e.getSource();
((JComponent) lbl_westPanel).setFont(new Font("tahoma", Font.BOLD, 12));
}
#Override
public void mouseExited(MouseEvent e) {
lbl_westPanel = e.getSource();
((JComponent) lbl_westPanel).setFont(new Font("tahoma", Font.PLAIN, 11));
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
}
sure this is not the best way but may be useful for your problem
public class MyLabel extends JLabel implements MouseListener {
public MyLabel() {
addMouseListener(this);
}
public MyLabel(String txt) {
super(txt);
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
System.out.println(getText() + " clicked");
}
public void mouseEntered(MouseEvent e) {
setFont(new Font("tahoma", Font.BOLD, 12));
}
public void mouseExited(MouseEvent e) {
setFont(new Font("tahoma", Font.PLAIN, 11));
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
}
then
JLabel lbl_orderStatus = new MyLabel("Order Status");
JLabel lbl_technicalDocu = new MyLabel("Technical Documentation");
JLabel lbl_checkReport = new MyLabel("Check Report");
// MouseListenerBoldFont mouseListenerLabelBoldPlain = new MouseListenerBoldFont();
//
// lbl_orderStatus.addMouseListener(mouseListenerLabelBoldPlain);
// lbl_technicalDocu.addMouseListener(mouseListenerLabelBoldPlain);
// lbl_checkReport.addMouseListener(mouseListenerLabelBoldPlain);
My recommendation is to write inline (anonymous-class) handlers that forward the actual handling to another, non-anonymous function. This would give you something like:
JLabel lblOrderStatus = new JLabel("Order Status");
lblOrderStatus.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
doWhateverClickOnOrderStatusRequires();
}
});
// much later
private void doWhateverClickOnOrderStatusRequires() { ... }
The name of the external not-quite-handler method (doWhateverClickOnOrderStatusRequires) should capture the task that it attempts to achieve (for example, launchRockets); and with this pattern, you can call the same not-quite-handler method from multiple handlers. Since the compiler will check that the calls are valid a compile-time, there are no fragile string-constants involved.
You probably still want to use a class which extends MouseAdapter, since it can be used as a MouseListener, a MouseMotionListener, and a MouseWheelListener all at once (You just have to add it as all of those into a component). I'm not sure why you need to get the text on a JLabel to detect if it's the one that has been clicked. You should create a class which extends MouseAdapter and make it solely for JLabels, then add it to that JLabel. You should define a custom constructor if you want that takes a JLabel for an argument so that it will automatically know what JLabel is being interacted with. You can then add a method which passes an event to the main class.
I need to know how to effectively add a mouse event to a JComboBox or any other approach that works. I found some possible solutions here and also different sites but I can't get it to work. It seems that mouseEvent is not appropriate to use on JComboBox as it is a compound component. I found a possible solution for a compound component but also doesn't work. So below is my code that works when I use a text field. Any ideas of which approach should I use? Thanks
private void updateReviewers() {
jComboBox_reviewer.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("clicked");
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("pressed");
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("released");
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("entered");
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println("exited");
}
}
);
}
You ought to be able to use addActionListener(ActionEvent e) on the JComboBox itself. Once any item is selected you may perform any sort of validation within the action listener.
jcomboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JComboBox comboBox = (JComboBox) event.getSource();
Object o = comboBox.getSelectedItem();
//Any extra code
}
});
Ofcourse, Object may be cast to your desired Object type.
Oracle Documentation for Event handling with JComboBox
It is a program to make a JComboBox and make a sting array and use those array items and make the ComboBox's list items. Then link each item with an image. Then we start the Action Listener and provide an action to each of the list item. Note that you must save the images in the source folder of the project and the class folder.
package JComboBox;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<applet code="JComboBoxDemo" width=200 height=120></applet>
*/
public class JComboBoxDemo extends JApplet
{
JLabel jlab;
ImageIcon hourglass, digital, analog, stopwatch;
JComboBox <String> jcb;
String timepieces[] = {"Digital", "Analog", "Hourglass", "Stopwatch"};
String s;
public void init()
{
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeGUI();
}
});
}
catch(Exception exc)
{
System.out.println("Program can't run because of "+exc);
}
}
private void makeGUI()
{
setLayout(new FlowLayout());
jcb = new JComboBox<String>(timepieces);
add(jcb);
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".jpg"));
}
});
jlab = new JLabel(new ImageIcon());
add(jlab);
}
}
I am using an Icon with Java (Swing) JButton. Is it possible to change the icon when I take my mouse arrow over it?
I saw somewhere on Youtube that it is possible, but am unable to recall it.
You can take advantage of the JButton API which provides this kind of support.
Take a look at JButton#setRolloverIcon and JButton#setRolloverSelectedIcon
You will need to implement MouseListener like this:
public class YourClass extends JFrame implements MouseListener {
#Override
public void mouseEntered(MouseEvent e) { }
#Override
public void mouseExited(MouseEvent e) { }
#Override
public void mouseClicked(MouseEvent e) { }
#Override
public void mousePressed(MouseEvent e) { }
#Override
public void mouseReleased(MouseEvent e) { }
}
Add your function where needed.
You can override the mouseEntered() function by implementing a MouseListener and add the code to change the icon in that function.
If you're using an abstract button, you can just use setRolloverIcon() to set an image which will appear on rollOver.
I was making a program and I wanted to know how to make certain areas of a JFrame activate something when clicked, although without a button, like you clicked in the upper-right quarter of a picture to activate something.
Create an List of Shape objects to represent the areas that you want to click on:
List<Shape> shapes = new ArrayList<Shape>();
Then you can add different shapes to the List:
areas.add( new Rectangle(5, 5, 10, 10) );
Then you add a MouseListener to the frame and in the mousePressed event you would do something like:
for (Shape shape: shapes)
{
if (shape.contains(theMousePointFromTheMouseEvent)
// do something
}
create a JLabel object and set its icon to the image you want to display. Then add a mouse listener to the label object and implement all of its abstract classes especially the mouse clicked method to do what you want to do when clicked. Then when you click your JLabel you will see what you want.
The below code is an example to print "hello" when label is clicked:-
java.awt.event.MouseListener ml = new java.awt.event.MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("hello");
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
};
jLabel1.addMouseListener(ml);