2017-04-19 33 views
0

我一直在使用的問題是,每當我將一個JButton添加到一個JPanel時,我所擁有的任何其他JButton都向該方向移動。添加多個JButtons移動其他JButtons(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); 
    } 
} 

然後朝按鈕1 BUTTON2下移。有誰知道爲什麼和/或修復它?

編輯:我問的是,如何添加另一個按鈕,而無需移動其他按鈕。

回答

0

我不知道你的意圖是什麼。你只是說它不符合你的期望。所以我不能給你一個確切的解決方案。

無論如何,首先閱讀Swing教程How to Use GridBagLayout中有關使用GridBagLayout的工作示例的部分。

我看到兩個問題:

  1. 你永遠不會改變的gridx/y值。這兩個組件都添加到網格(0,0),這不是GridBagLayout應該如何工作。每個組件都需要添加到不同的單元中。

  2. (500,....)的Insets值似乎非常大。