我正在开发一个摇摆应用程序,需要在一个表单上放置两个 JFileChoosers。我似乎无法将它们放置在特定位置(要求它们彼此相邻放置,而不是一个在另一个之上)。编码:
public class ServerGUI extends JFrame implements ActionListener {
private JPanel JPanel1 = null;
private JButton startStopButton = null;
private JTextField portSelect = null;
private JLabel portLabel = null;
private JFileChooser rootDir = null;
private JLabel rootLabel = null;
private JFileChooser maintenanceDir = null;
private JLabel maintenanceLabel = null;
private JCheckBox maintenanceMode = null;
private JLabel serverInfo = null;
ServerGUI() {
/// create an instance of our server
webserver = new WebServer();
/// build form controls -- with default options
JPanel1 = new JPanel();
startStopButton = new JButton("Start Server");
portSelect = new JTextField("10008");
portLabel = new JLabel("Port:");
rootDir = new RootChooser(System.getProperty("user.dir"));
/// choose directories only
rootDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
rootLabel = new JLabel("Choose web root directory:");
maintenanceDir = new MainChooser(System.getProperty("user.dir"));
/// choose directories only
maintenanceDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
maintenanceLabel = new JLabel("Choose maintenance root directory:");
maintenanceMode = new JCheckBox("Switch to maintenance mode");
/// not selected by default
maintenanceMode.setSelected(false);
serverInfo = new JLabel("Start");
/// add controls onto form
add(JPanel1, "Center");
serverInfo.setBounds(0, 0, 20, 10);
JPanel1.add(serverInfo);
startStopButton.addActionListener(this);
startStopButton.setBounds(35, 10, 2, 3);
startStopButton.setLayout(null);
JPanel1.add(startStopButton);
JPanel1.add(maintenanceMode);
JPanel1.add(portLabel);
JPanel1.add(portSelect);
/// set layout for directory choosers
// rootDir.setBounds(0, 0, 100, 100);
// rootDir.setLayout(null);
JPanel1.add(rootLabel);
JPanel1.add(rootDir);
// maintenanceDir.setBounds(130, 20, 100, 100);
// maintenanceDir.setLayout(null);
JPanel1.add(maintenanceLabel);
JPanel1.add(maintenanceDir);
}
}
我尝试了 setBounds()、setLocation() 用于标签、setBound() 和 setLayout(null) 用于按钮之间的变化,并创建了 JFileChooser 的扩展类以尝试对 Dlg 位置进行硬编码。
static class RootChooser extends JFileChooser {
private static final long serialVersionUID = 1L;
protected JDialog createDialog(Component parent)
throws HeadlessException {
JDialog dlg = super.createDialog(parent);
dlg.setLocation(0, 40); // new location does not apply
return dlg;
}
RootChooser(String filePath) {
super(filePath);
}
}
和
static class MainChooser extends JFileChooser {
private static final long serialVersionUID = 1L;
protected JDialog createDialog(Component parent)
throws HeadlessException {
JDialog dlg = super.createDialog(parent);
dlg.setLocation(200, 140); // does not work as expected
return dlg;
}
MainChooser(String filePath) {
super(filePath);
}
}
如何将这些控件放置在特定位置?