2017-04-19 8 views
0

私がしてきた問題は、JButtonをJPanelに追加するたびに、他のJButtonがその方向に移動したことです。複数のJButtonを追加すると他のJButtonが移動する(Java)

ここで最初のコードは次のとおりです。

//imports 
import java.awt.*; 
import javax.swing.*; 

public class Example { 
    public static void main(String[] args) { 
    // Create the frame and panel and the Grid Bag Constraints 
    JFrame frame = new JFrame(); 
    JPanel panel = new JPanel(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 
    // Create ONE JButton 
    JButton button1 = new JButton("Button1"); 
    // Set the frame's properties 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(600, 600); 
    frame.getContentPane().add(panel, BorderLayout.NORTH); 
    frame.setVisible(true); 
    // Set Basic Grid Bag Constraints settings. 
    c.gridx = 0; 
    c.gridy = 0; 
    // Set the Insets 
    c.insets = new Insets(0, 0, 0, 0); 
    // Add the Grid Bag Constraints and button1 the panel 
    panel.add(button1, c); 
    } 
} 

すべてが正しく動作するようですか?まあ 我々は第二ボタン追加した場合:

//imports 
import java.awt.*; 
import javax.swing.*; 

public class Example { 
    public static void main(String[] args) { 
    // Create the frame and panel and the Grid Bag Constraints 
    JFrame frame = new JFrame(); 
    JPanel panel = new JPanel(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 
    // Create TWO JButtons 
    JButton button1 = new JButton("Button1"); 
    JButton button2 = new JButton("Button2"); 
    // Set the frame's properties 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(600, 600); 
    frame.getContentPane().add(panel, BorderLayout.NORTH); 
    frame.setVisible(true); 
    // Set Basic Grid Bag Constraints settings. 
    c.gridx = 0; 
    c.gridy = 0; 
    // Set the Insets 
    c.insets = new Insets(0, 0, 0, 0); 
    // Add the Grid Bag Constraints and button1 the panel 
    panel.add(button1, c); 
    // Set the Insets 
    c.insets = new Insets(500, 0, 0, 0); 
    // Add the Grid Bag Constraints and button2 the panel 
    panel.add(button2, c); 
    } 
} 

その後button2を向けて下方に移動Button1を。誰かが理由や修正を知っていますか?

EDIT:他のボタンを移動せずに別のボタンを追加する方法です。

答えて

0

あなたの意図がわかりません。あなたはそれがあなたが期待することをしないと述べているだけです。だから私はあなたに正確な解決策を与えることはできません。

いずれの場合でも、GridBagLayoutを使用して作業例についてはHow to Use GridBagLayoutのSwingチュートリアルのセクションを読んで開始してください。

  1. あなたはgridx/yの値を変更することはありません:

    は、私は2つの問題を参照してください。両方のコンポーネントがグリッド(0、0)に追加されますが、これはGridBagLayoutの動作方法ではありません。すべてのコンポーネントを別のセルに追加する必要があります。

  2. Insets(500、....)の値は非常に大きいようです。

関連する問題