OnJava8-Examples/gui/Popup.java

51 lines
1.3 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: gui/Popup.java
// Creating popup menus with Swing.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*;
public class Popup extends JFrame {
private JPopupMenu popup = new JPopupMenu();
private JTextField t = new JTextField(10);
public Popup() {
setLayout(new FlowLayout());
add(t);
2015-05-06 12:09:38 -07:00
ActionListener al = e ->
2015-05-05 14:05:39 -07:00
t.setText(((JMenuItem)e.getSource()).getText());
2015-04-20 15:36:01 -07:00
JMenuItem m = new JMenuItem("Hither");
m.addActionListener(al);
popup.add(m);
m = new JMenuItem("Yon");
m.addActionListener(al);
popup.add(m);
m = new JMenuItem("Afar");
m.addActionListener(al);
popup.add(m);
popup.addSeparator();
m = new JMenuItem("Stay Here");
m.addActionListener(al);
popup.add(m);
PopupListener pl = new PopupListener();
addMouseListener(pl);
t.addMouseListener(pl);
}
class PopupListener extends MouseAdapter {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if(e.isPopupTrigger())
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
public static void main(String[] args) {
run(new Popup(), 300, 200);
}
} ///:~