我试图将两个按钮堆叠在一起并将它们锚定到面板的顶部,但第二个按钮留在面板的中心。
在此代码中,我创建了一个拆分窗格,然后向其中添加了两个面板。一个面板包含按钮(我感兴趣的面板),另一个包含一个文本字段。这些按钮使一些文本出现在文本字段中。
我想弄清楚 GridBagLayout 参数的哪个正确组合将允许我将两个按钮放在一起(中间没有间隙)并将它们锚定到面板的顶部。我用 weighting 和 gridy 参数尝试了一些不同的东西,但无济于事。
提前感谢您的时间和回复。
package gridbagtest;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GridBagTest
{
public static void main(String[] args)
{
JFrame gridTest = new JFrame("Grid Bag Layout Test");
JSplitPane splitPaneHorizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
final JTextField blah = new JTextField(30);
JPanel textPane = new JPanel();
textPane.add(blah);
JPanel buttonPane = new JPanel();
buttonPane.setBackground(Color.WHITE);
buttonPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 0;
// c.gridy = GridBagConstraints.RELATIVE;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
JButton flightPlanButton = new JButton("First Button");
flightPlanButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{ blah.setText("First Button pushed"); }
});
buttonPane.add(flightPlanButton, c);
JButton powerButton = new JButton("Second Button");
powerButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{ blah.setText("Second Button pushed"); }
});
c.gridy = 1;
buttonPane.add(powerButton, c);
splitPaneHorizontal.setTopComponent(new JScrollPane(buttonPane));
splitPaneHorizontal.setBottomComponent(textPane);
gridTest.add(splitPaneHorizontal);
gridTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gridTest.pack();
gridTest.setSize(600,800);
gridTest.setVisible(true);
}
}