2010-06-15 3 views
3

상자에 포함 된 버튼을 왼쪽으로 정렬하려고 시도했지만 성공하지 못했습니다.Java Box Class : Unsolvable : 컴포넌트를 왼쪽 또는 오른쪽으로 정렬

왼쪽 정렬은 괜찮지 만, 어떤 이유로 든 상상할 수있는대로 왼쪽으로 이동하지 않습니다.

아래 코드를 첨부합니다. 컴파일하고 직접보십시오. 나에게 기괴한 것 같다.

감사합니다, 에릭

import java.awt.Dimension; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import javax.swing.Box; 
import javax.swing.BoxLayout; 
import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JMenu; 
import javax.swing.JMenuBar; 
import javax.swing.JMenuItem; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 

public class MainGUI extends Box implements ActionListener{ 
    //Create GUI Components 
    Box centerGUI=new Box(BoxLayout.X_AXIS); 
    Box bottomGUI=new Box(BoxLayout.X_AXIS); 
    //centerGUI subcomponents 
    JTextArea left=new JTextArea(), right=new JTextArea(); 
    JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right); 
    //bottomGUI subcomponents 
    JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info"); 
    //Create Menubar components 
    JMenuBar menubar=new JMenuBar(); 
    JMenu fileMenu=new JMenu("File"); 
    JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit"); 
    int returnVal =0; 

    public MainGUI(){ 
     super(BoxLayout.Y_AXIS); 
     initCenterGUI(); 
     initBottomGUI(); 
     initFileMenu(); 
     add(centerGUI); 
     add(bottomGUI); 
     addActionListeners(); 
    } 
    private void addActionListeners() { 
     open.addActionListener(this); 
     save.addActionListener(this); 
     exit.addActionListener(this); 
     encrypt.addActionListener(this); 
     decrypt.addActionListener(this); 
     close.addActionListener(this); 
     info.addActionListener(this); 
    } 
    private void initFileMenu() { 
     fileMenu.add(open); 
     fileMenu.add(save); 
     fileMenu.add(exit); 
     menubar.add(fileMenu); 
    } 
    public void initCenterGUI(){ 
     centerGUI.add(leftScrollPane); 
     centerGUI.add(rightScrollPane); 
    } 
    public void initBottomGUI(){ 
     bottomGUI.setAlignmentX(LEFT_ALIGNMENT); 
     //setBorder(BorderFactory.createLineBorder(Color.BLACK)); 
     bottomGUI.add(encrypt); 
     bottomGUI.add(decrypt); 
     bottomGUI.add(close); 
     bottomGUI.add(info); 
    } 
    @Override 
    public void actionPerformed(ActionEvent arg0) { 
     // find source of the action 
     Object source=arg0.getSource(); 
     //if action is of such a type do the corresponding action 
     if(source==close){ 
      kill(); 
     } 
     else if(source==open){ 
      //CHOOSE FILE 
      File file1 =chooseFile(); 
      String input1=readToString(file1); 
      System.out.println(input1); 
      left.setText(input1); 
     } 
     else if(source==decrypt){ 
      //decrypt everything in Right Panel and output in left panel 
      decrypt(); 
     } 
     else if(source==encrypt){ 
      //encrypt everything in left panel and output in right panel 
      encrypt(); 
     } 
     else if(source==info){ 
      //show contents of info file in right panel 
      doInfo(); 
     } 
     else { 
      System.out.println("Error"); 
      //throw new UnimplementedActionException(); 
     } 
    } 

    private void doInfo() { 
     // TODO Auto-generated method stub 
    } 
    private void encrypt() { 
     // TODO Auto-generated method stub 
    } 
    private void decrypt() { 
     // TODO Auto-generated method stub 
    } 
    private String readToString(File file) { 
     FileReader fr = null; 
     try { 
      fr = new FileReader(file); 
     } catch (FileNotFoundException e1) { 
      e1.printStackTrace(); 
     } 
     BufferedReader br=new BufferedReader(fr); 

     String line = null; 
     try { 
      line = br.readLine(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     String input=""; 
     while(line!=null){ 
      input=input+"\n"+line; 
      try { 
       line=br.readLine(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return input; 
    } 
    private File chooseFile() { 
     //Create a file chooser 
    final JFileChooser fc = new JFileChooser(); 
    returnVal = fc.showOpenDialog(fc); 
     return fc.getSelectedFile(); 
    } 
    private void kill() { 
     System.exit(0); 
    } 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     MainGUI test=new MainGUI(); 
     JFrame f=new JFrame("Tester"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setJMenuBar(test.menubar); 
     f.setPreferredSize(new Dimension(600,400)); 
     //f.setUndecorated(true); 
     f.add(test); 
     f.pack(); 
     f.setVisible(true); 
    } 

}

답변

2

로부터의 섹션을 읽어 (질문을 할 때 당신은 다른 사람들이 더 쉽게 질문에 대답 할 수 있습니다,이 작업을 수행해야합니다) How to Use Box Layout에 대한 스윙 튜토리얼. 구성 요소가 서로 다른 정렬을 가질 때 BoxLayout이 작동하는 방법을 설명합니다 (예제가 있음).

centerGUI.setAlignmentX(LEFT_ALIGNMENT); 
+0

이 방법이 효과적입니다. 비 직관적 인 것 같지만, 텍스트를 읽고 이유를 알게 될 것입니다. – user323186

+1

그동안 누군가가 전체 텍스트를 읽지 못하게하고 그 텍스트를 설명 할 수 있다고 생각한다면 게시물을 추가하십시오. – user323186

0

MiGLayout를 사용해보십시오?

그들은 많은 정렬 예제를 포함하여 소스 코드와 함께 많은 훌륭한 온라인 데모를 가지고 있습니다.

+0

바보의 대답 :

간단한 솔루션을 추가하는 것입니다. 레이아웃 관리자를 변경하기 만하면됩니다. – user323186

+0

MiGLayout *는 레이아웃 관리자입니다 :-) 훌륭한 디버깅 기술을 위해 – mikera

2

버튼이 원래대로 정렬되어 있는지는 잘 모르겠지만 아마 위의 상자와 정렬하려고했기 때문일 것입니다. (스윙에 대해 더 잘 알고있는 사람이 당신에게 더 나은 답변을 줄 수 있다고 확신합니다) . 레이아웃 문제를 디버깅하는 편리한 방법은 색상이있는 테두리로 구성 요소를 강조 표시하는 것입니다. 현재 코드 : 그 요구 사항이 있다면

centerGUI.setBorder(BorderFactory.createLineBorder(Color.GREEN)); 
    add(centerGUI); 
    bottomGUI.setBorder(BorderFactory.createLineBorder(Color.RED)); 
    add(bottomGUI); 

그러나, 나는 BorderLayout를 사용하는 것, 예를 들어, 이 코드는 느슨하게 당신을 기반으로, 내가 레이아웃 부분에 집중하기, 불필요한 비트를 제거

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.event.ActionEvent; 
import javax.swing.AbstractAction; 
import javax.swing.Box; 
import javax.swing.BoxLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JMenu; 
import javax.swing.JMenuBar; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 

public class Tester { 

    private JPanel contentPanel; 
    private JTextArea leftTextArea = new JTextArea(); 
    private JTextArea rightTextArea = new JTextArea(); 
    private JMenuBar menuBar = new JMenuBar(); 

    public Tester() { 
     initialisePanel(); 
     initFileMenu(); 
    } 

    public JPanel getContent() { 
     return contentPanel; 
    } 

    public JMenuBar getMenuBar() { 
     return menuBar; 
    } 

    private final void initialisePanel() { 
     contentPanel = new JPanel(new BorderLayout()); 

     Box centreBox = new Box(BoxLayout.X_AXIS); 
     JScrollPane leftScrollPane = new JScrollPane(leftTextArea); 
     JScrollPane rightScrollPane = new JScrollPane(rightTextArea); 
     centreBox.add(leftScrollPane); 
     centreBox.add(rightScrollPane); 

     Box bottomBox = new Box(BoxLayout.X_AXIS); 
     bottomBox.add(new JButton(new SaveAction())); 
     bottomBox.add(new JButton(new ExitAction())); 
     contentPanel.add(centreBox, BorderLayout.CENTER); 
     contentPanel.add(bottomBox, BorderLayout.SOUTH); 
    } 

    private void initFileMenu() { 
     JMenu fileMenu = new JMenu("File"); 
     fileMenu.add(new SaveAction()); 
     fileMenu.add(new ExitAction()); 
     menuBar.add(fileMenu); 
    } 

    class SaveAction extends AbstractAction { 
     public SaveAction() { 
      super("Save"); 
     } 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      handleSave(); 
     } 
    } 

    void handleSave() { 
     System.out.println("Handle save"); 
    } 

    class ExitAction extends AbstractAction { 
     public ExitAction() { 
      super("Exit"); 
     } 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      handleExit(); 
     } 
    } 

    void handleExit() { 
     System.out.println("Exit selected"); 
     System.exit(0); 
    } 

    public static void main(String[] args) { 
     Tester test = new Tester(); 
     JFrame frame = new JFrame("Tester"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setContentPane(test.getContent()); 
     frame.setJMenuBar(test.getMenuBar()); 
     frame.setPreferredSize(new Dimension(600, 400)); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

} 
+1

+1을 사용하는 것이 옳습니다. –

관련 문제