Positioning a JDialog to appear below a JTextField in Swing?
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.
精彩评论