我正在创建一些GUI,并制作了这个JDialog,试图在其中创建姓名、电话号码和年龄的模板。我的问题是,当你按下按钮时,你会称之为这种方法:
public void createKunde(){
JDialog addDialog = new JDialog(frame);
JPanel addContentPane =(JPanel) addDialog.getContentPane();
addContentPane.setBorder(new EmptyBorder(12,12,12,12));
addContentPane.setLayout(new BorderLayout(6,6));
addDialog.setTitle("Opret Kunde");
addDialog.setSize(800, 400);
addDialog.setLocationRelativeTo(frame);
addDialog.setModal(true);
addDialog.setVisible(true);
JPanel addContent = new JPanel();
addContent.setLayout(new GridLayout(4,4));
JTextField addName = new JTextField(50);
addContent.add(addName);
JTextField addAge = new JTextField(50);
addContent.add(addAge);
JTextField addPhone = new JTextField(50);
addContent.add(addPhone);
addContentPane.add(addContent, BorderLayout.WEST);
addDialog.add(addContentPane);
}
我只是无法在我的JDialog中显示TextFields。我看不出问题出在哪里了?
您必须使您的JDialog可见,在末尾添加并从顶部删除:
addDialog.setVisible(true);
就我记忆中的java swing而言,你不可能让第一个东西可见并构建它
这里有另一个例子:
private void showSimpleDialog() {
final JDialog d = new JDialog(this, "Run", true);
d.setSize(200, 150);
JLabel l = new JLabel("Pagination Swing Demo", JLabel.CENTER);
d.getContentPane( ).setLayout(new BorderLayout( ));
d.getContentPane( ).add(l, BorderLayout.CENTER);
JButton b = new JButton("Run");
b.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ev) {
createFrame();
d.setVisible(false);
d.dispose( );
}
});
JPanel p = new JPanel( ); // Flow layout will center button.
p.add(b);
d.getContentPane( ).add(p, BorderLayout.SOUTH);
d.setLocationRelativeTo(this);
d.setVisible(true);
}
您的代码正试图将相同的父级添加到容器本身,即jdailog添加到jdsilog本身
并且添加组件后,您的addDialog未设置为可见
所以最好让它在结束时可见
这是您修改后的完整工作程序
package com.kb.gui;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class JdialogEx1 {
public static void main(String[] args) {
createKunde();
}
public static void createKunde(){
Frame frame = new JFrame();
JDialog addDialog = new JDialog(frame);
JPanel addContentPane =(JPanel) addDialog.getContentPane();
addContentPane.setBorder(new EmptyBorder(12,12,12,12));
addContentPane.setLayout(new BorderLayout(6,6));
addDialog.setTitle("Opret Kunde");
addDialog.setSize(800, 400);
addDialog.setLocationRelativeTo(frame);
addDialog.setModal(true);
JPanel addContent = new JPanel();
addContent.setLayout(new GridLayout(4,4));
JTextField addName = new JTextField(50);
addContent.add(addName);
JTextField addAge = new JTextField(50);
addContent.add(addAge);
JTextField addPhone = new JTextField(50);
addContent.add(addPhone);
addContentPane.add(addContent, BorderLayout.WEST);
addDialog.setVisible(true);
}
}