2017-04-19 1 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); 
    } 
} 

모든 것이 제대로 작동 보인다? 우리가 두 번째 단추를 추가 글쎄 경우 : 단추 2를 향해 아래로 이동 단추 1 다음

//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); 
    } 
} 

. 누구든지 이유 및/또는 해결 방법을 알고 있습니까?

편집 : 다른 버튼을 이동하지 않고 다른 버튼을 추가하는 방법은 무엇입니까?

답변

0

나는 당신의 의도가 무엇인지 알지 못합니다. 당신은 그것이 당신이 기대하는 것을하지 않는다고 진술합니다. 그래서 나는 정확한 해결책을 줄 수는 없다.

어쨌든 How to Use GridBagLayout에있는 스윙 튜토리얼에서 GridBagLayout을 사용하는 작업 예제를 읽어보십시오.

  1. 당신은는 gridx/y 값을 변경하지 않을 :

    나는 두 가지 문제를 참조하십시오. 두 구성 요소가 모두 GridBagLayout의 작동 방식이 아닌 그리드 (0, 0)에 추가됩니다. 모든 구성 요소를 다른 셀에 추가해야합니다.

  2. Insets (500, ....) 값이 매우 큰 것처럼 보입니다.

관련 문제