티스토리 뷰
처음 실행 모습.
Change Panel 버튼을 클릭하면 다음 패널로 변경된다.
메인 프레임의 레이아웃을 CardLayout으로 설정한 후 두개의 패널을 생성하여 각각 Card로 등록한뒤 버튼을 클릭하면 서로 전환 되도록 구성.
메인 프레임
public class Frame extends JFrame{ private CardLayout cards = new CardLayout(); public Frame() { setSize(330, 100); getContentPane().setLayout(cards); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); getContentPane().add("One", new P_One(this)); getContentPane().add("Two", new P_Two(this)); setVisible(true); } public void changePanel() { cards.next(this.getContentPane()); } } |
첫번째 패널
public class P_One extends JPanel { private JLabel lblNewLabel; private JButton btnNewButton; private Frame F; public P_One(Frame f) { setBackground(Color.LIGHT_GRAY); setSize(330, 80); setLayout(null); F = f; lblNewLabel = new JLabel("Panel One"); lblNewLabel.setBounds(12, 10, 59, 15); add(lblNewLabel); btnNewButton = new JButton("Change Panel"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { F.changePanel(); } }); btnNewButton.setBounds(12, 35, 113, 23); add(btnNewButton); setVisible(true); } } |
두번째 패널
public class P_Two extends JPanel { private JLabel lblNewLabel; private JButton btnNewButton; private Frame F; public P_Two(Frame f) { setBackground(Color.GRAY); setSize(330, 80); setLayout(null); F = f; lblNewLabel = new JLabel("Panel Two"); lblNewLabel.setBounds(12, 10, 61, 15); add(lblNewLabel); btnNewButton = new JButton("Change Panel"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { F.changePanel(); } }); btnNewButton.setBounds(12, 35, 113, 23); add(btnNewButton); setVisible(true); } } |
둘 이상의 패널을 각 Card로 등록한 뒤 원하는 패널을 부르는 방법
cards.show(Container parent, String name); - parent : CardLayout이 있는 컨테이너. 여기선 메인프레임의 Pane -> F.getContentPane() - name : CardLayout에 패널 등록시 지정한 String 값. 여기선 One, Two 패널1과 패널2의 Button Action에 - F.getCardLayout().show(F.getContentPane(), "One"); - F.getCardLayout().show(F.getContentPane(), "Two"); getCardLayout()는 구현되 있지 않다. 구현시 메인 프레임에 public CardLayout getCardLayout() { return cards; } |
댓글