2011-08-14 7 views
5

나는 다음과 같은 코드를 가지고 :변경 패널 크기는 클릭

package in.res.num.tapb.ui; 

import java.awt.BorderLayout; 
import java.awt.CardLayout; 
import java.awt.Dimension; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.BorderFactory; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

class MainClass extends JPanel { 
    public MainClass() { 
     Registration registration = new Registration(); 
     ButtonPanel buttonPanel = new ButtonPanel(); 
     buttonPanel.setRegistration(registration); 

     buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel")); 
     registration.setBorder(BorderFactory.createTitledBorder("Registration Panel")); 

     setLayout(new BorderLayout()); 
     add(registration, BorderLayout.CENTER); 
     add(buttonPanel, BorderLayout.SOUTH); 
    } 

    private static void createAndShowUI() { 
     JFrame frame = new JFrame("Registration"); 
     frame.getContentPane().add(new MainClass()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setResizable(false); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowUI(); 
      } 
     }); 
    } 

    @SuppressWarnings("serial") 
    private class ButtonPanel extends JPanel { 
     private Registration registration; 

     public ButtonPanel() { 
      setLayout(new GridLayout(1, 0, 10, 0));  
      for (final String keyText : Registration.KEY_TEXTS) { 
       JButton btn = new JButton(keyText); 
       btn.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) { 
         if (registration != null) { 
          registration.swapView(keyText); 
         } 
        } 
       }); 
       add(btn); 
      } 
     } 

     public void setRegistration(Registration registration) { 
      this.registration = registration; 
     } 
    } 

    private static class Registration extends JPanel { 
     private static final Dimension PREF_SIZE = new Dimension(450, 300); 
     public static final String USER_AGREEMENT = "User Agreement"; 
     public static final String USER_INFO = "User Information"; 
     public static final String ENROLLMENT = "Enrollment"; 
     public static final String[] KEY_TEXTS = { USER_AGREEMENT, USER_INFO, ENROLLMENT }; 
     private CardLayout cardlayout = new CardLayout(); 
     private JPanel cards = new JPanel(cardlayout); 

     public Registration() { 
      cards.add(createUserAgreePanel(), USER_AGREEMENT); 
      cards.add(createUserInfoPanel(), USER_INFO); 
      cards.add(createEnrollmentPanel(), ENROLLMENT); 
      setLayout(new BorderLayout()); 
      add(cards, BorderLayout.CENTER); 
     } 



     private JPanel createEnrollmentPanel() { 
      JPanel enrol = new JPanel(); 
      enrol.setSize(new Dimension(400, 200)); 
      enrol.add(new JLabel("Enrollment")); 
      return enrol; 
     } 

     private JPanel createUserAgreePanel() { 
      JPanel userAgree = new JPanel(); 
      userAgree.setSize(new Dimension(200, 300)); 
      userAgree.add(new JLabel("User Agreement")); 
      return userAgree; 
     } 

     private JPanel createUserInfoPanel() { 
      JPanel userInfo = new JPanel(); 
      userInfo.setSize(new Dimension(300, 400)); 
      userInfo.add(new JLabel("User Information")); 
      return userInfo; 
     } 

     public void swapView(String key) { 
      cardlayout.show(cards, key); 
     } 

    } 

} 

당신은 내가 버튼 클릭에 크기를 변경할 볼 수 있듯이. 가능한가? 위의 코드가 작동하지 않습니다. 크기가 변하지 않았 음을 의미합니다. 비행 중에 크기를 어떻게 바꿀 수 있습니까?

감사합니다. 편집 :

JList 행을 선택할 때 패널을 바꿉니다. JFrame에, 사용 후를 리사이징

public void changeView(int index) { 
    removeAll(); 
    getPanels().get(index).setPreferredSize(Constants.PanelInfo.valueOf(getEngine().getChoiceList().get(index).getEnumName()).getDimensionForViewPanel()); 
    add(getPanels().get(index)); 
} 
+2

이 도움이 될 수있다 http://stackoverflow.com/questions/3889498/how-can-i-increase-decrease-size-of-window-on-click-event – Shadow

+0

+1 감사합니다 ... –

+0

+1 [sscce] (http://sscce.org/). – trashgod

답변

3

레이아웃 관리자를 사용할 때는 setSize()를 사용하지 마십시오. 크기를 결정하는 것은 레이아웃 관리자의 임무입니다. 추천 된 또는 최소 또는 최대 크기를 설정하여 레이아웃 관리자에 대한 힌트를 제공 할 수 있습니다. 그러나 구성 요소와 패널은 사용중인 레이아웃 관리자에 의해 결정되는 기본 크기로 표시되어야하므로이 작업을 수행하지 않는 것이 좋습니다. 당신이 크기를 재정의 한 경우 코드를해야 다음 CardLayout의 작업이 패널에 추가 모든 패널의 최대 크기를 결정하기 때문에

// enrol.setSize(new Dimension(400, 200)); 
enrol.setPreferredSize(new Dimension(400, 200)); 

그러나, 이것은 아직도 당신이 원하는 방식으로 작동하지 않습니다 CardLayout를 사용하여. 따라서 패널에서 패널로 바꿀 때 각 패널의 크기는 알 수 없습니다. 사용자가 버튼을 누를 때마다 프레임 크기가 계속 변경되는 것을보고 싶지 않기 때문에 이것은 사용자에게 더 좋은 경험입니다. 당신이 프레임 크기 변경 당신이 버튼을 클릭 할 때마다하고 싶지 않은 경우

후 기본 코드는 다음과 같습니다

mainPanel.remove(oldPanel); 
mainPanel.add(newPanel); 
frame.pack(); 

그런 다음 메인 패널의 레이아웃 매니저가의 추천 사이즈를 준수합니다 newlay 패널 추가.

4

:

getChoicesList().addListSelectionListener(new ListSelectionListener() { 

     @Override 
     public void valueChanged(ListSelectionEvent listSelectionEvent) { 
      getViewPanel().changeView(getChoicesList().getSelectedIndex()); 
      getChoicePanel().changeView(Constants.PanelInfo.valueOf(getEngine().getChoiceList().get(getChoicesList().getSelectedIndex()).getEnumName()).getDimensionForScrollPaneOfChoicePanel()); 
      ((MainFrame) getTopLevelAncestor()).pack(); 
     } 
    }); 

ViewPanel # changeView()는,이 패널을 스왑 yourframe.validate을();

+1

프레임 크기를 조정하면 프레임 유효성이 검사됩니다. – camickr

3

캠틱의 answer의 구체적인 예로서, 아래 프로그램은 pack()을 통해 프레임의 크기를 조정할 때 원하는 구성 요소 크기에 의존하는 방법을 보여줍니다. 가짜 콘텐츠는 일련의 라벨이지만, JComponent이면됩니다. 콘텐츠가 동적으로 재생성되면 프로그램의 다른 조건에 따라 콘텐츠가 변경 될 수 있습니다.

enter image description here

import java.awt.BorderLayout; 
import java.awt.EventQueue; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.BorderFactory; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

/** @see https://stackoverflow.com/questions/7059278 */ 
class MainPanel extends JPanel { 

    private static final String title = "Registration Panel"; 
    private JFrame frame = new JFrame(title); 
    private JPanel registration = new JPanel(); 

    public MainPanel() { 
     this.setLayout(new BorderLayout()); 
     registration.setBorder(BorderFactory.createTitledBorder(title)); 
     registration.add(PanelType.USER_AGREEMENT.panel); 
     ButtonPanel buttonPanel = new ButtonPanel(); 
     buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel")); 
     add(registration, BorderLayout.CENTER); 
     add(buttonPanel, BorderLayout.SOUTH); 
    } 

    private void display() { 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(new MainPanel()); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new MainPanel().display(); 
      } 
     }); 
    } 

    private class ButtonPanel extends JPanel { 

     public ButtonPanel() { 
      for (final PanelType panel : PanelType.values()) { 
       final JButton button = panel.button; 
       this.add(button); 
       button.addActionListener(new ActionListener() { 

        @Override 
        public void actionPerformed(ActionEvent e) { 
         registration.removeAll(); 
         registration.add(panel.create()); 
         frame.pack(); 
         frame.setLocationRelativeTo(null); 
        } 
       }); 
      } 
     } 
    } 

    private enum PanelType { 

     USER_AGREEMENT("User Agreement", 2), 
     USER_INFO("User Information", 4), 
     ENROLLMENT("Enrollment Form", 6); 
     private String name; 
     private int count; 
     private JButton button; 
     private JPanel panel; 

     private PanelType(String name, int count) { 
      this.name = name; 
      this.count= count; 
      this.button = new JButton(name); 
      this.panel = create(); 
     } 

     private JPanel create() { 
      this.panel = new JPanel(new GridLayout(0, 1)); 
      this.panel.add(new JLabel(name)); 
      this.panel.add(new JLabel(" ")); 
      for (int i = 0; i < count; i++) { 
       this.panel.add(new JLabel("Label " + String.valueOf(i + 1))); 
          } 
      return panel; 
     } 
    } 
}