我想用Java编写一个简单的文本编辑器。
我已经整理好布局,得出的结论是,我基本上需要3个JPanels,一个在另一个之上。第一个和第二个的高度很短,因为它们分别是菜单栏和一个包含2个JLabel的JPanel。
中间一个必须是高度最高的一个,因为所有文本都将包含在其中。
我想我需要使用GridBagLayout,但是那行不通,我需要它们占用的大空间比小空间大10倍。所有这些都将利用JFrame提供的宽度。
到目前为止,代码段是-
GridBagConstraints gbc = new GridBagConstraints
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
mainFrame.add(upperGrid, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 10;
mainFrame.add(upperGrid, gbc);
gbc.gridx = 0;
gbc.gridy = 11;
mainFrame.add(upperGrid, GBC);
结果我得到的是-
最佳答案
我建议您放弃GridLayout的想法。我将改为执行以下操作:
在菜单栏中使用JMenuBar
(https://docs.oracle.com/javase/tutorial/uiswing/components/menu.html)
使用BorderLayout:
JFrame frame = new JFrame();
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(new JLabel("Label 1"));
topPanel.add(new JLabel("Label 2"));
frame.add(topPanel, BorderLayout.NORTH);
JPanel bigPanel = new JPanel();
frame.add(bigPanel, BorderLayout.CENTER);
例如,当您需要安排带有很多文本字段的对话框时,可以使用GridLayout。但是对于这种“粗糙”的东西,BorderLayout更好,也因为它可能更快。 (可能我不确定)
编辑:如果您绝对必须使用GridBagLayout,则可以执行以下操作:
JPanel panel = new JPanel();
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[] { 0, 0 };
layout.rowHeights = new int[] { 0, 0, 0, 0 };
layout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
layout.rowWeights = new double[] { 0.0, 0.0, 1.0, Double.MIN_VALUE };
panel.setLayout(layout);
JPanel menuBar = new JPanel();
GridBagConstraints contraints = new GridBagConstraints();
contraints.fill = GridBagConstraints.BOTH;
contraints.gridx = 0;
contraints.gridy = 0;
panel.add(menuBar, contraints);
JPanel panelForLabels = new JPanel();
contraints = new GridBagConstraints();
contraints.fill = GridBagConstraints.BOTH;
contraints.gridx = 0;
contraints.gridy = 1;
panel.add(panelForLabels, contraints);
JPanel bigPanel = new JPanel();
contraints = new GridBagConstraints();
contraints.fill = GridBagConstraints.BOTH;
contraints.gridx = 0;
contraints.gridy = 2;
panel.add(bigPanel, contraints);
关于java - 如何使用GridBagLayout创建3个JPanels,一个在另一个之上,高度可变,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45532432/