Java中的GridLayout帮助
我有一个JPanel,代码如下:Java中的GridLayout帮助,java,swing,grid-layout,Java,Swing,Grid Layout,我有一个JPanel,代码如下: JPanel pane = new JPanel(); pane.setLayout(new GridLayout(3, 2, 10, 30)); final JTextField fileName = new JTextField(); pane.add(fileName); JButton creater = new JButton("Create File"); pane.add(creater); JButton deleter = new JButto
JPanel pane = new JPanel();
pane.setLayout(new GridLayout(3, 2, 10, 30));
final JTextField fileName = new JTextField();
pane.add(fileName);
JButton creater = new JButton("Create File");
pane.add(creater);
JButton deleter = new JButton("Delete File");
pane.add(deleter);
我想知道,如何使JTextField在GridLayout上占用两个空格,而让两个按钮在同一行上各占用一个空格,从而共享一行?您不能使用GridLayout进行列跨距。我建议你尝试一下,这是一个很难做的GridleOut。您必须创建更宽的单元格(例如,
新建GridLayout(2,2,10,30)
,然后将文本字段添加到第一个单元格。然后您必须创建另一个带有GridLayout(2,1)的面板,将其放入第二行的单元格中,并将按钮添加到此嵌套网格布局的第一个单元格中
很快,您需要将GridLayout转换为其他GridLayout
有更好的工具来实现这一点。首先看看GridBagLayout。这只是为了确保生活并不总是如此。然后看看其他解决方案,比如MigLayout。它不是JDK的一部分,但它确实是一个功能强大的工具,可以让您的生活更轻松。请查看关于的教程 示例代码:
JPanel pane = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
pane.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
final JTextField fileName = new JTextField();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 0;
pane.add(fileName, c);
JButton creater = new JButton("Create File");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
pane.add(creater, c);
JButton deleter = new JButton("Delete File");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
pane.add(deleter, c);
在否定了第三方布局的建议之后,由于我对GBL怀有恶意的仇恨,我认为是时候“把我的代码放在我的嘴边”供公众审查(和否定) 此SSCCE使用嵌套布局
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class SimpleLayoutTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JPanel ui = new JPanel( new BorderLayout(20,20) );
// I would go for an EmptyBorder here, but the filled
// border is just to demonstrate where the border starts/ends
ui.setBorder( new LineBorder(Color.RED,15) );
// this should be a button that pops a JFileChooser, or perhaps
// a JTree of the existing file system structure with a JButton
// to prompt for the name of a new File.
final JTextField fileName = new JTextField();
ui.add(fileName, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 10, 30));
ui.add(buttonPanel, BorderLayout.CENTER);
JButton creater = new JButton("Create File");
buttonPanel.add(creater);
JButton deleter = new JButton("Delete File");
buttonPanel.add(deleter);
JOptionPane.showMessageDialog(null, ui);
}
};
SwingUtilities.invokeLater(r);
}
}
一个好的建议:远离标准布局管理器并使用一个好的建议:在放弃J2SE提供的或Oracle不支持的布局之前,先学习如何使用和嵌套标准布局。请注意,对于人们最熟悉的布局,您也更有可能在公共论坛上获得帮助,这将是J2SE的核心布局。