显示相对于其他主JFrame上的元素的JFrame

时间:2015-03-13 00:49:38

标签: java swing jframe

例如,您可以想象有人要求您重新发明下拉菜单。正确的方法似乎是制作JFrame并在单击某个元素时显示它。这样的JFrame将是未修饰的。我正是这样做的。我的程序希望允许用户点击图像(代表某些内容)并从其他可用图像中进行选择。

所以我制作了这样的JFrame:

public class FrameSummonerSpells extends JFrame {
  public FrameSummonerSpells() {
    settings = set;
    // Remove title bar, close buttons...
    setUndecorated(true); 
    setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    //Will populate the selection of objects in grid layout
    createButtons();
    //Will make the frame as large as the content
    pack();
    //Do not appear by default
    setVisible(false); 
  }
}

我从JButton显示它:

  private void showPopup() {
    //Create the popup if needed
    if(popup==null)
      createPopup();
    //Get location of this button
    Point location = getLocation();
    //Move the popup at the location of this button
    //Also move vertically so it appears UNDER the button
    popup.setLocation(location.x, location.y+this.getSize().height);
    //Show the popup
    popup.setVisible(true);
  }

如您所见,我设置的位置不是相对于按钮或框架设置的:

image description

但是,应该注意的是,我发送给setLocation的参数被接受,但是被错误地解释了。

我的问题是:如何生成一个可以包含JComponent的新对象(JFrame或其他),在窗口上显示或者甚至在窗口上扩展并保持与窗口的相对位置(或某些元素)?

这就是我要显示的内容:

image description

2 个答案:

答案 0 :(得分:2)

  

如何生成一个新对象(JFrame或其他东西

不要使用JFrame。子窗口应该(可能)是JDialog,JFrame作为所有者。

  

我接受发送给setLocation的参数,但只是错误地解释了。

尝试使用getLocationOnScreen()方法获取源组件的位置。您可能会使用该组件的高度来确定弹出窗口的位置,以便它显示在组件下方。

答案 1 :(得分:0)

很少需要调整。

  1. JDialogJFrame更好,因为它可以成为主框架的子窗口。
  2. getLocation没有给出正确的坐标。 getLocationOnScreen做了。
  3. 现在代码看起来像这样 - 我已经覆盖setVisible,以便框架在显示时始终对齐:

      @Override
      public void setVisible(boolean visible) {
        if(visible) {
          //Get location of the button
          Point location = parent_button.getLocationOnScreen();
          //Move the popup at the location of the
          //Also move vertically so it appears UNDER the button
          setLocation(location.x, location.y+parent_button.getSize().height);
        }
        //Call the original setVisible
        super.setVisible(visible); 
      }