How to change cursor when dropping into Java application - java

I'm having some problems I just can't figure out...
I'm writing a Swing Java application with a JList that accepts drag-and-drops. I want to change the cursor while dragging a file or folder from my system over the Java application.

I've found it myself... Thanks Clinton for answering though. Here's what I've used:
first create the JList... You all know how to do that...
Then I've added a setDropTarget:
lstFiles.setDropTarget(new DropTarget()
{
#Override
public synchronized void drop(DropTargetDropEvent dtde)
{
this.changeToNormal();
//handle the drop... [...]
}
#Override
public synchronized void dragEnter(DropTargetDragEvent dtde)
{
//Change cursor...
Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
setCursor(cursor);
//Change JList background...
lstFiles.setBackground(Color.LIGHT_GRAY);
}
#Override
public synchronized void dragExit(DropTargetEvent dtde)
{
this.changeToNormal();
}
private void changeToNormal()
{
//Set cursor to default.
Cursor cursor = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(cursor);
//Set background to normal...
lstFiles.setBackground(Color.WHITE);
}
});

The following will only change the cursor when the user has moved the mouse over your JList.
You can change the cursor when you mouse over a component (i.e. your JList) by using a mouse listener and the setCursor method.
Essentially just add the mouse listener to your JList and use setCursor to change the cursor when the user mouses over the component in your application (mouseEntered and mouseExit). You may also need to do a little inquiry on your drag and drop code to only change the cursor when something valid is being dragged into your JList.
Hope this helps a bit.

Related

How to check whether the cursor is in an eclipse editor part?

I need to find out whether the cursor is inside my tree (tree extends org.eclipse.ui.EditorPart) or somewhere else in the Eclipse workbench.
So I have tried this code:
tree.addMouseMoveListener(new MouseMoveListener() {
#Override
public void mouseMove(MouseEvent e) {
boolean mouseIsInEditor = tree.getClientArea().contains(new Point(e.x, e.y));
if (mouseIsInEditor) {
System.out.println("IS IN EDITOR");
} else {
System.out.println("NOT IN EDITOR");
}
}
});
}
But it won't even run the code as long as the mouse is outside of my tree, so mouseIsInEditor will always be true.
Add a MouseTrackListener listener to your tree:
tree.addMouseTrackListener(listener);
This has mouseEnter method called when the mouse enters your control, mouseExit called when the mouse leaves the control and mouseHover when the mouse hovers over some part of the control.

jtable mouse event pop 2 times

I created an event that execute on table click ,that open a Joptionpane .
but the problem is the joptionpane pops up 2 times .
keep in mind that , i am adding the event after i generate the table
like this click(table0), the tables are generated after retriving from DB and some calculations .
her is the code for the event
protected void click(JTable table)
{
JScrollPane pane=new JScrollPane();
table.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if(!combo_chau.getSelectedItem().toString().equals("station"))
pane.setViewportView(tab_mat(table.getValueAt(table.getSelectedRow(), 2).toString(),table.getValueAt(table.getSelectedRow(), 3).toString()));
if(combo_chau.getSelectedItem().toString().equals("station"))
{pane.setViewportView(tab_sta(table.getValueAt(table.getSelectedRow(), 5).toString(),table.getValueAt(table.getSelectedRow(), 0).toString()));
if(comboBox_1.getSelectedItem().equals("sans detail"))
{ pane.setViewportView(tab_sta_sansdetail(combo_cam.getSelectedItem().toString()));
if(combo_cam.getSelectedItem().toString().equals("tout"))
pane.setViewportView(tab_sta(table.getValueAt(table.getSelectedRow(), 5).toString(),table.getValueAt(table.getSelectedRow(), 0).toString()));
}
}
if(table.getModel().getColumnName(((JTable) e.getSource()).getSelectedColumn()).equals("autre") )
{ int result = JOptionPane.showConfirmDialog(
frame,
pane,
"Use a Panel",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
}
}
});
}
Make sure you are calling your protected void click(JTable table) method only once on each table because you will add a new listener every time you are calling it.
Another issue might be that you are using mousePressed which reacts on the mouse press already, you should consider using mouseClicked instead to react only on a full click.

Gridlayout and mouse listeners

hi i am trying to build a grid-layout GUI with mouse listener. SO when a particular cell is clicked in a grid ,information would be displayed. I don't know where to start, any help would be good
thankyou
I believe you have a class that inherits from JPanel or JFrame and there is whole GUI in it. Then, this class should implement mouseListener. Then your class should have similar code:
#override
public void mouseClicked(MouseEvent e){}
#override
public void mousePressed(MouseEvent e){}
#override
public void mouseEntered(MouseEvent e){}
#override
public void mouseReleased(MouseEvent e){
/*This method is being called when you release your click. It's better
then mouseClicked because mouseClicked is only called when you press
and release on the same pixel or Object (not sure about it)
*/
}
#override
public void mouseExiteded(MouseEvent e){}
In each method you can get source of
MouseEvent e
using
Object source = e.getSource();
if (source == button1){
//Do sth
}if (source == button2){
//Do sth else
}if (source == radioButton1){
//Do whatever you want
}
Then you have reference to the source, so you can modify what you want.
In your gridlayout, set all grids with some Component such as Button or Label. You can set listeners on the components added and display information when a component is clicked
To use properly a gridbaglayout, you should first work on the gridbagconstraints. Then, you should use the ActionListener interface to handle the mouse clicks. If the cells are of the type Labels, you coud hide the text by using myLabel.setText("") and putting the text by using myLabel.setText("information to display"). If you need more help, just ask :D and +1 if it helps ^^

How to change the default cursor position of a JTextArea?

In previous question I asked how to set cursor to the bottom of the JTextArea. The answer was textField.getDocument().getLength() Technically, I can use textField.getDocument().getLength() after every text insert, but this is not convenient.
However, this is not exactly what I meant. I need to change the JTextArea PROPERTY of cursor position. In my program _result is JTextArea. It gets texts from multiple classes and methods, so using textField.getDocument().getLength() everytime after _result.append("text") is not convenient and makes code error prone and not flexible
Is there any way I could do something like:
// this is just a pseudocode
_result.setDefaultCursorPosition(bottom);
and then whenever text goes there (NO MATTER from what class or method), the cursor is always at the bottom.
This would move the caret to the end position after each document change:
_result.getDocument().addDocumentListener(new DocumentListener() {
private void atEnd() {
_result.setCaretPosition(_result.getText().length());
}
public void insertUpdate(DocumentEvent evt) { atEnd(); }
public void removeUpdate(DocumentEvent evt) { atEnd(); }
public void changedUpdate(DocumentEvent evt) { atEnd(); }
});
It still allows the user to re-position the caret by clicking, or by other calls to setCaretPosition.

JTable won't listen to Doubleclicks

I´m trying to implement an undo (and redo) function for an editable JTable with the default components. The JTable has an extra class to specify its properties called SpecifiedJTable.
To do so I wanted to grab the moment when a cell is doubleclicked (i.e. the moment when a cell is chosen/marked to be edited) to push the information in the cell and its coordinates onto the stack.
This should be done by a MouseListener ...at least that was my idea.
I tried this (standing in the constructor of my SpecifiedJTable class)
class JTableSpecified extends JTable {
private static final long serialVersionUID = 1L;
private int c; // the currently selected column
private int r; // the currently selected row
public JTableSpecified(String[][] obj, String[] columnNames) {
super(obj, columnNames); // constructs the real table
// makes that you can only select one row at a time
this.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
// makes that columns are not squeezed
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// forbids to rearrange the columns
getTableHeader().setReorderingAllowed(false);
// adds action listener
this.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
r = getSelectedRow();
c = getSelectedColumn();
// get the String at row r and column c
String s = (String) getValueAt(r, c);
if (jobDisplayed) jobSwitch(c, s);
else resSwitch(c, s);
}
});
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
System.out.println("test");
}
}
});
}
}
but somehow the clickCounter doesn´t want to reach anything that´s higher than 1.
I am glad about any answer and help. Thanks.
The problem you are experiencing is related to use of mouseClicked() rather than using mousePressed(). In this case it appears to be very hard to increase the click counter, yet still it is possible. It took me lots of clicking and also mouse movement to increase the click counter over 1. You could try it by yourself, in your code. To get the counter over 1 you need to go crazy on the mouse by pressing & releasing fast while moving the mouse from cell to cell at the same time (or maybe I was just luckily clicking between the cells?).
As you can see in this fully working sample, made from your code, two mouse presses, using the mousePressed() method are being detected just fine.
public class JTableSpecified extends JTable {
private static final long serialVersionUID = 1L;
public JTableSpecified(String[][] obj, String[] columnNames) {
super(obj, columnNames); // constructs the real table
// makes that you can only select one row at a time
this.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
// makes that columns are not squeezed
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// forbids to rearrange the columns
getTableHeader().setReorderingAllowed(false);
// adds action listener
this.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
}
});
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
System.out.println("test");
}
System.out.println("e.getClickCount() = " + e.getClickCount());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JPanel panel = new JPanel();
panel.add(new JTableSpecified(new String[][]{{"oi", "oi2"}, {"oi3", "oi4"}}, new String[]{"Col1", "Col2"}));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setVisible(true);
}
});
}
}
Conclusion: Maybe you in fact want to use the mousePressed() method?
This answer extends Boro´s answer.
To catch every case that enables the user to edit the table I will also need to add a KeyListener for F2 (which has the same effect as double clicking onto a cell) and disable the automatic cell editing by pressing any key.
I just added it to the constructor right behind the mouseListener (see above)
// forbids the editing by striking a key
this.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);
// keyListener to react on pressing F2 (key code 113)
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 113) System.out.println("test");
}
});
The BasicTableUI is responding to the double-click by going into an edit mode on the cell that was double-clicked. It does lots of complicated stuff, part of which involves creating a JTextField (or other component) to allow the data to be edited, and then preventing the mouse click event from propagating any further.
If your table, or that table cell, is not editable, you can easily capture mouse events with click count 2, 3, 4, .... But since you want your table to be editable, you need a different approach.
One idea would be to override JTable.editCellAt()
A better idea is to forget about messing with the JTable and instead listen for data changes on the table model itself.
the error in the code is that the mouseClicked method is called as soon as the first click takes place. when a double click takes place the mouseClicked method is called again. you can place a static variable (or a class variable) for the earlier click event storing the time (using the e.getWhen() method).
Check for the time difference and if it's small enough, execute your actions (I'd suggest calling a doubleClick method).
you may have to implement mouse listener in your class JTableSpecified since a static variable might not be placed in your existing code.

Categories