2

私は Java で羊の群れのパーティクル シミュレーションを行う単純なアプリケーションを作成しています (聞かないでください)。このために、グラフィック用の JPanel (いくつかの標準解像度を含む単純なコンボボックスでサイズ変更可能) と、シミュレーションを開始および一時停止するためのボタンなどの他の要素を含むウィンドウが必要です。

私の質問: JFrame.pack メソッドを使用して、borderLayout を使用してすべてをうまくまとめています。しかし、何らかの理由で JPanel が間違ってパックされているようです。パッキングがそれを無視しているように見えるため、ウィンドウのサイズを変更して、現在持っている 2 つのボタンのみのサイズに合わせます。私は何を間違っていますか?

これはこれまでのコードです(少し初心者なので、私の愚かさについてのコメントはありません;)):

public class Window {
 public Sheepness sheepness;

 public ButtonPanel buttonPanel;
 public PaintPanel paintPanel;
 public JFrame frame;

 public Window(Sheepness sheepness, int width, int height) {
  this.sheepness = sheepness;

  frame = new JFrame("Sheepness simulation");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  //frame.setSize(width, height);

  BorderLayout frameLayout = new BorderLayout();
  JPanel background = new JPanel(frameLayout);
  background.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

  buttonPanel = new ButtonPanel(this);
  background.add(BorderLayout.SOUTH, buttonPanel.buttonBox);

  paintPanel = new PaintPanel(this);
  paintPanel.setSize(600, 600);
  background.add(BorderLayout.CENTER, paintPanel);

  frame.getContentPane().add(background);
  frame.pack();
  frame.setResizable(false);
  frame.setVisible(true);
 }
}

public class PaintPanel extends JPanel {
 public Window window;

 public PaintPanel(Window window) {
  this.window = window;
 }

 @Override
 public void paintComponent(Graphics g) {
  g.setColor(Color.blue);
  g.fillRect(0, 0, 300, 200);
 }
}

public class ButtonPanel {
 public Window window;
 public Box buttonBox;

 public JButton startButton;
 public JButton resetButton;

 public ButtonPanel(Window window) {
  this.window = window;

  buttonBox = new Box(BoxLayout.X_AXIS);

  startButton = new JButton("Start");
  startButton.addActionListener(new startButtonListener());
  buttonBox.add(startButton);

  resetButton = new JButton("Reset");
  resetButton.addActionListener(new resetButtonListener());
  buttonBox.add(resetButton);
 }
}
4

1 に答える 1

4

試す:

paintPanel.setPreferredSize(600, 600);

Window.pack()サブコンポーネントの優先サイズにサイズを合わせ、子コンポーネントから優先サイズを取得JPanelします(あなたの場合はありません)。

于 2009-10-19T10:46:31.950 に答える