2012-08-23 2 views
2

간단한 문제가있는 것 같습니다. 왼쪽에 맞추려는 레이블이 있지만 크기를 조정하면 가운데로 표류하기 시작합니다. 이것은 내가 추가 할 계획 인 다른 구성 요소들의 정렬을 포기할 것입니다. 왼쪽에서 그들을 지키려면 어떻게해야합니까?Swing에서 구성 요소를 왼쪽 및 오른쪽으로 정렬하는 방법은 무엇입니까?

Example

그것은 확실하지 내 문제는 여기에 짧고 쉬운 코드의 새로운 기능 :

package com.protocase.notes.views; 

import com.protocase.notes.model.Note; 
import com.protocase.notes.model.User; 
import java.awt.Component; 
import java.util.Date; 
import javax.swing.BoxLayout; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 
import javax.swing.border.BevelBorder; 

/** 
* @author dah01 
*/ 
public class NotesPanel extends JPanel{ 

    public NotesPanel(Note note){ 
     this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); 
     JLabel creatorLabel = new JLabel("Note by "+note.getCreator()+ " @ "+note.getDateCreated()); 
     creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT); 
     creatorLabel.setHorizontalAlignment(JLabel.LEFT); 


     JTextArea notesContentsArea = new JTextArea(note.getContents()); 
     notesContentsArea.setEditable(false); 
     JScrollPane scrollPane = new JScrollPane(notesContentsArea); 

     JLabel editorLabel = new JLabel(" -- Last edited by "+note.getLastEdited() +" at "+note.getDateModified()); 
     editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT); 
     editorLabel.setHorizontalAlignment(JLabel.LEFT); 

     this.add(creatorLabel); 
     this.add(scrollPane); 
     this.add(editorLabel); 
     this.setBorder(new BevelBorder(BevelBorder.RAISED)); 
    } 


    public static void main(String[] args) { 
     JFrame frame = new JFrame("Notes Panel"); 
     Note note = new Note(); 
     User user = new User(); 
     user.setFirstName("d"); 
     user.setLastName("h"); 
     user.setUserID("dah01"); 
     note.setCreator(user); 
     note.setLastEdited(user); 
     note.setDateCreated(new Date()); 
     note.setDateModified(new Date()); 
     note.setContents("A TEST CONTENTS"); 
     NotesPanel np = new NotesPanel(note); 

     JScrollPane scroll = new JScrollPane(np); 
     frame.setContentPane(scroll); 
     np.setVisible(true); 
     frame.setVisible(true); 
     frame.pack(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 
+0

하지만 (즉, 'setAlignmentX') 각 라벨의 왼쪽에 ... 당신은 어떻게 될 것이라고 생각 했습니까? – user1329572

+0

편집 : 예제에서이 작업을 수행하고있었습니다. 코드에서 오른쪽으로 변경 한 것이 하나도 없습니다. – davidahines

+1

스텁 사용자/노트 클래스 사용 : http://pastebin.com/Si0iCPnG – EthanB

답변

4

패널에서 항목을 정렬하려면 모든 것을 정렬해야합니다. JScrollPane을 잊어 버렸습니다. 당신은 당신의 코드에 줄을 추가하는 경우, 정렬 당신을 위해 고정해야합니다

scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT); 

그리고 어떤 새로운 생성자과 같습니다 명시 적으로 수평 정렬을 설정하는

public NotesPanel(Note note){ 
    this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); 
    JLabel creatorLabel = new JLabel("Note by "+note.getCreator()+ " @ "+note.getDateCreated()); 
    creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT); 
    creatorLabel.setHorizontalAlignment(JLabel.LEFT); 


    JTextArea notesContentsArea = new JTextArea(note.getContents()); 
    notesContentsArea.setEditable(false); 
    JScrollPane scrollPane = new JScrollPane(notesContentsArea); 
    scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT); 

    JLabel editorLabel = new JLabel(" -- Last edited by "+note.getLastEdited() +" at "+note.getDateModified()); 
    editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT); 
    editorLabel.setHorizontalAlignment(JLabel.LEFT); 

    this.add(creatorLabel); 
    this.add(scrollPane); 
    this.add(editorLabel); 
    this.setBorder(new BevelBorder(BevelBorder.RAISED)); 
} 
+0

이것은 내가 찾던 해답이다. – davidahines

+0

내가 원하는 것은 중첩 레이아웃 관리자를 사용하지 않고 코드를 정렬하고 유지하는 것뿐이었습니다. – davidahines

3

당신의 의견 당, 나는 다른 어떤 layout와 함께 갈 당신을 추천 할 것입니다, 나는 것

: 당신이 MigLayout 갈 여기 MigLayout

추천

import java.awt.EventQueue; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.border.EmptyBorder; 
import net.miginfocom.swing.MigLayout; 
import javax.swing.JLabel; 
import javax.swing.JTextArea; 


public class MigLayoutDemo { 

    private JPanel contentPane; 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        new MigLayoutDemo(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the frame. 
    */ 
    public MigLayoutDemo() { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setBounds(100, 100, 450, 300); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     frame.setContentPane(contentPane); 
     contentPane.setLayout(new MigLayout("", "[grow]", "[][grow][]")); 

     JLabel lblLabel = new JLabel("Label 1"); 
      lblLabel.setBorder(BorderFactory.createLineBorder(Color.red)); 
     contentPane.add(lblLabel, "cell 0 0,alignx left"); 

     JTextArea textArea = new JTextArea(); 
     contentPane.add(textArea, "cell 0 1,grow"); 

     JLabel lblLabel_1 = new JLabel("Label 2"); 
      lblLabel_1.setBorder(BorderFactory.createLineBorder(Color.red)); 
     contentPane.add(lblLabel_1, "cell 0 2,alignx left"); 
     frame.setVisible(true); 
    } 

} 

출력 :

enter image description here

당신이 빨간색 테두리 표시 labels을 볼 수 있듯이이 가운데로 뻗어되지 않습니다, 그들은 왼쪽 정렬된다.

+0

하지만, 나는 그것들을 정렬 상태로 유지하고, 수직으로 움직이게하고 싶다. – davidahines

+0

나는 당신의 업데이 트를 보지 못했지만, 미안 해요 ... –

+1

좋은 대답과 예제에 대한 Upvote하지만 난 정말 두 레이블을 왼쪽 정렬처럼 뭔가 간단한 외부 라이브러리에 대한 의존성을 높이고 싶지 않아요. – davidahines

1

BorderLayout을 사용하면 확실히 문제가 해결됩니다. 당신은 샘플 코드에 표시 무엇보다 UI에 표시 할 이상의 구성 요소가있는 경우

JLabel alignments

this.setLayout(new BorderLayout()); 

this.add(creatorLabel, BorderLayout.NORTH); 
this.add(scrollPane); 
this.add(editorLabel, BorderLayout.SOUTH); 

은 또는, 당신은 여전히 ​​ GridBagLayout를 사용할 수 있습니다. 나는 많은 사람들이 이것을 사용하는 것을 좋아하지 않는다는 것을 알고있다. 왜냐하면 매우 장황하기는하지만 제 의견으로는 가장 강력한 스윙 레이아웃 관리자이다.

관련 문제