Why is this event doing as much as the overall clicks? - java

I have two events that support the button and table by click mouse
if i click te button should remove the record from the list and table. It
happens but program display this exception ArrayIndexOutOfBoundsException:
-1
r.getjTable3().addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
System.out.println(e.getClickCount());
r.getjButton2().addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
String nazwa = r.getjTable3().getValueAt(r.getjTable3().getSelectedRow(), 3).toString();
System.out.println(r.getjTable3().getSelectedRow());
((DefaultTableModel)r.getjTable3().getModel()).removeRow(r.getjTable3().getSelectedRow());
for (Wydarzenie lista1 : lista)
{
if(nazwa==lista1.name)
{
lista.remove(lista1);
}
}
}
});
}
});

Related

How to assign a method to a button when pressed or released with ActionListener in Java?

I am new to coding GUIs in Java and I am trying to just print a message on the terminal when a button is pressed and another one when it is released.
This is what I have for a regular button pressing.
leftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Pressed");
}
});
I did this with the help of IntelliJ IDEA. I want to make the button send a message when pressed and a different thing when released.
You can just add a simple MouseAdapter, like this:
MouseAdapter ma = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Released");
}
};
leftButton.addMouseListener(ma);
frame.add(button);
This will detect when it is the mouse is pressed on the button or released on the button.
If you want, you can also add a mouseClicked() method, mouseExited(), mouseEntered(), mouseMoved(), and (many) more methods in your MouseAdapter. Check out this JavaDoc
Use custom class and use it
leftButton.getModel().addChangeListener(new BtnCusttomListener());
private class BtnCusttomListener implements ChangeListener {
private boolean pressed = false; // holds the last pressed state of the button
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel Buttonmodel = (ButtonModel) e.getSource();
// if the current state differs from the previous state
if (model.isPressed() != pressed) {
String text = "Button pressed: " + model.isPressed() + "\n";
textArea.append(text);
pressed = model.isPressed();
}
}
}
You can use a MouseListener instead:
leftButton.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
// The mouse button was pressed and released
}
#Override
public void mousePressed(MouseEvent e) {
// The mouse button was pressed
}
#Override
public void mouseReleased(MouseEvent e) {
// The mouse button was released
}
#Override
public void mouseEntered(MouseEvent e) {
// The cursor entered the bounds of the button (i.e. hovering)
}
#Override
public void mouseExited(MouseEvent e) {
// The cursor exited the bounds of the button
}
});

2 MouseListener in 2 different class Java

I have a problem with MouseListeners, in fact i have two java class, the first is a Menu with buttons, each button call a method with MouseListeners and a second one as a map, in the second class i have a method which use a MouseListener to locate a clic on the map, the problem is that this MouseListener doesn't work because of the listener in the first class button.
here is my code to have a clear idea :
First class (The Menu with buttons) :
button4.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
//button4.removeMouseListener (button4.getMouseListeners()[0]);
//System.out.println("Mouse Free");
map.locateClick() ;
}
});
Second Class : (The map)
// Mouse Listener
public void mouseEntered(MouseEvent e) { } ;
public void mouseExited(MouseEvent e) { } ;
public void mousePressed(MouseEvent e) { } ;
public void mouseReleased(MouseEvent e) { } ;
public void mouseClicked(MouseEvent e) {
this.ClickIsHere = true ;
this.XClick = e.getX() ;
this.YClick = e.getY() ;
synchronized (lock) {
lock.notify() ;
}­­­­­­

I'm having trouble choosing when to use a MouseListener object

Sorry for the bad title, I couldn't think of a better way to phrase it.
Anyway, I need my JLabel to have a different MouseListener when there are more than 2 objects in the same container. I'm trying to make a calendar program so there are 42 panels that these labels are added to. When there are too many labels, I want the last one to be able to open a window that will show the rest.
Right now, when there is more than 2 labels, the last label has both the mouseListener from inside the if (number_of_labels[index-7]) statement and from the if (mouseListenerActive) statement.
This method is called in a loop elsewhere. If you need to see anything else, I'll add it.
public static void insertLabel(String text, final int index, Color colour) {
final JLabel label = new JLabel();
label.setText(text);
label.setOpaque(true);
label.setBackground(colour);
mouseListenerActive = true;
if (number_of_labels[index-7] == 2) {
label.setBackground(Color.RED);
JLabel last_label = (JLabel) calendar_boxes[index].getComponent(2);
last_label.setText(" ▼");
last_label.setForeground(Color.WHITE);
last_label.setBackground(Color.BLACK);
mouseListenerActive = false;
last_label.addMouseListener(new MouseListener() {
#Override public void mouseExited(MouseEvent e) {}
#Override public void mouseEntered(MouseEvent e) {}
#Override public void mouseReleased(MouseEvent e) {}
#Override public void mousePressed(MouseEvent e) {}
#Override
public void mouseClicked(MouseEvent e) {
//int day = index - (position of last day - number of days in current month)
int day = index - (Integer.parseInt(monthDataNode.getChildNodes().item(Main.year-1900).getChildNodes().item(Main.month_index-1).getTextContent()) - Constants.month_lengths[Main.month_index-1]);
calendarList.open(day, Main.month_index-1, Main.year);
}
});
} else if (number_of_labels[index-7] > 2) {
return;
}
if (mouseListenerActive) {
label.addMouseListener(new MouseListener() {
#Override public void mouseExited(MouseEvent e) {}
#Override public void mouseEntered(MouseEvent e) {}
#Override public void mouseReleased(MouseEvent e) {}
#Override public void mousePressed(MouseEvent e) {}
#Override
public void mouseClicked(MouseEvent e) {
//int day = index - (position of last day - number of days in current month)
int day = index - (Integer.parseInt(monthDataNode.getChildNodes().item(Main.year-1900).getChildNodes().item(Main.month_index-1).getTextContent()) - Constants.month_lengths[Main.month_index-1]);
calendarEdit.open(day, Main.month_index-1, Main.year, label.getText());
}
});
}
calendar_boxes[index].add(label, new AbsoluteConstraints(19, 6+(15*number_of_labels[index-7]), 40, 12));
number_of_labels[index-7]++;
}
In your code, before you add the second MouseListener, remove the first. As you are using anonymous classes and don't have a reference to the original MouseListener, use the following:
MouseListener existingListener = last_label.getMouseListeners()[0];
last_label.removeMouseListener(existingListener);

Incorporating ActionListener to MouseMotionListener in java

How can I incorporate the actionPerformed() to mouseMoved()?
This is my code:
public void mouseMoved(MouseEvent e) {
if(e.getSource()==app.p1){
????
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1)
????
}
b1 is a JButton which says "red" and p1 is a panel which is colored with blue.
I want a result that when I click b1, I would get a color. And when I move my mouse to p1, p1 will change color from blue to red. How do I do this.
Any help would be much appreciated. :)
Something like:
public void mouseMoved(MouseEvent e) {
if(e.getSource()==app.p1){
//get the color stored in the variable and set it as background
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1)
//get color and store it in like a variable
}
I can't directly do this because p1 will be filled without moving the mouse over it:
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1)
p1.setBackground(Color.RED);
}
Instance Variable:
String colorString = ""
Event handlers:
public void mouseMoved(MouseEvent e) {
if(e.getSource()==app.p1){
app.p1.setBackground(Color.getColor(this.colorString));
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1)
this.colorString = e.getActionCommand();
}
}
This uses the text on the button to determine color. Note that if the String is an invalid color name it won't work.
first define a flag in the class
public boolean isBtnClicked = false;
and now add actionListener as you want
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
isBtnClicked = true;
}
});
and the same with mouse events
P1.addMouseListener(new MouseListener(){
#Override
public void mouseEntered(MouseEvent e) {
if(isBtnClicked)
{
b1.setBackground(Color.RED);
isBtnClicked = false;
}
}
//Other overriden methods
...
});

Adding Mouse listener to multiple JLabel

for(int k=0;k< dtm.getRowCount();k++) //dtm is object of default table model
{
if(String.valueOf(dtm.getValueAt(k,1)).equalsIgnoreCase("Today") && check==0 )
{
cnt++;
JLabel jp=new JLabel();
panel.add(jp);
panel.setLayout(null);
if(cnt<=12)
{
jp.setBounds(j,500,100,100);
j=j+115;
jp.addMouseListener(this);
}
else
{
j=j-115;
jp.setBounds(j,400,100,100);
}
String b="<html><body text=#FDFA0B>"+String.valueOf(dtm.getValueAt(k,0))+"'s Birthday";
jp.setText(b);
jp.setFont(new java.awt.Font("comicbd",Font.ITALIC+Font.BOLD, 14));
}
}
It will not work mouselister only apply for last placed Label...
I want to apply mouse listener for all label how can I do that ..
please help me ....
Without SSCCE I can tell you that you're adding listener on 3 conditions:
String.valueOf(dtm.getValueAt(k,1)).equalsIgnoreCase("Today")
check == 0
and if(cnt<=12)
Other JLabels (that don't pass these conditions) haven't assigned your listener.
Make sure that you're clicking correct labels.
Or move jp.addMouseListener(this); just after JLabel creation (if you want to add listener to all your JLabels).
You certainly can add the same MouseListener to multiple components - here's an example in it's simplest form:
MouseListener ml = new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {System.out.println("Released!");}
#Override
public void mousePressed(MouseEvent e) {System.out.println("Pressed!");}
#Override
public void mouseExited(MouseEvent e) {System.out.println("Exited!");}
#Override
public void mouseEntered(MouseEvent e) {System.out.println("Entered!");}
#Override
public void mouseClicked(MouseEvent e) {System.out.println("Clicked!");}
};
JLabel j1 = new JLabel("Label1");
j1.addMouseListener(ml);
JLabel j2 = new JLabel("Label2");
j2.addMouseListener(ml);
BUT according to your code, you're messing with a JTable - and JTable's act differently than you're thinking. The labels you're trying to edit are actually part of a TableCellEditor. The JTable uses the single TableCellEditor (read: single JLabel) to display every cell in the JTable. This is why you're only seeing the Listener applied to the last cell (because that's the only the last cell has a full component any more - the rest are just ghosts of where the component was applied before).
The good news is you can add a MouseListener to the JTable, and obtain information from there:
final JTable table = new JTable();
MouseListener ml = new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
};
table.addMouseListener(ml);
One Option is to add another inner class:
class MListener extends MouseAdapter{
public void mouseReleased(MouseEvent e) {}
//other mouse evetns
}
then rather then:
jp.addmousListener(this);
do:
jp.addMouseListener(new MListener());

Categories