[英]Java adding components to JOptionPane
我正在尝试为简单的数据输入对话框创建自定义面板。 我创建了一个自定义面板,我添加了标签和文本字段。 我正在尝试将其添加到JOptionPane进行显示。
当我调用它时,我的组件不会显示,但JOptionPane按钮会显示。 这样做的正确方法是什么? 提前致谢!!
这是我创建自定义面板并调用JOptionPane的地方:
public class ListenCustEdit implements ActionListener {
@Override
@SuppressWarnings("empty-statement")
public void actionPerformed(ActionEvent e) {
TestPanel panel = new TestPanel();
int input = JOptionPane.showConfirmDialog(frame, panel, "Edit Customer:"
,JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (input == 0) {
// OK
JOptionPane.showMessageDialog(frame,"Changes savewd");
} else {
// Cancel
JOptionPane.showMessageDialog(frame, "No changes were saved");
}
}
}
这是我的自定义面板类:
public class TestPanel extends JPanel {
JTextField custIdTextField;
JTextField companyTextField;
JTextField firstNameTextField;
JTextField lastNameTextField;
public TestPanel() {
initUI();
}
public final void initUI() {
// create the panel and set the layout
JPanel main = new JPanel();
main.setLayout(new GridLayout(4,4));
// create the labels
JLabel custIdLabel = new JLabel("Cust Id: ");
JLabel companyLabel = new JLabel("Company: ");
JLabel firstNameLabel = new JLabel("First Name: ");
JLabel lastNameLabel = new JLabel("Last Name: ");
// create the text fields
custIdTextField = new JTextField();
companyTextField = new JTextField();
firstNameTextField = new JTextField();
lastNameTextField = new JTextField();
// add componets to panel
main.add(custIdLabel);
main.add(custIdTextField);
main.add(companyLabel);
main.add(companyTextField);
main.add(firstNameLabel);
main.add(firstNameTextField);
main.add(lastNameLabel);
main.add(lastNameTextField);
}
您需要将主面板添加到TestPanel。
public final void initUI() {
// ...
add(main);
}
在initUI中,您创建一个JPanel(称为“main”)并将其充满组件,但不对其执行任何操作。 您需要将“main”添加到TestPanel的实际实例中,或者只是跳过创建“main”面板的步骤。
第一种方式:
public final void initUI() {
// ... everything as before, then
this.add(main);
}
第二种方式:
public final void initUI() {
this.setLayout(new GridLayout(4,4));
// create the labels
JLabel custIdLabel = new JLabel("Cust Id: ");
JLabel companyLabel = new JLabel("Company: ");
JLabel firstNameLabel = new JLabel("First Name: ");
JLabel lastNameLabel = new JLabel("Last Name: ");
// create the text fields
custIdTextField = new JTextField();
companyTextField = new JTextField();
firstNameTextField = new JTextField();
lastNameTextField = new JTextField();
// add componets to panel
this.add(custIdLabel);
this.add(custIdTextField);
this.add(companyLabel);
this.add(companyTextField);
this.add(firstNameLabel);
this.add(firstNameTextField);
this.add(lastNameLabel);
this.add(lastNameTextField);
}
(“这个。”并不是绝对必要的,但我添加它们是为了说明。)
希望这可以帮助!
您没有在构造函数中将主Panel添加到TestPanel实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.