JFrame getLocation and setLocation deal with system border differently - java

I am creating a multi-user Swing GUI application, and want the user's window location and size settings to persist when they log out and back in. I am currently getting the window location and size using the getLocation() and getSize() methods on my parent JFrame when the user logs out and saving them to a file, and then when the user logs back in I read those values back in and set the window size and location using setLocation() and setSize().
The problem that I am having is that getLocation() and getSize() appear to be subtracting off the system border (e.g. if I put the window in the upper left corner getLocation returns (1,54) instead of (0,0)), but setLocation() and setSize() don't. The result is that every time I logout and log back in, the window appears slightly offset and slightly smaller than it did when I closed it.
Does anybody know why this might be happening or how I can get around it? Is there some other method I should be using to get and set the window location and size?
I'm running java 1.7.0_45 on Ubuntu 12.04, if that helps.
Thanks!
EDIT:
The following example replicates the issue I am seeing:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class JFrameTest
{
private JFrame frame;
private JButton button;
private Point lastLocation;
private Dimension lastSize;
private void run()
{
button = new JButton("Test");
button.addActionListener(listener);
lastLocation = new Point(0, 0);
lastSize = new Dimension(200, 200);
initFrame();
}
private void initFrame()
{
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().add(button);
frame.setLocation(lastLocation);
frame.setPreferredSize(lastSize);
frame.pack();
frame.setVisible(true);
}
private ActionListener listener = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == button)
{
lastLocation = frame.getLocationOnScreen();
lastSize = frame.getSize();
frame.dispose();
initFrame();
}
}
};
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
new JFrameTest().run();
}
});
}
}
Also, I see the same issue when I use getLocationOnScreen() instead of getLocation().

You can use getLocationOnScreen()
Gets the location of this component in the form of a point specifying
the component's top-left corner in the screen's coordinate space.

Related

image to show up when I press the button in java swing (error in frame.add( ) )

Hello first of all when I run the program a button appear , when I press the button the image will go from top to down.
I try the code when the image go from top to down , it work very well
BUT when I put all the codes together there is an error in ( frame.add(new AnimationPane() ); )
Question : How to add AnimationPane() to the frame ???
because this is my problem.
The idea that I want to make two scenes , the first one have a button to make go to the second scene which will have an image (it must be pushed from top until reach down ).
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package maincontentpaneswitching;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MainContentPaneSwitching {
private static class ChangeContentPaneListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// I want to put the image here
JPanel newFrameContents = new JPanel(); //Uses FlowLayout by default.
newFrameContents.add(new JLabel("You have successfully changed the content pane of the frame!", JLabel.CENTER));
/*We assume that the source is a JButton and that the Window is of type JFrame, hence
the following utility method call is possible without letting any errors appear:*/
JFrame frame = (JFrame) SwingUtilities.getWindowAncestor((JButton) e.getSource());
frame.setSize(600, 300);
frame.setContentPane(newFrameContents); //Change the content pane of the frame.
frame.revalidate(); //Notify the frame that the component hierarchy has changed.
frame.add(new AnimationPane() );
frame.pack(); //Resize the frame as necessary in order to fit as many contents as possible in the screen.
frame.setLocationRelativeTo(null); //Place the frame in the center of the screen. As you can tell, this needs its size to calculate the location, so we made sure in the previous line of code that it is set.
frame.repaint(); //Repaint frame with all its contents.
}
}
public class AnimationPane extends JPanel {
private BufferedImage boat;
private int yPos = 0;
private int direction = 1;
public AnimationPane() {
try {
boat = ImageIO.read(new URL("https://i.stack.imgur.com/memI0.png"));
Timer timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
yPos += direction;
if (yPos + boat.getHeight() > getHeight()) {
yPos = getHeight() - boat.getHeight();
direction *= +1;
} else if (yPos < 0) {
yPos = 0;
direction *= +1;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return boat == null ? super.getPreferredSize() : new Dimension(boat.getHeight()*2 , boat.getWidth() *2);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = getWidth() - boat.getWidth();
g.drawImage(boat, x, yPos, this);
}
}
private static class MainRunnable implements Runnable {
#Override
public void run() {
JButton changeContentPaneButton = new JButton("Click to go to the next image!");
changeContentPaneButton.addActionListener(new ChangeContentPaneListener());
JPanel frameContents = new JPanel(); //Uses FlowLayout by default.
frameContents.add(changeContentPaneButton);
JFrame frame = new JFrame("My application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tells the frame that when the user closes it, it must terminate the application.
frame.setContentPane(frameContents); //Add contents to the frame.
frame.pack(); //Resize the frame as necessary in order to fit as many contents as possible in the screen.
frame.setLocationRelativeTo(null); //Place the frame in the center of the screen. As you can tell, this needs its size to calculate the location, so we made sure in the previous line of code that it is set.
frame.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new MainRunnable()); //Swing code must always be used in the Event Dispatch Thread.
}
}
Introduction
As I said in my comment, I couldn't get the image animation to work properly. At least this code would give you a solid foundation to start with.
Here's the GUI I came up with.
Here's the GUI after you left-click on the button.
If you're going to add comments to your code, put the comments on separate lines from the code. Not everyone has a large monitor and can read 200+ character lines of code.
Explanation
Oracle has a rad tutorial, Creating a GUI With Swing. Skip the Netbeans section.
When I create a Swing GUI, I use the model/view/controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time.
In Swing, the MVC pattern means:
The view reads information from the model
The view may not update the model
The controller updates the model and repaints/revalidates the view.
There's usually not one controller to "rule them all". Each listener controls its portion of the model and the view.
When I put together an application, I code one tiny tiny piece of it, then run tests. I probably ran two to three dozen tests, and this was mostly coded by you.
Model
I created a BoatImage class to read the boat image. It's a separate class, so I can read the image before I start to construct the GUI.
View
I created a JFrame. I created a main JPanel with a CardLayout.
I use a CardLayout to layout the button JPanel and the image JPanel. This way, the JFrame is not constantly changing size.
I create the JFrame and JPanels as separate methods/classes. This makes it much easier for people, including yourself, to read and understand the view code.
Controller
I coded the ChangeContentPaneListener to change from the button JPanel to the image JPanel. This is where you would put your image animation code.
Code
Here's the complete runnable code. I made all the additional classes inner classes so I could post this code as one block.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MainContentPaneSwitching implements Runnable {
public static void main(String[] args) {
// Swing code must always be used in the Event Dispatch Thread.
SwingUtilities.invokeLater(new MainContentPaneSwitching());
}
private AnimationPane animationPane;
private BoatImage boatImage;
private CardLayout cardLayout;
private JPanel mainPanel;
public MainContentPaneSwitching() {
this.boatImage = new BoatImage();
}
#Override
public void run() {
JFrame frame = new JFrame("My application");
// Tells the frame that when the user closes it, it
// must terminate the application.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainPanel = createMainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
// Resize the frame as necessary in order to fit as many contents
// as possible in the screen.
frame.pack();
// Place the frame in the center of the screen. As you can tell, this
// needs its size to calculate the location, so we made sure in the
// previous line of code that it is set.
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createMainPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.add(createButtonPanel(), "button");
animationPane = new AnimationPane(boatImage);
panel.add(animationPane, "image");
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton changeContentPaneButton = new JButton(
"Click to go to the next image!");
changeContentPaneButton.addActionListener(
new ChangeContentPaneListener(this, boatImage));
panel.add(changeContentPaneButton);
return panel;
}
public JPanel getAnimationPane() {
return animationPane;
}
public void repaint() {
animationPane.repaint();
}
public class AnimationPane extends JPanel {
private static final long serialVersionUID = 1L;
private BoatImage boat;
public AnimationPane(BoatImage boat) {
this.boat = boat;
BufferedImage image = boat.getBoat();
this.setPreferredSize(new Dimension(image.getWidth(),
image.getHeight()));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage image = boat.getBoat();
int x = getWidth() - image.getWidth();
g.drawImage(image, x, boat.getyPos(), this);
}
}
private class ChangeContentPaneListener implements ActionListener {
private int direction, yPos;
private final MainContentPaneSwitching view;
private final BoatImage model;
public ChangeContentPaneListener(MainContentPaneSwitching view,
BoatImage model) {
this.view = view;
this.model = model;
this.direction = 1;
this.yPos = 0;
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(mainPanel, "image");
}
}
public class BoatImage {
private int yPos;
private BufferedImage boat;
public BoatImage() {
try {
URL url = new URL("https://i.stack.imgur.com/memI0.png");
boat = ImageIO.read(url); // boat.jpg
} catch (MalformedURLException e) {
e.printStackTrace();
boat = null;
} catch (IOException e) {
e.printStackTrace();
boat = null;
}
this.yPos = 0;
}
public BufferedImage getBoat() {
return boat;
}
public void setyPos(int yPos) {
this.yPos = yPos;
}
public int getyPos() {
return yPos;
}
}
}

two dialogs setAlwaysOnTop(true): the second generated one is behind the first one

I have a JDialog which can generate another one. The two JDialogs have the property setAlwaysOnTop(true) and aren't modal. The second Jdialog generated from the first one appears always behind. I would like it to appear in front.
I tried several things : toFront(), requestFocus(), etc..
Here a short example to reproduce the problem:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
final JDialog modelDialog = createDialog();
modelDialog.setVisible(true);
}
private static JDialog createDialog(){
final JDialog modelDialog = new JDialog();
modelDialog.setBounds(132, 132, 300, 200);
Container dialogContainer = modelDialog.getContentPane();
dialogContainer.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
JButton okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final JDialog modelDialog = createDialog();
modelDialog.setVisible(true);
}
});
panel1.add(okButton);
dialogContainer.add(panel1, BorderLayout.SOUTH);
modelDialog.setAlwaysOnTop(true);
return modelDialog;
}
After a click on the OK button, we see another dialog appearing behind the current one. The new dialog has the focus but is still behind
Actually, I tried your code, and it is no problem appears. If you want to see it too clearly, create dialog with random location. In every click, new dialog is random place on the top.
modelDialog.setBounds(new Random().nextInt(400), new Random().nextInt(400), 300, 200);
But my suggestion is create dialog as modal, in addition to set old one as parent.

Java : using graphics component within an action listener

I've made a JFrame with Diferent JButtons and i'd like to get an image from another class. Any ideas? Or how draw on the same class but on the action performed?
Because it doesnt let me to do any drawings...my complier always gives me error messages
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class red extends JFrame {
public JButton b;
public JButton b1;
public JButton b2;
public JButton b3;
public JButton b4;
public static Image p;
public static Graphics g;
public red() throws IOException {
gui1 x = new gui1();
setTitle(" ");
setSize(1200,700);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
b= new JButton("click");
b1= new JButton();
b.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e0){
b1.setBounds(0, 0, 200, 200);
b.show(false);
add(x);
}
});
b.setBounds(0, 0, 100, 100);
add(b1);
add(b);
setVisible(true);
}
public static void main(String[] args) throws IOException {
red k = new red();
}
}
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class gui1 extends Canvas {
public static Image p;
public void paint(Graphics g){
g.drawImage(p, 700, 200, 100, 100, this);
}
{
try {
p= ImageIO.read(new File("Lighthouse.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Phew! I see A LOT of errors in your code (even after I corrected the compilation errors):
You're not following the Java naming conventions:
Class names should be nouns, in mixed case with the first letter of each internal word capitalized
while red is a noun it should be more descriptive and be capitalized. The same goes for gui1
You're extending JFrame which in plain english would say: red is a JFrame, you should really avoid this and create your GUI based on JPanels instead... see Java Swing using extends JFrame vs callint it inside of class
You're setting size (a REAAAAAAALLY big one window for the JButton sizes you're using), instead use pack()
You're using null-layout, while pixel-perfect GUIs might seem like the easiest way to create complex GUIs for Swing newbies, the more you use them the more problems related to this you'll find in the future, they are hard to maintain and cause random problems, they don't resize, etc. Please read Null layout is evil and Why is it frowned upon to use a null layout in Swing? for more information about why you should avoid its use and why you should change your GUI to work with Layout Managers along with Empty Borders for extra spacing between components.
You're making use of a deprecated method JFrame#show() you should be using JFrame#setVisible(...) instead.
Related to point #4, you shouldn't be calling setBounds(...) method, but let that calculations to the layout managers.
You're not placing your program on the Event Dispatch Thread (EDT), Swing is not thread safe, you can fix this by changing your main() method as follows:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//Your constructor here
}
});
}
You're mixing AWT and Swing components, instead of using AWT's Canvas use Swing's JPanel which has more functionality and support.
Images will become embedded resources once they're packaged in a JAR file, so it's wise to start treating them as if they already were, not as external files as shown in the embedded-resource tag.
Once you change from Canvas to JPanel you should override its paintComponent(...) method and not paint(...) and call it's super.paintComponent(g) method as the first line, also don't forget to add the #Overrides annotation. See the tutorial on Swing custom painting.
You're abusing the use of static keyword, see how does the static keyword works?
After seeing all the above errors I recommend you to go back and Learn the basics of the language before starting with a graphical environment which will only add more difficulty to your learning.
From what I understand you want to draw an image on a button click, if that's the case then you can wrap your image in a JLabel and add that JLabel to a JPanel which then is added to a parent JPanel which is later added to the JFrame:
As you can see in the GIF above, the icon is displayed after user presses the button.
Obviously this can be improved for the GUI to be more "attractive" with combinations of layout managers and empty borders as stated before.
This was done with the following code:
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ImageDrawingFromOneClassToAnother {
private JFrame frame;
private JPanel pane;
private JPanel leftPane;
private JPanel rightPane;
private ImageIcon icon;
private JButton button;
private JLabel label;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ImageDrawingFromOneClassToAnother().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
icon = new ImageIcon(this.getClass().getResource("king.png")); //Read images as if they were already embedded resources
button = new JButton("Draw image");
label = new JLabel(""); //Create an empty label
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(icon); //On button click, we set the icon for the empty label
}
});
pane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200); //Set a size for the main panel
}
};
pane.setLayout(new GridLayout(1, 2)); //The main panel
leftPane = new JPanel(); //The button panel
leftPane.setLayout(new BoxLayout(leftPane, BoxLayout.PAGE_AXIS));
leftPane.add(button);
rightPane = new JPanel(); //The panel where the image will be drawn
rightPane.add(label);
//We add both (button and image) panels to the main panel
pane.add(leftPane);
pane.add(rightPane);
frame.add(pane); //Add the main panel to the frame
frame.pack(); //Calculate its preferred size
frame.setVisible(true); //Set it to be visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

java fullscreen window with transparency

I am trying to create a fullscreen window that cover the whole screen using Java. This window must also have some transparency (about 30%-50% transparent). When saying whole screen, I do mean it cover everything (including the dock/taskbar/menubar in OSX/Linux/Windows), and when I say with transparancy, I mean a real-time transparancy and not just a hacked screenshot. Here is what I am aware-of/tried:
Using Java Fullscreen API: while it creates a true fullscreen, you cannot have some transparency with it (only opaque color). One hack is to take a screenshot of the whole desktop and set it as background for the window, but this mean it is not real-time transparency.
Setting window size to match screen dimension: while it fills the whole screen, in certain OSes (e.g. Mac OS X) the window will be rendered behind the dock/menubar, and not above it. However, transparency do work here.
Using setWindowOpacity API: it work in the second case, but not in the first (Fullscreen API)
Using setBackground with alpha: it work like the setWindowOpacity, but only in certain OSes. But also doesn't work with Fullscreen API.
Use JFrame/JWindow/JDialog/Frame/Window: tried every window model I could, without any luck
So I am asking if this is possible through a another hack that I am not aware of, then I would be happy to hear about.
The goal is to overlay a semi-transparent fullscreen over the desktop.
is possible only with visible TaskBar e.i.
.
GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
otherwise you got and exception
.
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
The effects for full-screen windows are not supported.
or by using brutte_force to DirectX freezed my PC twicw, only power_off to save PC's GPU
import com.sun.awt.AWTUtilities;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JFrameOpacityExample {
private JFrame myFrame = new JFrame("Test Frame");
private boolean opacity = true;
private boolean resize = true;
private JButton button = new JButton("Opacity");
private JButton button1 = new JButton("Resize");
public JFrameOpacityExample() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (opacity) {
AWTUtilities.setWindowOpacity(myFrame, 0.50f);
opacity = false;
} else {
AWTUtilities.setWindowOpacity(myFrame, 1.0f);
opacity = true;
}
}
});
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (resize) {
Rectangle dim = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
int h = dim.height;
int w = dim.width;
myFrame.setBounds(00, 00, w, h);
resize = false;
} else {
myFrame.setBounds(100, 100, 400, 400);
resize = true;
}
}
});
JPanel panel = new JPanel();
panel.add(button);
panel.add(button1);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(panel);
myFrame.setSize(400, 400);
myFrame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrameOpacityExample jFrameOpacityExample = new JFrameOpacityExample();
}
});
}
}

Get a components location on its current monitor

I want to set the location of a JPopupMenu depending of the y location of the button that opens the menu. My code works fine on my first monitor, but fails on my second monitor, wich has a different height.
The problem is getLocationOnScreen() delivers the location relative to the main screen, not the actual screen on which the component is shown.
My code:
// screenSize represents the size of the screen where the button is
// currently showing
final Rectangle screenSize = dateButton.getGraphicsConfiguration().getBounds();
final int yScreen = screenSize.height;
int preferredY;
// getLocationOnScreen does always give the relative position to the main screen
if (getLocationOnScreen().y + dateButton.getHeight() + datePopup.getPreferredSize().height > yScreen) {
preferredY = -datePopup.getPreferredSize().height;
} else {
preferredY = getPreferredSize().height;
}
datePopup.show(DateSpinner.this, 0, preferredY);
How can I get the location of a component on its actual monitor?
I got a solution for this using the bounds of the second screen, it's quite simple:
public static Point getLocationOnCurrentScreen(final Component c) {
final Point relativeLocation = c.getLocationOnScreen();
final Rectangle currentScreenBounds = c.getGraphicsConfiguration().getBounds();
relativeLocation.x -= currentScreenBounds.x;
relativeLocation.y -= currentScreenBounds.y;
return relativeLocation;
}
Thanks for your answers!
Usually when you call "getLocationOnScreen()" it gets the location of the component "this" (from the code I don't quite understand who "this" is).
Maybe you can try to get location of the button by using "button.getLocationOnScreen()".
Here is a small snippet that shows how to position elements relatively to another one. It displays a popup menu below the button, and a JDialog to its left. I tested it on a multi-screen environment where secondary screen is on the right of the main one.
Also, use getSize(), getWidth() and getHeight() instead of getPreferredSize(). getSize(), getWidth and getHeight return the actual dimensions of the component, while getPreferredSize() is only an indicator to the LayoutManager to what the component wishes to have.
If you use the method JPopupMenu.show() make sure to use coordinates and sizes relative to the invoker component.
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class Test2 {
public static void main(String[] args) {
final JFrame frame = new JFrame();
final JButton button = new JButton("Hello");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(new JMenuItem("Some test"));
System.err.println(button.getLocationOnScreen());
popupMenu.show(button, 0, button.getHeight());
JDialog dialog = new JDialog(frame);
dialog.setSize(100, 30);
Point locationOnScreen = button.getLocationOnScreen();
locationOnScreen.x += button.getWidth();
dialog.setLocation(locationOnScreen);
dialog.setVisible(true);
}
});
frame.addComponentListener(new ComponentListener() {
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentResized(ComponentEvent e) {
info(button);
}
private void info(final JButton button) {
if (button.isShowing()) {
System.err.println(button.getLocationOnScreen());
System.err.println(button.getGraphicsConfiguration().getBounds());
}
}
#Override
public void componentMoved(ComponentEvent e) {
info(button);
}
#Override
public void componentHidden(ComponentEvent e) {
}
});
button.setPreferredSize(new Dimension(200, 60));
frame.add(button);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}

Categories