here's a quick explanation, I make my TextField into false condition inside of .setEnabled area. So basically after the user press check on Cake's check-box, he need to choose either one of the sub-item menu, after he do that, he needs to enter the quantity of the cake. But, after choosing the sub-item menu, the TextField condition should be true(means it should be editable), but it doesn't go as were told. Thank you.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
class testingcheckbox
{
public static void main(String[] args)
{
Frame qB = new Frame("Queen Bakery");
JCheckBox cake;
cake = new JCheckBox("Cake");
JCheckBox cakeOpt1 = new JCheckBox("Butter Cake");
JCheckBox cakeOpt2 = new JCheckBox("Cheese Cake");
TextField tfCake = new TextField();
tfCake.setPreferredSize(new Dimension(50,24));
tfCake.setEnabled(false);
ActionListener cakeListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(cake.isSelected())
{
cakeOpt1.setEnabled(true);
cakeOpt2.setEnabled(true);
if(cakeOpt1.isSelected())
{
tfCake.setEnabled(true);
}
else
{
tfCake.setEnabled(false);
}
}
else
{
cakeOpt1.setEnabled(false);
cakeOpt2.setEnabled(false);
}
}
};
cake.addActionListener(cakeListener);
qB.add(cake);
cakeOpt1.setEnabled(false);
cakeOpt2.setEnabled(false);
qB.add(cakeOpt1);
qB.add(cakeOpt2);
qB.add(tfCake);
qB.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
qB.setSize(780,470);
qB.setLayout(new FlowLayout(FlowLayout.LEFT));
qB.setVisible(true);
qB.setLocationRelativeTo(null);
qB.setResizable(false);
}
}
cake.addActionListener(cakeListener);
You only add the ActionListener to one check box so no code is execute when you click on the "optonal" check boxes.
You also need to add your ActionListener to your other check boxes:
cakeOpt1.addActionListener(cakeListener);
cakeOpt2.addActionListener(cakeListener);
Related
So I have a swing application where a button opens up a window. It is pretty simple, to open it I use:
private static logPicker logWindow;
static boolean logViewerOpen = false;
if (!logViewerOpen) {
logWindow = new logPicker();
logWindow.frmOpenLog.setVisible(true);
logViewerOpen = true;
}
else {
logWindow.frmOpenLog.requestFocus();
}
I also have a window listener to know when the viewer is closed:
frmOpenLog.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent arg0) {
indexPage.logViewerOpen = false;
frmOpenLog.dispose();
}
});
I do this because I want to keep track on whether or not the window is already open, because if it is then I have to update information. The window I open has a list of logs that a user can double click on to view the information about that log. The problem right now is, when a user double clicks on the list it gets called however many times I have opened and closed that window. example: I open the log picker window, and then close it. I open it again and double click on the log I want to view, and it will open 2 of those. I have the double click simple do a .doClick() on the Open Log button. The weird thing is, when I use the button to open the log, it does not do this. It will only open the log once. Here is the code for the double click event and the Open Log button.
#Override
public void mouseClicked(MouseEvent arg0) {
if (arg0.getClickCount() == 2) {
btnOpenLog.doClick();
}
}
btnOpenLog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
logViewer window = new logViewer(log.getSelectedValue());
window.frmLogViewer.setVisible(true);
}
});
#LiverpoolFTW: Please provide a SSCCE demonstrating the problem. Absent sufficient code, I speculate you're (re-)adding the MouseListener/MouseAdapter each time your window is opened. The following example works as desired as-is, incrementing the clickCount once per button press or label double-click. But if you uncomment the indicated section, you'll see that the doClick() is executed twice when you double-click the label. If you have, for example, some component to which you're adding a listener each time the window opens, each of those listeners will be executed.
package example.stackoverflow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class ClickCheck extends JFrame
{
private static final long serialVersionUID = -6446528001976145548L;
private static final JButton btnOpenLog = new JButton("Open Log");
public ClickCheck()
{
JLabel label = new JLabel("Double-Click Me");
label.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0) {
if (arg0.getClickCount() == 2) {
btnOpenLog.doClick();
}
}
});
// Uncomment to demonstrate the effect of multiple listeners
// label.addMouseListener(new MouseAdapter()
// {
// #Override
// public void mouseClicked(MouseEvent arg0) {
// if (arg0.getClickCount() == 2) {
// btnOpenLog.doClick();
// }
// }
// });
btnOpenLog.addActionListener(new ActionListener() {
private int clickCount = 0;
public void actionPerformed(ActionEvent e) {
System.out.println(++clickCount + ": Button clicked");
}
});
setSize(200, 200);
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(btnOpenLog);
add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
ClickCheck c = new ClickCheck();
c.setVisible(true);
}
});
}
}
Hello I'm currently working in my java file.
I'd like to add an event on JFormattedTextField when I press the enter key.
This is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.text.ParseException;
public class Test extends JFrame implements ActionListener
{
JFormattedTextField phoneField;
Test()
{
setTitle("JFormatted Text");
setLayout(null);
MaskFormatter mask = null;
try {
mask = new MaskFormatter("##########");
} catch (ParseException e) {
e.printStackTrace();
}
phoneField = new JFormattedTextField(mask);
phoneField.setBounds(20, 20, 150, 30);
phoneField.addActionListener(this);
setVisible(true);
setSize(200, 200);
getContentPane().add(phoneField);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== phoneField)
{
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
}
it works but their the user needs to enter 10 digits.
Add an ActionListener to the field. It is better than using the (low level) KeyListener and will conform to whatever that OS accepts as 'end of entry'.
Don't use KeyListener instead use DocumentListener.
It has the following methods which captures the changes in the JTextField
JTextField textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent arg0) {
// Gives notification that a portion of the document has been removed.
}
#Override
public void insertUpdate(DocumentEvent arg0) {
// Gives notification that there was an insert into the document.
}
#Override
public void changedUpdate(DocumentEvent arg0) {
// Gives notification that an attribute or set of attributes changed.
}
});
You could add a keyListener instead.
phonefield.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if(evt.getKeyCode() == evt.VK_ENTER){
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
});
If this isn't your problem, you should expand a little and clarify.
EDIT:
As comments and other answers pointed out, you should go for an ActionListener instead. Reasoning can be found below.
I want to make an event which will be triggered after i make the selection to the JComboBox.
the problem I'm now facing is that when i added an ActionListener, it was triggered when the user clicked on the box but BEFORE he actually chose the new item, thus the action listener was activated all the time on the previous value which was selected in the box. what i want to do is simply changing the title of an JTextArea according to the selection.
I tried doing something like this:
jBox.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String alt = GetAlgoAreaTitleByChoice();
panel.remove(jArea);
currentBest = setArea("",alt);
currentBest.setBounds(50, 350, 1000, 290);
panel.add(jArea);
}
});
and the method inside:
private String GetArgsAreaTitleByChoice(){
String chi = jBox.getSelectedItem().toString();
if(chi.equals(generalChoice)){
return "Hello";
}
else if(chi.equals(algoChoice)){
return "World";
}
else if(chi.equals(argsChoice)){
return "Hello";
}
return null;
}
I've tried using the SELECTED events now like this:
public void itemStateChanged(ItemEvent e) {
JComboBox cb = (JComboBox)e.getSource();
// Get the affected item
String item = cb.getSelectedItem().toString();
if (e.getStateChange() == ItemEvent.SELECTED) {
panel.remove(jBox);
textArea = setArea("", item);
panel.add(jBox);
}
but it seems to remove the area from the panel without adding it back... why is this happening?
Here is a simple demonstration with a sample code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Tester {
public Tester(){
JComboBox box = new JComboBox();
box.addItem("One");
box.addItem("Two");
box.addItem("Three");
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange()==ItemEvent.SELECTED){
e.getItem(); //Do what ever you want :))
}
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args) {
Tester tester = new Tester();
}
}
For listening of events from JComboBox is better implements ItemListener, returns two events SELECTED/DESELECTED
EDIT
if you remove/add JComponent(s) on Runtime and in already visible container, then you have to call (as least code lines)
revalidate();
repaint();
I have a JFileChooser in a JFrame. I've added an ActionListener to the JFileChooser so that the "Cancel" button works when clicked. I can also tab to the "Cancel" button, but when I then hit the "Enter" key, nothing happens (i.e., the ActionListener isn't called with the event command JFileChooser.CANCEL_SELECTION). What must I do with the JFileChooser so that hitting the "Enter" key when on the "Cancel" button is equivalent to clicking on the "Cancel" button?
Here's a simple example of the (mis)behavior I'm seeing:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public final class TestApp {
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
final JFileChooser chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
System.exit(0);
}
});
final JFrame frame = new JFrame();
frame.add(chooser);
frame.pack();
frame.setVisible(true);
}
catch (final Throwable t) {
t.printStackTrace();
}
}
});
}
}
To see the (mis)behavior, execute the program, tab to "Cancel", and then hit the "Enter" key. The program doesn't terminate on my platform -- although it does when I click on the "Cancel" button.
Extending JFileChooser and overriding cancelSelection() also doesn't work (apparently, that function isn't called when the "Enter" key is hit while on the "Cancel" button).
The (mis)behavior occurs on my Fedora 10 x86_64 system with Java 5, 6, and 7.
ADDENDUM: The following adds a KeyEventPostProcessor to the current KeyboardFocusManager and appears to do what I want:
import java.awt.Component;
import java.awt.KeyEventPostProcessor;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public final class TestApp {
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
final JFileChooser chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
System.out.println(e.paramString());
System.exit(0);
}
});
final KeyboardFocusManager kfm = KeyboardFocusManager
.getCurrentKeyboardFocusManager();
kfm.addKeyEventPostProcessor(new KeyEventPostProcessor() {
#Override
public boolean postProcessKeyEvent(final KeyEvent e) {
if (e.getID() == KeyEvent.KEY_RELEASED
&& e.getKeyCode() == KeyEvent.VK_ENTER) {
final Component comp = e.getComponent();
if (chooser.isAncestorOf(comp)) {
if (!(comp instanceof JButton)) {
chooser.approveSelection();
}
else {
final JButton button = (JButton) comp;
if ("Cancel".equals(button.getText())) {
chooser.cancelSelection();
}
else {
chooser.approveSelection();
}
}
}
}
return false;
}
});
final JFrame frame = new JFrame();
frame.add(chooser);
frame.pack();
frame.setVisible(true);
}
catch (final Throwable t) {
t.printStackTrace();
}
}
});
}
}
It seems like a lot of work, however, just to be able to distinguish between hitting the enter key on the "Cancel" button versus anywhere else.
Do you see any problems with it?
DISCOVERED SOLUTION: Setting the GUI Look and Feel to the native one for my system (Linux) does what I want without the need for anything else. This is what I was ignorant of and what I was looking for. The solution is to have the following
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
as the first executable statement of the main() method. One can then dispense with all focus listeners, key event processors, etc.
I've awarded the 100 points to the most helpful respondent.
The program doesn't terminate on my platform.
I see normal operation on Mac OS X 10.5, Ubuntu 10 and Windows 7 using (variously) Java 5 and 6. I replaced your exit() with println() to see the event:
System.out.println(rootDirChooser.getSelectedFile().getName() + e.paramString());
It may help to specify your platform and version; if possible, verify correct installation as well.
I'm not sure I understand your goal; but, as an alternative, consider overriding approveSelection():
private static class MyChooser extends JFileChooser {
#Override
public void approveSelection() {
super.approveSelection();
System.out.println(this.getSelectedFile().getName());
}
}
Addendum:
The goal is to have the action of hitting the "Enter" key while on the "Cancel" button be identical to clicking on the "Cancel" button.
As discussed in Key Bindings, you can change the action associated with VK_ENTER.
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
InputMap map = chooser.getInputMap(JFileChooser.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
map.put(enter, "cancelSelection");
If you want the change to occur only while the "Cancel" button has focus, you'll need to do it in a Focus Listener.
Addendum:
I found a solution that uses KeyboadFocusManager, instead. What do you think?
I can see pros & cons each way, so I've outlined both below. Using KeyboadFocusManager finds all buttons, but offers no locale independent way to distinguish among them; the Focus Listener approach can only see the approve button, and it's UI specific. Still, you might combine the approaches for better results. A second opinion wouldn't be out of order.
Addendum:
I've updated the code below to eliminate the need to know the localized name of the "Cancel" button and use key bindings.
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import javax.swing.plaf.metal.MetalFileChooserUI;
public final class FileChooserKeys
implements ActionListener, FocusListener, PropertyChangeListener {
private final JFileChooser chooser = new JFileChooser();
private final MyChooserUI myUI = new MyChooserUI(chooser);
private final KeyStroke enterKey =
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
private void create() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chooser.addActionListener(this);
myUI.installUI(chooser);
myUI.getApproveButton(chooser).addFocusListener(this);
KeyboardFocusManager focusManager =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
focusManager.addPropertyChangeListener(this);
frame.add(chooser);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.paramString());
}
#Override
public void focusGained(FocusEvent e) {
System.out.println("ApproveButton gained focus.");
}
#Override
public void focusLost(FocusEvent e) {
System.out.println("ApproveButton lost focus.");
}
#Override
public void propertyChange(PropertyChangeEvent e) {
Object o = e.getNewValue();
InputMap map = chooser.getInputMap(
JFileChooser.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
if (o instanceof JButton) {
if ("focusOwner".equals(e.getPropertyName())) {
JButton b = (JButton) o;
String s = b.getText();
boolean inApproved = b == myUI.getApproveButton(chooser);
if (!(s == null || "".equals(s) || inApproved)) {
map.put(enterKey, "cancelSelection");
} else {
map.put(enterKey, "approveSelection");
}
}
}
}
private static class MyChooserUI extends MetalFileChooserUI {
public MyChooserUI(JFileChooser b) {
super(b);
}
#Override
protected JButton getApproveButton(JFileChooser fc) {
return super.getApproveButton(fc);
}
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new FileChooserKeys().create();
}
});
}
}
I have a Popup that is shown when a user clicks on a button. I would like to hide the popup when any of the following events occur:
The user clicks somewhere else in the application. (The background panel for example)
The user minimizes the application.
The JPopupMenu has this behavior, but I need more than just JMenuItems. The following code block is a simplified illustration to demonstrate the current usage.
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PopupTester extends JFrame {
public static void main(String[] args) {
final PopupTester popupTester = new PopupTester();
popupTester.setLayout(new FlowLayout());
popupTester.setSize(300, 100);
popupTester.add(new JButton("Click Me") {
#Override
protected void fireActionPerformed(ActionEvent event) {
Point location = getLocationOnScreen();
int y = (int) (location.getY() + getHeight());
int x = (int) location.getX();
JLabel myComponent = new JLabel("Howdy");
Popup popup = PopupFactory.getSharedInstance().getPopup(popupTester, myComponent, x, y);
popup.show();
}
});
popupTester.add(new JButton("No Click Me"));
popupTester.setVisible(true);
popupTester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Use a JPopupMenu. You can add any component to it, not just menu items.
As pajton noted in a previous comment, Popup is not a JComponent to which listeners can be readily bound. But, as its documentation states, "implementations of Popup are responsible for creating and maintaining their own Components to render [its subject] to the user."
So in using it as your presentation mechanism, your Popup is going to have to present itself as an actual Swing component anyway. Have it register itself to that component. Have it hide itself when the component loses focus.
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Popup;
public class PopupTester extends JFrame {
private static class MessagePopup extends Popup
implements WindowFocusListener
{
private final JDialog dialog;
public MessagePopup(Frame base, String message) {
super();
dialog = new JOptionPane().createDialog( base, "Message" );
dialog.setModal( false );
dialog.setContentPane( new JLabel( message ) );
}
#Override public void show() {
dialog.addWindowFocusListener( this );
dialog.setVisible( true );
}
#Override public void hide() {
dialog.setVisible( false );
dialog.removeWindowFocusListener( this );
}
public void windowGainedFocus( WindowEvent e ) {
// NO-OP
}
public void windowLostFocus( WindowEvent e ) {
hide();
}
}
public static void main(String[] args) {
final PopupTester popupTester = new PopupTester();
popupTester.setLayout(new FlowLayout());
popupTester.setSize(300, 100);
popupTester.add(new JButton("Click Me") {
#Override
protected void fireActionPerformed(ActionEvent event) {
Point location = getLocationOnScreen();
MessagePopup popup = new MessagePopup( popupTester, "Howdy" );
popup.show();
}
});
popupTester.add(new JButton("No Click Me"));
popupTester.setVisible(true);
popupTester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You can add MouseListener to your background panel and hide the popup when somebody clicks on the panel.
To react on application minimization, use WindowListener attached to a JFrame.
Etc, etc. May seem tedious, but surely will work.
Thanks pajton and Noel Ang for getting me pointed in the right direction! Here is the solution that I ended up with. I'm just including it here so that others may benefit from it.
I ended up going with a JWindow since it doesn't get the window decorations but does get focus events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupTester extends JFrame {
private static class MessagePopup extends Popup implements WindowFocusListener {
private final JWindow dialog;
public MessagePopup(Frame base, JLabel component, int x, int y) {
super();
dialog = new JWindow(base);
dialog.setFocusable(true);
dialog.setLocation(x, y);
dialog.setContentPane(component);
component.setBorder(new JPopupMenu().getBorder());
dialog.setSize(component.getPreferredSize());
dialog.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
dialog.setVisible(false);
}
}
});
}
#Override
public void show() {
dialog.addWindowFocusListener(this);
dialog.setVisible(true);
}
#Override
public void hide() {
dialog.setVisible(false);
dialog.removeWindowFocusListener(this);
}
public void windowGainedFocus(WindowEvent e) {
// NO-OP
}
public void windowLostFocus(WindowEvent e) {
hide();
}
}
public static void main(String[] args) {
final PopupTester popupTester = new PopupTester();
popupTester.setLayout(new FlowLayout());
popupTester.setSize(300, 100);
popupTester.add(new JButton("Click Me") {
#Override
protected void fireActionPerformed(ActionEvent event) {
Point location = getLocationOnScreen();
int x = (int) location.getX();
int y = (int) (location.getY() + getHeight());
JLabel myComponent = new JLabel("Howdy");
MessagePopup popup = new MessagePopup(popupTester, myComponent, x, y);
popup.show();
}
});
popupTester.add(new JButton("No Click Me"));
popupTester.setVisible(true);
popupTester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You could add a FocusListener to your popup-window, and dispose it when it loses focus. However, that will cause you some troubles when the focus loss is due to some other application (new windows comes to the foreground, you switch virtual desktops, etc.)
But perhaps you (a) know that that cannot happen in your case or (b) would want to close the popup in such cases anyway, a focus-based approach may still be interesting to you.
I know this is an old question but I really needed the Popup to work in my case. So I tried a few things and the following is my solution.
Add a FocusListener to the component you add to the popup and program the focusLost event on that component to hide the popup when focus is lost. Call the requestFocus method on your component just after showing the popup.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
public class PopupTester extends JFrame {
JButton myButton = new JButton("Click Me");
JLabel myComponent = new JLabel("Howdy");
Popup popup = null;
public PopupTester() {
setLayout(new FlowLayout());
setSize(300, 100);
add(myButton);
add(new JButton("No Click Me"));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myComponent.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
if (popup != null) {
popup.hide();
}
}
});
myButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (popup != null) {
popup.hide();
popup = null;
}
Point location = myButton.getLocationOnScreen();
int y = (int) (location.getY() + myButton.getHeight());
int x = (int) location.getX();
popup = PopupFactory.getSharedInstance().getPopup(PopupTester.this, myComponent, x, y);
popup.show();
myComponent.requestFocus();
}
});
}
public static void main(String[] args) {
PopupTester popupTester = new PopupTester();
popupTester.setVisible(true);
}
}