2 つのボタンを重ねてパネルの上部に固定しようとしていますが、2 番目のボタンはパネルの中央にとどまります。
このコードでは、分割ペインを作成し、そこに 2 つのパネルを追加します。1 つのパネルにはボタン (関心のあるパネル) が含まれ、もう 1 つのパネルにはテキスト フィールドが含まれています。ボタンを使用すると、テキスト フィールドにテキストが表示されます。
GridBagLayout パラメーターの正しい組み合わせによって、2 つのボタンを (間に隙間なく) 重ねて配置し、それらをパネルの上部に固定できるようにする方法を見つけたいと思います。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);
}
}