I am making a 4x4 board kinda like minesweeper. Each button has a bomb or another image.
Here's my code:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
this.jToggleButton1.setIcon(new javax.swing.ImageIcon("bombaa.png"));
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.jToggleButton1.setIcon(new javax.swing.ImageIcon("bombaa.png"));
}
also tried this way...
private void setIcon1(){
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("bombaa.png")));
}
and call setIcon() in the jButton1ActionPerformed and jButton1MouseClicked BUT this sets my image as the main Icon for the program.
Basically what I need is: Click a button and set the image/icon one time only.
Start by creating your own button, one which you can control the selected state...
public class StickyModel extends JToggleButton.ToggleButtonModel {
public void reset() {
super.setSelected(false);
}
#Override
public void setSelected(boolean b) {
if (!isSelected()) {
super.setSelected(b);
}
}
}
This will prevent the button from becoming "unselected" once it has been set selected (it also includes a reset method which will make it "unselected" for you)
Create your buttons with a "blank" or empty "default" icon and a set the selectedIcon property to what you want shown when the button is selected...
JToggleButton btn = new JToggleButton();
btn.setModel(new StickyModel());
btn.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Blank.png"))));
btn.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Bomb.png"))));
So, when the button is clicked, it will use the selectedIcon
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
try {
add(createButton());
add(createButton());
add(createButton());
} catch (IOException exp) {
exp.printStackTrace();
}
}
protected JToggleButton createButton() throws IOException {
JToggleButton btn = new JToggleButton();
btn.setModel(new StickyModel());
btn.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Blank.png"))));
btn.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Bomb.png"))));
return btn;
}
}
public class StickyModel extends JToggleButton.ToggleButtonModel {
public void reset() {
super.setSelected(false);
}
#Override
public void setSelected(boolean b) {
if (!isSelected()) {
super.setSelected(b);
}
}
}
}
Related
I have simple JTextField and KeyListener.
JTextField textField = new JTextField();
textField.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
}
#Override
public void keyReleased(KeyEvent e)
{
validateThatTextWasSelectedWithShiftAndArrow();
}
});
How do I check that someone select text with key combination (SHIFT + LEFT or RIGHT ARROW) ?
Swing makes heavy use of the Key Bindings API to make it easy to work with existing functionality. We already know the JTextField is fully capable of performing selection, we just need to be able to plug into it.
The JTextField uses the selection-backward and selection-forward to execute the required functionality when the system dependent key strokes are activated, we just need to inject our code into it.
For this, I wrote a simple ReplaceAction action, which takes the old Action we are interested, and calls two methods, one before and one after the old Action is called. This allows you to inject your required functionality into whatever point is required to achieve whatever functionality you are trying to implement...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MonitorSelection {
public static void main(String[] args) {
new MonitorSelection();
}
public MonitorSelection() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JTextField field = new JTextField(10);
add(field);
InputMap im = field.getInputMap(WHEN_FOCUSED);
ActionMap am = field.getActionMap();
Action oldAction = am.get("selection-backward");
am.put("selection-backward", new ReplacedAction(oldAction){
#Override
protected void doAfterReplacedAction() {
System.out.println("Before selection-backward");
}
#Override
protected void doBeforeReplacedAction() {
System.out.println("After selection-backward");
}
});
oldAction = am.get("selection-forward");
am.put("selection-forward", new ReplacedAction(oldAction){
#Override
protected void doAfterReplacedAction() {
System.out.println("Before selection-forward");
}
#Override
protected void doBeforeReplacedAction() {
System.out.println("After selection-forward");
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class ReplacedAction extends AbstractAction {
private Action replaced;
public ReplacedAction(Action replaced) {
this.replaced = replaced;
}
#Override
public void actionPerformed(ActionEvent e) {
doBeforeReplacedAction();
replaced.actionPerformed(e);
doAfterReplacedAction();
}
protected void doBeforeReplacedAction() {
}
protected void doAfterReplacedAction() {
}
}
}
I found a cool way in another question to create a JButton whose actions are written and viewed in an easy way:
public JButton makeToolbarButton(String title, String actionCommand) {
JButton button = new JButton(title);
button.setActionCommand(actionCommand);
button.addActionListener(this);
return button;
}
The class this method is in implements ActionListener, and the buttons commands are assigned by:
public void actionPerformed(ActionEvent e) {
int action = Integer.parseInt(e.getActionCommand());
switch(action) {
case 1:
System.out.println("This button pressed.");
break;
}
}
And the buttons are made by:
JButton button1 = makeToolbarButton("Button 1", "1");
So my question is: can I add KeyStrokes to a button by this method? I tried something like this (inside of the makeToolbarButton method):
button.getInputMap().put(KeyStroke.getKeyStroke("B"), "button_pressed");
button.getActionMap().put("button_pressed", button.getAction());
But I figure this doesn't work because the action command isn't actually assigning an action to a specific button. Is there a way to add something to the makeToolbarButton() method and a parameter for the KeyStroke to accomplish this?
I think you're missing the point of the Action API. A Action is intended to provide a single, self contained, unit of work. This means that the actionCommand really isn't required, as when the actionListener event is triggered, you know exactly the context in which it's been executed
I'd also avoid using KeyStroke.getKeyStroke(String), as the text is a verbose description of what you want to do (ie pressed B or something, but needless to say, it's a pain to get right)
So, the following demonstrates how you might use Actions and assign them to a button AND a key binding
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ActionTest {
public static void main(String[] args) {
new ActionTest();
}
public ActionTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
add(createButton(new ActionOne(), KeyStroke.getKeyStroke(KeyEvent.VK_1, 0)));
add(createButton(new ActionTwo(), KeyStroke.getKeyStroke(KeyEvent.VK_2, 0)));
}
public JButton createButton(Action action, KeyStroke keyStroke) {
JButton btn = new JButton(action);
btn.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "button_pressed");
btn.getActionMap().put("button_pressed", action);
return btn;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
public class ActionOne extends AbstractAction {
public ActionOne() {
putValue(NAME, "1");
putValue(Action.ACTION_COMMAND_KEY, "Action.one");
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
}
public class ActionTwo extends AbstractAction {
public ActionTwo() {
putValue(NAME, "2");
putValue(Action.ACTION_COMMAND_KEY, "Action.two");
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
}
}
See How to Use Actions for more details
I am trying to create a JTextArea which scrolls to bottom every time a text is appended to that text area. Otherwise, the user should be able to scroll top and see previous message. I used this code:
JTextArea terminalText = new JTextArea();
JPanel terminal = new JPanel();
terminal.setLayout(new BorderLayout());
add(terminal); //Adds the terminal to mother JPanel
//I added scrollbar to my JTextArea
JScrollPane scroll = new JScrollPane(terminalText);
terminal.add(scroll, BorderLayout.CENTER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}});
So far this code seems to make my text area scroll to bottom of the terminalText text area every time I append something to terminalText using terminalText.append.
However, the user cannot use scroll bar to scroll to the top to see previous message. Is there a way to fix this? Should I be using DocumentListener to achieve this?
Check out Smart Scrolling.
If the scrollbar is at the bottom, then as text is appended you will see the new text.
If the user has scrolled to a different position, then the viewport will stay there until the user scrolls back to the bottom.
As a simple (and rough) proof of concept...
This basically adds a DocumentListener to the JTextArea and on any Document event, use setCaretPosition to move the caret to the end of the document.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.WeakHashMap;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JTextArea ta = new JTextArea(10, 20);
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
MoveToTheBottom.install(ta);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(ta));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ta.append(new Date().toString() + "\n");
}
});
timer.start();
}
});
}
public static class MoveToTheBottom implements DocumentListener {
private static WeakHashMap<JTextComponent, DocumentListener> registry = new WeakHashMap<>(25);
private JTextComponent parent;
protected MoveToTheBottom(JTextComponent parent) {
this.parent = parent;
parent.getDocument().addDocumentListener(this);
}
public static void install(JTextComponent parent) {
MoveToTheBottom bottom = new MoveToTheBottom(parent);
registry.put(parent, bottom);
}
public static void uninstall(JTextComponent parent) {
DocumentListener listener = registry.remove(parent);
if (listener != null) {
parent.getDocument().removeDocumentListener(listener);
}
}
#Override
public void insertUpdate(DocumentEvent e) {
parent.setCaretPosition(e.getDocument().getLength());
}
#Override
public void removeUpdate(DocumentEvent e) {
parent.setCaretPosition(e.getDocument().getLength());
}
#Override
public void changedUpdate(DocumentEvent e) {
parent.setCaretPosition(e.getDocument().getLength());
}
}
}
The example demonstrates a possible re-usable API which you can use to "install" and "uninstall" the support as reqiured
I've got a viewport, and I've attached a change listener to it. Whenever I scroll through my viewport, my change listener gets called about four times. I'm not sure how to avoid this; I only want the call to happen once?
There's no way around this, JViewport will fire several stateChanged events because it's providing notification about changes to a number of properties...
From the JavaDocs...
Adds a ChangeListener to the list that is notified each
time the view's size, position, or the viewport's extent size has
changed.
At this point, it's kind of hard to know what to suggest as we don't know what it is you are trying to achieve, however, if you have to use a ChangeListener, you could set up a coalescing mechanism. That is, rather then responding to each event, you basically wait until a long enough delay has occurred between events before responding to it...
For example...
public class DelayedChangeHandler implements ChangeListener {
private Timer timer;
private ChangeEvent last;
public DelayedChangeHandler() {
timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stableStateChanged();
}
});
timer.setRepeats(false);
}
#Override
public void stateChanged(ChangeEvent e) {
last = e;
timer.restart();
}
protected void stableStateChanged() {
System.out.println("Finally...");
}
}
Basically, this is a ChangeListener implementation that uses a non-repeating javax.swing.Timer with a short delay. Each time stateChanged is called, the timer is restart. Finally, when the timer is allowed to "tick", it calls stableStateChanged indicating that enough time has passed since the last event was raised.
This assumes that you don't so much care about what caused the event, only that the event occured...
A runnable example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestViewport {
public static void main(String[] args) {
new TestViewport();
}
public TestViewport() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JPanel pane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(1000, 1000);
}
};
JScrollPane sp = new JScrollPane(pane);
sp.getViewport().addChangeListener(new DelayedChangeHandler());
sp.getViewport().addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println(evt.getPropertyName());
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(sp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DelayedChangeHandler implements ChangeListener {
private Timer timer;
private ChangeEvent last;
public DelayedChangeHandler() {
timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stableStateChanged();
}
});
timer.setRepeats(false);
}
#Override
public void stateChanged(ChangeEvent e) {
last = e;
timer.restart();
}
protected void stableStateChanged() {
System.out.println("Finally...");
}
}
}
You can try to use AdjustmentListener for gettign scroll event once, try next:
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.io.UnsupportedEncodingException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Example {
public static void main(String[] args) throws UnsupportedEncodingException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane pane = new JScrollPane(new JTextArea());
pane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
if(e.getValueIsAdjusting()){
return;
}
System.out.println("vertical scrolled");
System.out.println("bar value = " + e.getValue());
}
});
frame.setContentPane(pane);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Here is another example.
So for my school project I am creating a Class Diagram maker. I am 95% done with it and all I need is to make the Jpopup menu appear. In the core I have 3 files. The ApplicationModel which extends the JFrame, ClassDiagram which extends the JPanel and ClassModel which makes the Rectangles (in the picture) appear. The core of the rendering is on Rectangle objects and the text inside the middle and bottom rectangles are surrounded by another invisible rectangle, which is right-clickable.
This is what the program looks like (Minus the paint editting)
Now for the file that handles the clicking is DiagramMouseListener, here is the code for it.
package edu.mville.cs.classdiagram;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
public class DiagramMouseListener extends MouseAdapter
{
ClassDiagram diagram;
Field field;
Method method;
int x;
int y;
ClassModel elementBeingDragged;
JPopupMenu fieldPopupMenu = new JPopupMenu();
JPopupMenu methodPopupMenu = new JPopupMenu();
JMenuItem editFieldNameItem;
JMenuItem createFieldItem;
JMenuItem deleteFieldItem;
JMenuItem editMethodNameItem;
JMenuItem createMethodItem;
JMenuItem deleteMethodItem;
public DiagramMouseListener(ClassDiagram diagram) { this.diagram = diagram; }
public void addPopupMenu()
{
editFieldNameItem = new JMenuItem("Edit Field Name");
createFieldItem = new JMenuItem("New Field");
deleteFieldItem = new JMenuItem("Delete Field");
editMethodNameItem = new JMenuItem("Edit Method Name");
createMethodItem = new JMenuItem("New Method");
deleteMethodItem = new JMenuItem("Delete Method");
methodPopupMenu.add(editMethodNameItem);
methodPopupMenu.add(createMethodItem);
methodPopupMenu.add(deleteMethodItem);
fieldPopupMenu.add(editFieldNameItem);
fieldPopupMenu.add(createFieldItem);
fieldPopupMenu.add(deleteFieldItem);
editFieldNameItem.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
}
});
/*
createFieldItem.addActionListener(this);
deleteFieldItem.addActionListener(this);
editMethodNameItem.addActionListener(this);
createMethodItem.addActionListener(this);
deleteMethodItem.addActionListener(this);
*/
}
#Override
public void mouseClicked(MouseEvent me)
{
if(SwingUtilities.isLeftMouseButton(me) && me.getClickCount() == 2)
{
diagram.doubleClick(me.getPoint());
}
}
#Override
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
DiagramElement elt = diagram.containsPoint(e.getPoint());
if (elt instanceof ClassModel)
{
elementBeingDragged = (ClassModel) elt;
}
}
#Override
public void mouseDragged(MouseEvent e)
{
int dx = e.getX() - x;
int dy = e.getY() - y;
if (elementBeingDragged != null)
{
elementBeingDragged.move(dx, dy);
diagram.repaint();
}
x += dx;
y += dy;
}
#Override
public void mouseReleased(MouseEvent me)
{
elementBeingDragged = null;
DiagramElement de = diagram.containsPoint(me.getPoint());
if (SwingUtilities.isRightMouseButton(me) && me.getClickCount() == 1 && de instanceof Field)
{
if (me.isPopupTrigger())
{
System.out.println("it is");
fieldPopupMenu.show(me.getComponent(), me.getX(), me.getY());
}
}
else if (SwingUtilities.isRightMouseButton(me) && me.getClickCount() == 1 && de instanceof Method)
{
if (me.isPopupTrigger())
{
System.out.println("it is");
methodPopupMenu.show(me.getComponent(), me.getX(), me.getY());
}
}
}
}
At line 118 where it says System.out.println("it is"); It successfully displays the text on console, which tells me the code successfully reached that part, but the popup menu is never displayed when I right click the text (which is inside invisible Rectangles separated by 5 pixels of space).
I tried multiple solutions to this problem. I even looked at the oracle tutorials and other user's examples to see what was wrong with my code. But after countless hours of searching, I failed to fix the problem. Any help would be appreciated. Also if you need more information, I will be glad to provide! Thanks.
Several things;
First off, the popup coordinates should be relative to the component you are triggering the popup on, not the screen coordinates. What is happening is, the API is calculating the screen location of the component and adding the x/y values you pass, which is possibly pushing the popup off the screen
fieldPopupMenu.show(me.getComponent(), me.getX(), me.getY());
Secondly, popups can be triggered on different systems by different events. You should be checking for isPopupTrigger in mousePressed, mouseReleased and even mouseClicked.
Lastly, popups can be triggered by different mouse buttons (and even possibly other conditions), so should only need to check isPopupTrigger
Additionally, you could just use JComponent#setComponentPopupMenu
Updated with setComponentPopupMenu example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class PopupMenuTest {
public static void main(String[] args) {
new PopupMenuTest();
}
public PopupMenuTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPopupMenu popupMenu;
public TestPane() {
popupMenu = new JPopupMenu();
popupMenu.add(new JMenuItem("Open..."));
popupMenu.add(new JMenuItem("Save..."));
popupMenu.add(new JMenuItem("Close..."));
popupMenu.add(new JMenuItem("Give Blood..."));
popupMenu.add(new JMenuItem("Give Money..."));
setComponentPopupMenu(popupMenu);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Updated with MouseListener example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class PopupMenuTest {
public static void main(String[] args) {
new PopupMenuTest();
}
public PopupMenuTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPopupMenu popupMenu;
public TestPane() {
popupMenu = new JPopupMenu();
popupMenu.add(new JMenuItem("Open..."));
popupMenu.add(new JMenuItem("Save..."));
popupMenu.add(new JMenuItem("Close..."));
popupMenu.add(new JMenuItem("Give Blood..."));
popupMenu.add(new JMenuItem("Give Money..."));
addMouseListener(new MouseAdapter() {
protected void doPopup(MouseEvent evt) {
if (evt.isPopupTrigger()) {
popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
}
}
#Override
public void mouseClicked(MouseEvent e) {
doPopup(e);
}
#Override
public void mousePressed(MouseEvent e) {
doPopup(e);
}
#Override
public void mouseReleased(MouseEvent e) {
doPopup(e);
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}