2013-03-13 2 views
0

양식을 생성하기 위해 찾은 샘플 코드를 편집하려고합니다. 샘플 코드에는 4 개의 레이블과 텍스트 필드가 완벽하게 정렬되어 있습니다. 마지막에 버튼을 추가하려고하지만 버튼 대신 화면의 왼쪽 상단 모서리에있는 레이블이 겹쳐 있습니다. 이 문제를 어떻게 해결할 수 있습니까?Jframe 레이블 및 단추를 정렬하는 방법

public class SpringDemo { 
private static void createAndShowGUI() { 
    String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "}; 
    int labelsLength = labels.length; 

    //Create and populate the panel. 
    JPanel p = new JPanel(new SpringLayout()); 
    for (int i = 0; i < labelsLength; i++) { 
     JLabel l = new JLabel(labels[i], JLabel.TRAILING); 
     p.add(l); 
     JTextField textField = new JTextField(10); 
     l.setLabelFor(textField); 
     p.add(textField); 
    } 
    JButton l = new JButton("Submit"); 
    p.add(l); 

    //Lay out the panel. 
    SpringUtilities.makeCompactGrid(p, 
            labelsLength, 2, //rows, cols 
            7, 7,  //initX, initY 
            7, 7);  //xPad, yPad 

    //Create and set up the window. 
    JFrame frame = new JFrame("SpringForm"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //Set up the content pane. 
    p.setOpaque(true); //content panes must be opaque 
    frame.setContentPane(p); 

    //Display the window. 
    frame.pack(); 
    frame.setVisible(true); 
} 

public static void main(String[] args) { 
    //Schedule a job for the event-dispatching thread: 
    //creating and showing this application's GUI. 
    javax.swing.SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGUI(); 
     } 
    }); 
} 

}

답변

1

를 문제가 발생하기 때문에 라벨과 텍스트 필드에 필요한 크기로 JPanel를 압축하고 당신이 어떤 제약을 두지 않는 것이 makeCompactGrid 방법 귀하의 버튼을 어디 레이아웃을 알 수 있도록하자.

빈 레이블을 만들고 단추 다음에 추가 한 다음 makeCompactGrid을 호출하면 마지막 레이블 아래에 단추를 넣을 수 있습니다. 마찬가지로

JButton l = new JButton("Submit"); 
p.add(l); 
p.add(new JLabel()); 
SpringUtilities.makeCompactGrid(p, 
           labelsLength + 1, 2, //rows, cols 
           7, 7,  //initX, initY 
           7, 7);  //xPad, yPad 

당신은 또한 당신이 원하는 곳에 넣어 레이아웃을 강제로 버튼에 제약을 넣어 시도 할 수 있지만 그 방법은 모르는 것 같은 makeCompactGrid 아주 잘 작동하지 않을 수 있습니다 단추.

+0

이것은 완벽하게 작동했습니다. 고맙습니다 :) – MrSnare

0

이 방법을 시도 할 수 있을까요?

private void addComponent(Container container, Component c, int x, int y,int width, int  
height){ 

c.setBounds(x, y, width, height); 
container.add(c); 
} 

그리고 다음과 같이 호출 :

addComponent(container such as JPanel, component such as a JButton, x position, yposition,  
width, height); 
+0

이것은 작동하지 않았습니다. 나는 이유를 모른다. 그래도 또 다른 대답을했습니다. 노력해 주셔서 감사합니다 :) – MrSnare

관련 문제