开发者

Positioning a JDialog to appear below a JTextField in Swing?

I want to position a JDialog box below a JTextField of a JFrame and when the dialog box opens my JFrame should not able to move -- that is, it should not be draggable. Any s开发者_开发知识库uggestions?


public class DialogTest {
    public static void main(String[] args) {

        final JFrame frame = new JFrame("Frame");
        JTextField field = new JTextField("Click me to open dialog!");
        field.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                JTextField f = (JTextField) e.getSource();
                Point l = f.getLocationOnScreen();

                JDialog d = new JDialog(frame, "Dialog", true);
                d.setLocation(l.x, l.y + f.getHeight());
                d.setSize(200, 200);
                d.setVisible(true);
            }
        });
        frame.add(field);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 100);
        frame.setVisible(true);
    }
}


Use JDialog.setLocationRelativeTo to set it below the text field.


Create a modal JDialog like this.

public class MyDialog extends JDialog
{
  private int width = 50;
  private int height = 50;

  public MyDialog(Frame parent, int x, int y)
  {
    super(parent, "MyTitle", true);
    setBounds(x, y, width, height);
  }

}

Being modal means the user won't be able to interact with the parent until the dialog has closed. You can figure out the location you want and pass the x,y coords in the constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜