For a school project I have to use a ListSelectionListener(LSL) on a JList. I know that an LSL responds to a mouse click and a mouse release. But for the project, i have to let it respond to a double click. Is there anyway to make an LSL respond to that?
I don't know what a ListActionHandler is since you haven't provided the code for it.
My guess is that it implements MouseListener, or maybe extends MouseAdapter. If so, there will be a method called public void mouseClicked(MouseEvent e) that you'll have to implement. In there, just put an if-check to only respond to double-clicks:
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
// do your stuff here
}
}
EDIT:
Now that you've corrected your post to a ListSelectionListener, you'll notice that there is only one method to implement, void valueChanged(ListSelectionEvent e) which does not directly translate to mouse clicks.
Why? Because the mouse isn't the only way to change selection on a JList. It can be done via the arrow keys, or programmatically.
This can be (sort of) solved by adding a MouseListener to the JList and then implementing the click count code I've shown. However, most would consider this a hack since using MouseListeners to track changes in a JList's selection is not advised for reasons already mentioned.
Related
It might be confusing for some to answer this but I will try to put my question in the best way. I am working with jdbc and gui. Basically I want to display (in buttons format) the particular data received from my sql database. I could get the data correctly and put it to my array of buttons as their names. In other words, I have an ArrayList of buttons with different names/texts received from my database. Thus i really need to make an arraylist of buttons since data are dynamically populated. My problem is, I am so confused of how am going to create an actionListener to each button. Everytime each button is clicked, it must show the values associated with its name. I don't know how am i supposed to pass at least the names of the buttons to my actionListener method (or action Event Handler). If you find it confusing, here is the code for my buttons.
todayTaskButton.add(new JButton(taskForToday.get(i)));
todayTaskButton.get(i).setPreferredSize(new Dimension(300,75));
todayTaskButton.get(i).setBackground(Color.GRAY);
todayTaskButton.get(i).setFont(new Font("Century Gothic",Font.PLAIN,30));
todayTaskButton.get(i).setForeground(Color.WHITE);
todayTaskButton.get(i).setFocusable(false);
Thank you so much
You don't need to pass the name of the button to the ActionListener. It is automatically detected. You just need to implement the method actionPerformed(ActionEvent) in you class.
Then add the listener to the button :
todayTaskButton.get(i).addActionListener(this);
In your actionPerformed method, you can do:
JButton b = (JButton) e.getSource();
String text = b.getText();
Honestly there are so many ways you might achieve this, the problem is picking the right one for you...
You could...
Create a anonymous class for each button, each time your create them
todayTaskButton.get(i).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...
}
});
While this can work, it can make the code really messy, you also still need a way to map the action back to the button in some way, which can be done using the actionCommand property or using the source property if you don't mind iterating through the list of available buttons
You could...
Create a purpose build class which implements ActionListener for each button, which possibly takes some kind of reference to the data
todayTaskButton.get(i).addActionListener(new TodayActionListener(taskForToday.get(i)));
This is a little more focused, as you don't really care about the button, as you have the "today" value for the listener, so all the normally repeated code could be isolated into a single class and you would simply pass in the "variable" element
You could...
Take full advantage of the Action API and make individual, self contained actions for each button...
public class TaskAction extends AbstractAction {
public TodayAction(String task) {
putValue(NAME, task);
}
#Override
public void actionPerformed(ActionEvent e) {
// Specific action for task
}
}
Then you could simply use
todayTaskButton.add(new JButton(new TaskAction(taskForToday.get(i))));
While this is similar to the previous option, the Action is a self contained unit of work and has a number of properties which the JButton can use to configure it self. The Action can also be re-used for JMenuItems and key bindings, making it incredibly flexible
Have a closer look at How to Use Actions for more details
I'd like to implement a ToolTip in Swing that has customised behaviour: the longer the user hovers over the component, the more detail should be shown in the tooltip (i.e., a few new lines are added after a few seconds of the user hovering over the component). I just need to check whether this is really doable with Swing without things getting too messy. My idea at the moment would probably be:
Extend ToolTipManager
Override mouseEntered to start a timer (maybe use javax.swing.Timer?). Call setToolTipText and createToolTip to refresh the tooltip and add new information at regular intervals
Override mouseExited to reset the timer
Probably use setDismissDelay to set the dismiss delay to something a lot longer (or Integer.MAX_VALUE)
Is such a thing feasible or is this not a good way to work with Swing (sorry, I'm pretty new to it)? Is there a better way of doing this?
[edit] Hmm, just remembered that ToolTipManager is a singleton with a constructor that only has package visibility, so it can't be extended.
[edit 2] I'm trying out a few solutions at the moment. One thing that I forgot to add is that I do need to know which component is being hovered over - which I guess means I'll need to be working with some sort of listener with a mouseEntered() method (or be able to access this information). And no other interactivity with the popup/tooltip is needed - it just needs to display information.
(This may seem a bit confusing so let me know if you need me to clarify let me know and I'll try to show you how I picture the code) I think your idea might work like if you extend it, and also make a private class that extends Threadand then in the run() method you do something like
while(true)
{
sleep(1);
timeElapsed++;
}
And in your class that extends ToolTipManager, create a field for that class that extends Thread and in the mouseEntered(MouseEvent e) instantiate the thing like:
extendsThreadClass = new ExtendsThreadClass();
extendsThreadClass.start();
and then in the mouseExited(MouseEvent e) method do
extendsThreadClass = null;
Then in that mouseEntered(MouseEvent e) method after starting the Thread then you can do what you want to do after the time thing like
if(timeElapsed > 3000)
{
//what you want to do here
}
Sorry it may be confusing, let me know if i can clear it up for you
I thought I should update this with the approach I took before I saw l1zZY's answer (which I think is the better way of doing things - I still had bugs in my code before I moved onto something else, but this might still be helpful to someone). This is what I did:
Extend JToolTip
Use a Swing Timer for timing
Add a MouseMotion listener to the JTree (in my case I wanted the popup to show when a node was hovered over)
Somewhat inelegantly, detect when the mouse moved over a tree node like this:
public void mouseMoved(MouseEvent e) {
int x = (int) e.getX();
int y = (int) e.getY();
TreePath path = getPathForLocation(x, y);
if (path == null) {
tooltip.hide();
} else {
TreeNode node = (TreeNode) path.getLastPathComponent();
tooltip.setHoveredNode(node);
if (!tooltip.isVisible) {
int absX = e.getXOnScreen();
int absY = e.getYOnScreen();
final Popup tooltipContainer = PopupFactory.getSharedInstance().getPopup(PDTreeView.this,
tooltip, absX, absY);
tooltip.setToolTipContainer(tooltipContainer);
tooltip.show();
}
}
}
tooltip.show() refers to how the tooltip was contained in a Popup
in order to show or hide it programmatically. show() shows the
Popup (and therefore tooltip) and also starts the Swing timer.
Timer has a method called actionPerformed() which is called at whatever interval you set. I just had that method call the code that adds new information to the tooltip. in hide(), I reset the tooltip and the timer.
I had issues with the popup or tooltip not resizing to fit the content, but otherwise this seemed ok.
new to Java here but i have been experimenting...
I am trying to achieve this in Greenfoot: I want to have a mouse click on an object (Actor) and it disappears from the world. This is my code so far:
public void act()
{
disappear();
}
public void disappear(){
if(Greenfoot.mouseClicked(this)){
getWorld().removeObject(this);
}
}
From my understanding, when the mouse is clicked, then it will remove the object from the world... but the object still doesn't disappear, what am i missing here?
Many thanks!
You can regist the action
getWorld().removeObject(this);
to the mouse clicked event list.
Maybe show us the class archi of your system could give us more information.
I know the title didnt say much, but here I go with a clearer explanation:
I have made a tool/app in netbeans that extends JFrame. It has a button and i've added a keyListener when the button is pressed. It gets if the VK_DOWN button is pressed, if yes, it presses it 4 times and then presses enter. this works very fine, but I want to use this in a game. But when I have the app running, if i click on something else, it takes away the priority (i hope thats the right word here..), it doesnt work anymore unless I click on the app and make it top priority again..
Here is the code for the button:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jButton1.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
// TODO: Do something for the keyTyped event
}
public void keyPressed(KeyEvent e) {
// TODO: Do something for the keyPressed event
if (e.getKeyCode() == e.VK_L){
System.out.println("Works");
}
if (e.getKeyCode() == e.VK_DOWN){
System.out.println("Down Arrow Pressed!");
e.setKeyCode(e.VK_DOWN);
e.setKeyCode(e.VK_DOWN);
e.setKeyCode(e.VK_DOWN);
e.setKeyCode(e.VK_DOWN);
e.setKeyCode(e.VK_ENTER);
}
}
});
}
I want to press the VK_DOWN arrow key in the game and let the app press it 4 times and then press enter by itself. This works only when I'm running the app on top of everything else; but if Im running the game, the game takes the higher priority and so the app dont work ..
Please help.
Check out this API:
"JNativeHook is a library to provide global keyboard and mouse hooking for Java. The primary purpose is to provide a portable and reliable method for delivering keyboard and mouse events to a Java application that would otherwise be inaccessible. This is beneficial for applcatiions that run in the background but may require user interaction though hotkeys or mouse events."
http://code.google.com/p/jnativehook/
You cannot do what you are looking to do with Java unless you use some native code.
Uh, not sure whether it will work, but try the Robot class from awt package to generate your Key-Events. It shall work better than your code.
I have a keylistener attached to my frame in java, i can detect key presses when I hit any key, a strange thing is happening however. My game is a minesweeper game, I have a restart button that basically clears the board and remines it. The weird thing is when I click the button with the mouse everything clears fine and the board is remined but the keylistener stops working. Even stranger I have a jmenuitem that basically does a automated click of the button. So its like restartbutton.doclick()
if i click the jmenuitem to restart it restarts fine clears everything and the keylistener still functions. I can even see the button being clicked. Any ideas why this could be happening?
Thanks
this is attached to my main frame. this is the listener that stops working after clicking the button.
frame.addKeyListener(new KeyListener(){
public void keyReleased(KeyEvent e){
}
public void keyPressed(KeyEvent e){
System.out.println("hey");
int keycode = e.getKeyCode();
if(e.isControlDown() & keycode==KeyEvent.VK_C){
balh blah balh
}
}
public void keyTyped(KeyEvent e){
}
});
Suggestions:
Yours is a focus issue, where the KeyListener stops working because the container it is listening to has lost focus to the JButton.
One solution is to make the JButton not able to gain focus by calling setFocusable(false) on it.
But I recommend that you don't use a KeyListener at all if possible, but rather key bindings, since with bindings you don't have this issue and also it is a higher level construct.
Edit
Regarding:
what would be the best way to change that to a key binding?
Best would be to go through the Key Bindings tutorial and to implement the recommendations found there.
this is focus problem, you can use this code to give focus again
getTopLevelAncestor().requestFocus();
Based on the answer to this similar question, I implemented the KeyEventDispatcher rather than using the default listeners. I believe this function will be fairly global though, so you might need to check and make sure the right things are visible/focused.
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
System.out.println("tester");
}
return false;
}
I was able to solve this problem by setting the setFocused property of the container to be true:
frame.setFocusable(true);