I want to show a popupmenu, while using Metal L&F it will do these behavior.
single click: it printed "pressed" and show menu
double pressed: it printed "pressed" and show menu too.
Yes it is I needed. But when using WindowsLookAndFeel, it not same as those.
when twice pressed it just hide menu and not printed "pressed". why it have difference behavior between two L&F?
import javax.swing.*;
import java.awt.event.*;
public class Popup {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(300, 300);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception ex) {
ex.printStackTrace();
}
JPopupMenu menu = new JPopupMenu();
menu.add("item");
f.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("pressed");
}
});
f.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
menu.show(f, e.getX(), e.getY());
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
boolean consumeEvent = UIManager.getBoolean("PopupMenu.consumeEventOnClose");
// Consume the event so that normal processing stops.
if(consumeEvent && !(src instanceof MenuElement)) {
me.consume();
}
I have found the problems, because of this property is different
so end it
Related
Once the steps below are taken, the whole application is frozen and the modal dialog cannot be closed.
(This is related to another question but this time we have a reproducible scenario)
The steps:
Open dropdown
Select "Han-Ra" (the last value in the drop down)
After this, trying to resize or close the modal dialog will not succeed. It reproduces 1 out of 3 times (might be easier to reproduce if you do the selection by arrow down but happens with mouse selection also)
This happens on jdk 1.8 (tried 1.8.0_162 and 1.8.0_144) and jdk 10 (10.0.1) but not when using 1.7 (tried 1.7.0_80)
This is just the most obvious case we could find but it randomly (rarely) happens for most modal dialogs.
Anyone else had this problem and found a workaround? We'll report it to Oracle but we'd be more interested in a workaround.
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class FreezePleeze {
public static final Object[] ALL_THE_SINGLE_LADIES = {"Rahan", "Crao", "Naouna", "Han-ra"};
public static void main(String[] args) {
new FreezePleeze();
}
public FreezePleeze() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JButton push_me = new JButton("Push me");
JFrame frame = new JFrame("Mmmmm");
JPanel containerPanel = new JPanel();
frame.add(containerPanel);
final JComboBox<Object> comboBox = new JComboBox<>(ALL_THE_SINGLE_LADIES);
containerPanel.add(comboBox);
frame.setSize(300, 300);
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JDialog jDialog = new JDialog((JFrame) null, true);
jDialog.add(push_me);
if (comboBox.getSelectedIndex() == ALL_THE_SINGLE_LADIES.length - 1) {
jDialog.setLocationRelativeTo(frame);
jDialog.setSize(300, 300);
jDialog.setVisible(true);
}
}
});
comboBox.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_WINDOWS);
robot.keyRelease(KeyEvent.VK_WINDOWS);
} catch (AWTException e1) {
e1.printStackTrace();
}
push_me.setText("Finished counting");
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
frame.setVisible(true);
}
});
}
}
I can reproduce your problem. The solution is to submit the correct window to the constructor of your dialog:
Example:
JDialog jDialog = new JDialog(frame, true);
or, if you have no window instance when you create a dialog:
JDialog jDialog = new JDialog(FocusManager.getCurrentKeyboardFocusManager().getActiveWindow(),
ModalityType.APPLICATION_MODAL);
i am constructing a word processor program as an assignment for my Java class in school and i am having a really hard time getting the popupmenu to work when i right click on my text area. I have already constructed the popup menu and have my textarea listening to my popuplistener and i have overridden the mouse pressed and mouse released functions with
class popupframe extends JFrame{
JMenuItem copy;
JMenuItem paste;
JTextArea textarea = new JTextArea();
JPopupMenu pop;
popupframe(){
Container cpane = getContentPane();
setSize(300 , 300);
setLocation(300, 300);
setTitle("Test");
JPopupMenu pop = new JPopupMenu();
copy = new JMenuItem("copy");
paste = new JMenuItem("paste");
textarea = new JTextArea("something goes here", 5, 5);
pop.add(copy);
pop.add(paste);
PopupListener popuplistener = new PopupListener();
textarea.addMouseListener(popuplistener);
}
class PopupListener extends MouseAdapter{
public void MousePressed(MouseEvent e){
popit(e);
}
public void MouseReleased(MouseEvent e){
popit(e);
}
private void popit(MouseEvent e){
if(e.isPopupTrigger()){
pop.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
I cannot see why it is not working but perhaps i am missing something crucial, please help!! much appreciated
Add the #Override annotation to the methods you think your are overriding...
class PopupListener extends MouseAdapter {
#Override
public void MousePressed(MouseEvent e) {
System.out.println("Pressed");
popit(e);
}
#Override
public void MouseReleased(MouseEvent e) {
System.out.println("Pressed");
popit(e);
}
You will now find that this fails to compile, but why? Because Java is case sensitive, and by convention, method names start with a lower case character
You'll find that something like...
class PopupListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
popit(e);
}
#Override
public void mouseReleased(MouseEvent e) {
popit(e);
}
#Override
public void mouseClicked(MouseEvent e) {
popit(e);
}
private void popit(MouseEvent e) {
if (e.isPopupTrigger()) {
pop.show(e.getComponent(), e.getX(), e.getY());
}
}
}
will work better. But having said that, you'll generally find
textarea.setComponentPopupMenu(pop);
significantly easier and less error prone (and it won't cause a NullPointerException like your example code will.
I'm blocked with a probelm about Java and the use of JTree:
I want to create a JTree with, node by node, some JButtons components (or Images, I don't mind), like in the following picture. It will be 3 or 4 buttons in the same row. I succeed to do that.
But where I'm blocked is when I want to add a mouselistener on each of this button to manage their tooltip or an action on them.
In fact the JTree component is most of the time used to manage the action on the full node, but not on its inside components.
I did a short code, in comparaison at the real big code I have to work in, to quickly test what I say:
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
public class TreeWithPopup extends JPanel {
DefaultMutableTreeNode root, node1, node2, node3;
public TreeWithPopup() {
MyJTree tree;
root = new DefaultMutableTreeNode("root", true);
node1 = new DefaultMutableTreeNode("node 1", true);
node2 = new DefaultMutableTreeNode("node 2", true);
node3 = new DefaultMutableTreeNode("node 3", true);
root.add(node1);
node1.add(node2);
root.add(node3);
setLayout(new BorderLayout());
tree = new MyJTree(root);
tree.setCellRenderer(new PCellRenderer());
add(new JScrollPane((JTree) tree), "Center");
}
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
public static void main(String s[]) {
JFrame frame = new JFrame("Tree with button");
TreeWithPopup panel = new TreeWithPopup();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setForeground(Color.black);
frame.setBackground(Color.lightGray);
frame.getContentPane().add(panel, "Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
frame.addWindowListener(new WindowCloser());
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
class MyJTree extends JTree implements ActionListener {
MyJTree(DefaultMutableTreeNode dmtn) {
super(dmtn);
addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent arg0) {
System.out.println("JTree.MouseListener");
}
public void mouseEntered(MouseEvent arg0) {
System.out.println("JTree.MouseListener");
}
public void mouseExited(MouseEvent arg0) {
System.out.println("JTree.MouseListener");
}
public void mousePressed(MouseEvent arg0) {
System.out.println("JTree.MouseListener");
}
public void mouseReleased(MouseEvent arg0) {
System.out.println("JTree.MouseListener");
}
});
}
public void actionPerformed(ActionEvent ae) {
System.out.println("MyJTree.ActionPerformed");
}
}
class PCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree ptree, Object pvalue, boolean psel, boolean pexpanded, boolean pleaf, int prow,
boolean phasFocus) {
Box myPanel = new Box(BoxLayout.X_AXIS);
JButton myButton = new JButton("test");
Image imgToUse = null;
Image imgRollOver = null;
try {
URL urlIcon = new URL("file:///C:/1.jpg"); // <===== change their the path to icons
imgToUse = ImageIO.read(urlIcon);
urlIcon = new URL("file:///C:/2.jpg"); // <===== change their the path to icons
imgRollOver = ImageIO.read(urlIcon);
} catch (IOException e) {
e.printStackTrace();
}
myButton.setRolloverIcon(new ImageIcon(imgRollOver));
myButton.setIcon(new ImageIcon(imgToUse));
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(" detected on ");
}
});
myButton.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent arg0) {
System.out.println("myButton.MouseListener");
}
public void mouseEntered(MouseEvent arg0) {
System.out.println("myButton.MouseListener");
}
public void mouseExited(MouseEvent arg0) {
System.out.println("myButton.MouseListener");
}
public void mousePressed(MouseEvent arg0) {
System.out.println("myButton.MouseListener");
}
public void mouseReleased(MouseEvent arg0) {
System.out.println("myButton.MouseListener");
}
});
myPanel.add(myButton);
return myPanel;
}
}
You just have to change the icon path or put the two following icons at "c:/"
I also searched to use the x/y position of the row event but I was unable to find the position of my button after rendering.
If anyone can have an idea how to do that, he could be very helpful.
Thanks, at least for read this question ;-)
Tooltip support is actually provided by the TableCellRenderer directly. Your TableCellRenderer is a little muddled. It extends from DefaultTreeCellRenderer but makes no use of any of it's features, instead creating a new Box, JButton and loading icons each time a cell is rendered...
This is going to increase your memory usage a slow you application down...
Instead, try something like...
class PCellRenderer extends Box implements TreeCellRenderer {
private Image imgToUse = null;
private Image imgRollOver = null;
public PCellRenderer() {
super(BoxLayout.X_AXIS);
JButton myButton = new JButton("test");
try {
URL urlIcon = new URL("file:///C:/1.jpg"); // <===== change their the path to icons
imgToUse = ImageIO.read(urlIcon);
urlIcon = new URL("file:///C:/2.jpg"); // <===== change their the path to icons
imgRollOver = ImageIO.read(urlIcon);
} catch (IOException e) {
e.printStackTrace();
}
myButton.setRolloverIcon(new ImageIcon(imgRollOver));
myButton.setIcon(new ImageIcon(imgToUse));
add(myButton);
}
public Component getTreeCellRendererComponent(JTree ptree, Object pvalue, boolean psel, boolean pexpanded, boolean pleaf, int prow,
boolean phasFocus) {
// set the tooltip text here...
// Maybe change the icon...
return this;
}
}
Now, actually doing something...
Renderers are rubber stamps. That are not actually life components. Think of them like photos. You can take a snap shot of your friends, but you can't interact with them...same thing here...
Your idea of a MouseListener on the JTree is a correct one, in fact the JavaDocs actually have a demonstration of this...
public void mousePressed(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
mySingleClick(selRow, selPath);
}
else if(e.getClickCount() == 2) {
myDoubleClick(selRow, selPath);
}
}
}
Is it possible to listen to events from browser with Java?
The main task is to add command "copy to file" to pop-up menu of right click of the mouse. This command must add selected text in browser, in Notepad, in winword (any selectable text) to specific text file.
I've just tried code which adds icon to tray but I do not know whether it can it be developed for solving my task.
import java.awt.*;
import java.awt.event.*;
public class SystemTrayTest
{
public SystemTrayTest()
{
final TrayIcon trayIcon;
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage("tray.gif");
MouseListener mouseListener = new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.println("Tray Icon - Mouse clicked!");
}
public void mouseEntered(MouseEvent e) {
System.out.println("Tray Icon - Mouse entered!");
}
public void mouseExited(MouseEvent e) {
System.out.println("Tray Icon - Mouse exited!");
}
public void mousePressed(MouseEvent e) {
System.out.println("Tray Icon - Mouse pressed!");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Tray Icon - Mouse released!");
}
};
ActionListener exitListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Exiting...");
System.exit(0);
}
};
PopupMenu popup = new PopupMenu();
MenuItem defaultItem = new MenuItem("Exit");
defaultItem.addActionListener(exitListener);
popup.add(defaultItem);
trayIcon = new TrayIcon(image, "Tray Demo", popup);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
trayIcon.displayMessage("Action Event",
"An Action Event Has Been Peformed!",
TrayIcon.MessageType.INFO);
}
};
trayIcon.setImageAutoSize(true);
trayIcon.addActionListener(actionListener);
trayIcon.addMouseListener(mouseListener);
// Depending on which Mustang build you have, you may need to uncomment
// out the following code to check for an AWTException when you add
// an image to the system tray.
// try {
tray.add(trayIcon);
// } catch (AWTException e) {
// System.err.println("TrayIcon could not be added.");
// }
} else {
System.err.println("System tray is currently not supported.");
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
SystemTrayTest main = new SystemTrayTest();
}
}
You are talking about accessing clipboard events. this may helps you. How do we get notified about system clipboard events?
My problem is when I right click on the JFrame in the example below, the JPopupMenu shows up but if I click anywhere outside the JFrame, the menu does not disappear. I have to click somewhere on the JFrame to get rid of it which is not the expected behavior. Here are the steps to reproduce:
Run the window class from Eclipse (JFrame appears)
Click into the Eclipse workspace (JFrame loses focus and is hidden behind eclipse)
Minimize Eclipse (JFrame appears)
Go with your mouse over JFrame and make a right click (Popup appears)
Click somewhere (Not into JFrame or Popup). The Popup will not disappear
I'm running OS X 10.6.7 and Java full version 1.6.0_24-b07-334
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test
{
static class window extends JFrame implements MouseListener,
MouseMotionListener
{
JPopupMenu popMenu;
JPanel panel = new JPanel();
Point location;
MouseEvent pressed;
public window()
{
addMouseListener(this);
addMouseMotionListener(this);
JLabel label = new JLabel("JFrame", JLabel.CENTER);
initPopMenu();
add(label);
setUndecorated(true);
setVisible(true);
// setAlwaysOnTop(true);
setLocationRelativeTo(null);
pack();
}
public void initPopMenu()
{
popMenu = new JPopupMenu();
JMenuItem item;
item = new JMenuItem("Title");
item.setEnabled(false);
popMenu.add(item);
popMenu.addSeparator();
item = new JMenuItem("Item One");
popMenu.add(item);
item = new JMenuItem("Item 2");
popMenu.add(item);
item = new JMenuItem("Item 3");
popMenu.add(item);
}
public void mousePressed(MouseEvent e)
{
pressed = e;
int nModifier = e.getModifiers();
if (((nModifier & InputEvent.BUTTON2_MASK) != 0)
|| ((nModifier & InputEvent.BUTTON3_MASK) != 0))
popMenu.show( this, e.getX(), e.getY() );
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseDragged(MouseEvent me)
{
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
}
public static void main(String[] args)
{
window dw = new window();
}
}
you can add a windowFocusListener, hide the menu when window lost focus
this.addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowLostFocus(WindowEvent e) {
if(popMenu != null){
popMenu.setVisible(false);
}
}
#Override
public void windowGainedFocus(WindowEvent e) {
//System.out.println(e);
}
});