【发布时间】:2015-11-15 23:24:58
【问题描述】:
我目前正在开发一个 GUI,我想使用 JOptionPane 显示一个与下图相同的弹出窗口。我目前能够显示 JTextField 和 JLabel,但与图片中显示的位置不同。此外,我无法将用户输入存储到变量中。有人可以向我提供提示或一些代码示例,以便我可以继续走正确的道路吗? 这就是我正在做的事情:
GridBagConstraints layoutConst = null; // GUI 组件布局 JPanel myPanel = new JPanel();
JLabel sNameLabel = null; // Label for hourly salary
JLabel sDepLabel = null; // Label for yearly salary
JTextField sNameField = null; // Displays hourly salary
JTextField sDepField = null; // Displays yearly salary
sNameLabel = new JLabel("Student Name:");
sDepLabel = new JLabel("Student Department:");
sNameField = new JTextField(15);
sNameField.setEditable(true);
sDepField = new JTextField(15);
sDepField.setEditable(true);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 0;
layoutConst.gridy = 0;
layoutConst.insets = new Insets(10, 10, 10, 10);
myPanel.add(sNameLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 0;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
myPanel.add(sNameField, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 0;
layoutConst.gridy = 0;
layoutConst.insets = new Insets(10, 10, 10, 10);
myPanel.add(sDepLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 1;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
myPanel.add(sDepField, layoutConst);
JOptionPane.showInputDialog(null, myPanel, "Add Course", JOptionPane.OK_CANCEL_OPTION);
【问题讨论】:
-
只需将它们放在使用 GridBagLayout 的 JPanel 中即可。
-
JOptionPane的一个很棒的功能是,如果你通过message参数传递一个Component,它会简单地显示该组件
标签: java user-interface joptionpane