I have:
class extended from JFrame;
an list of JTextField's elements - JTextField[] pix.
When clicking on pix[i] - JFrame must iconified and next click at any point of screen must changes exactly that textField (pix[i]) without any influence on another textFields, then frame must normalized and any mouseClicks after that (not on textField) couldn't influenced on that elements.
Clicks outside of JFrame processed with jnativehook library.
That part of code here:
for (int i = 0; i < pix.length; i++){
int tmp = i;
pix[i].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
}
});
}
});
P.S.: I've tried to use
GlobalScreen.removeNativeMouseListener(new NativeMouseAdapter() {
public void nativeMouseClicked(NativeMouseEvent e) {
}
});
but don't actually know how to use this correctly.
P.S.[2]: if you have another solution of that question, you are welcome to type it into the answers - it will be great :>
EDIT!
I was buisy and now I'm here with solution:
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
GlobalScreen.removeNativeMouseListener(this);
}
};
MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(adapter);
}
};
pix[i].addMouseListener(listener);
Add (after the setState) code to remove the MouseListener.
setState(Frame.NORMAL);
for (int i = 0; i < pix.length; i++){
pix[i].removeMouseListener(MouseAdapter::this);
}
pix must be effectively final, and I hope MouseAdapter::this works for the anonymous MouseListener.
MouseAdapter::this fails
Instead of
pix[i].addMouseListener(new MouseAdapter() {
hold the MouseListener in its own variable:
MouseListener cat = new MouseAdapter() { ... };
pix[i].addMouseListener(cat);
And later do in the inner callback do
pix[i].removeMouseListener(cat);
In the code where you create the mouse listener, you need to keep a reference.
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
}
}
GlobalScreen.addNativeMouseListener(adapter);
Then when you want to remove it, you use that reference.
GlobalScreen.removeNativeMouseListener(adapter);
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
GlobalScreen.removeNativeMouseListener(this);
}
};
MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(adapter);
}
};
pix[i].addMouseListener(listener);
Related
I am trying to make a chess program where I have an 8x8 array of JPanels which all require an addMouseListener but in this addMouseListener I need to make use of the index of that array for it to work, like this:
panels[0][0].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
panels[0][0].setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
}
public void mouseReleased(MouseEvent e) {
}
});
Since I have 64 JPanels that means I need to copy this 63 times and possible changes need to be copied as well. Is there any better, more efficient way to achieve this?
Since I have 64 JPanels that means I need to copy this 63 times
You can write a generic listener
MouseListener ml = new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
JPanel panel = (JPanel)e.getSource();
panel.setBorder(...);
}
};
Then in your looping code you just do:
panels[?][?].addMouseListener( ml );
You should always attempt to write generic listeners so the code can be reused.
You should use a loop for this:
for (int r = 0; r < panels.length; ++r) {
for (int c = 0; c < panels[r].length; ++c) {
// Do this to fix the "must be final" error:
final int row = r;
final int col = c;
panels[row][col].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
panels[row][col].setBorder(.....);
}
// ..... more
});
}
}
However, there are a few other additional ways to go about this. One is that you could write a class which saves the location of the panel:
class MyMouseListener extends MouseAdapter {
int panelRow;
int panelCol;
MyMouseListener(int panelRow, int panelCol) {
this.panelRow = panelRow;
this.panelCol = panelCol;
}
//.....
}
That is basically what the example using an anonymous class does behind the scenes. You could also save a reference to the panel itself.
Or you can use the getSource() method on the MouseEvent:
#Override
public void mousePressed(MouseEvent e) {
JPanel panelWhichWasClicked = (JPanel) e.getSource();
// .....
}
In that case, you only need 1 mouse listener which you can add to every panel.
When you have an array you must take different approach.
First your class should implement MouseListener which has 5 abstract methods but you are probably interested in mouseClicked:
public class Example implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
JPanel panel = (JPanel) e.getSource(); // finding which panel is clicked on
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}
Then somewhere inside your class you will do:
for(int i = 0; i < panels.length; i++){
for(int j = 0; j < panels[0].length; j++){
panels[0][0].addMouseListener(this);
}
}
addItem = new JButton("Add");
gc.gridwidth = GridBagConstraints.RELATIVE;
gc.weightx = 1.0;
panel.add(addItem, gc);
Am I able to make it into something like that:
addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
Instead of this I would want that button, but I have no idea what does that addItem do, since it does not let me to add a name there.
Is there a way how I can do this without modifying the 4 rows of code given at the beginning of the question?
what you can do is to add ActionListener to the button click or if you want you can add MouseListener , actually it depends on what you want to do
addItem.addActionListener(new ActtionListener() {...});
Code using an inner class instead of EventHandler.
addItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something
}
});
you can get more information on this in java official website.
Refer: http://docs.oracle.com/javase/7/docs/api/java/beans/EventHandler.html
if you add just the mouse listener you will not get the 'press' event if using keyboard. So, if your requirement is strictly bound to mouse press then use below snippet :)
addItem.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
// do something
}
#Override
public void mousePressed(MouseEvent e) {
// do something
}
#Override
public void mouseExited(MouseEvent e) {
// do something
}
#Override
public void mouseEntered(MouseEvent e) {
// do something
}
#Override
public void mouseClicked(MouseEvent e) {
// do something
}
});
I have to disable right click on JTableHeader so that user cannot right click over column header and drag to reposition the columns. Do we have any trick to do that? Just to mention left mouse button click works good but when user does RMB and drags the column, the column is moved and is repainted over the other columns when mouse is released.
Any help is appreciatted.
Triggering column drag/resizing with the right button clearly is a bug IMO.
A whacky workaround is to hook into the mouse/Motion/Listener installed by the uidelegate and silently eat all events which are not the left button. Something like (note: a more robust install of this wrapping listener which would survive a LAF switch is outlined in a recent answer):
public static class BugHook implements MouseListener, MouseMotionListener {
private JTableHeader header;
private MouseListener mouseDelegate;
private MouseMotionListener motionDelegate;
public BugHook(JTableHeader header) {
this.header = header;
MouseListener[] ls = header.getMouseListeners();
for (int i = 0; i < ls.length; i++) {
header.removeMouseListener(ls[i]);
String name = ls[i].getClass().getName();
if (name.contains("TableHeaderUI")) {
this.mouseDelegate = ls[i];
ls[i] = this;
}
}
for (MouseListener l : ls) {
header.addMouseListener(l);
}
MouseMotionListener[] motionLs = header.getMouseMotionListeners();
for (int i = 0; i < motionLs.length; i++) {
header.removeMouseMotionListener(motionLs[i]);
String name = motionLs[i].getClass().getName();
if (name.contains("TableHeaderUI")) {
this.motionDelegate = motionLs[i];
motionLs[i] = this;
}
}
for (MouseMotionListener l : motionLs) {
header.addMouseMotionListener(l);
}
}
// methods delegation left buttons only
#Override
public void mousePressed(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
mouseDelegate.mousePressed(e);
}
#Override
public void mouseDragged(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
motionDelegate.mouseDragged(e);
}
#Override
public void mouseReleased(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
mouseDelegate.mouseReleased(e);
}
/// ---------- methods delegating always
#Override
public void mouseClicked(MouseEvent e) {
mouseDelegate.mouseClicked(e);
}
#Override
public void mouseEntered(MouseEvent e) {
mouseDelegate.mouseEntered(e);
}
#Override
public void mouseExited(MouseEvent e) {
mouseDelegate.mouseExited(e);
}
#Override
public void mouseMoved(MouseEvent e) {
motionDelegate.mouseMoved(e);
}
}
I tried with Java versions 1.7.0_11 and 1.6.0_38 and doing this:
table.getTableHeader().setReorderingAllowed(false);
will lock the columns in place. Are you perhaps using older Java version or doing the disabling some other way?
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());
I have a simple JTabbedPane that shows text files. Each tab contains a JList wrapped in a JScrollPane I would like to be able to close the individual tabs with a right click, but I can't get this seemingly simple behavior to work.
Here is what I've tried so far:
Adding a listener to the Pane
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
remove(getComponentAt(e.getPoint()));
}
}
}
Adding to the individual tabs
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
remove((Component) e.getSource());
}
}
}
I've tried several other variations, and nothing seems to work. Does anyone know why these components aren't being removed? I'd be happy to provide any additional details as necessary.
UPDATE More detail:
public void loadCode(String cFile, String cLine) {
Scanner scan = null;
try {
scan = new Scanner(new File(cFile));
} catch (FileNotFoundException e) { e.printStackTrace();}
DefaultListModel<String> model = new DefaultListModel<String>();
JList<String> list = new JList<String>(model);
while(scan.hasNext()) {
model.addElement(scan.nextLine());
}
JScrollPane newTab = new JScrollPane(list);
tp.add(cFile, newTab);
tp.addMouseListener(new RightClickListener());
}
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
remove(indexAtLocation(e.getX(), e.getY()));
}
}
}
Right now in your listener, you're using getComponentAt - which will return the component at the point which was clicked (if you're clicking on the tab titles, you're going to get the JTabbedPane back). Since the JTabbedPane was never added to itself, it can't remove that component...
Try using the indexAtLocation method instead - this will check if the x/y coordinates of the click correspond to a tab heading and return that tab's index (see http://docs.oracle.com/javase/7/docs/api/javax/swing/JTabbedPane.html for more details)
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
tp.remove(tp.indexAtLocation(e.getX(), e.getY()));
}
}
}