기본 튜토리얼은 여기 How to get the top card in Java's CardLayout
을 게시 링크에서 CardLayout
the best are here 또는
here
에 대해 betweens cards in CardLayout, 예를 많이 전환하는 방법을 통해 VII
이상
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
public class CardlayoutTest extends JFrame {
private static final long serialVersionUID = 1L;
public CardLayout card = new CardLayout();
public CardlayoutTest() {
EventHandler eventHandle = new EventHandler();
JPanel pnlA = new JPanel(new BorderLayout());
pnlA.add(new JButton("A"), BorderLayout.CENTER);
JPanel pnlB = new JPanel(new BorderLayout());
pnlB.add(new JButton("B"), BorderLayout.CENTER);
pnlA.addAncestorListener(eventHandle);
pnlA.addHierarchyListener(eventHandle);
pnlB.addAncestorListener(eventHandle);
pnlB.addHierarchyListener(eventHandle);
setLayout(card);
add(pnlA, "A");
add(pnlB, "B");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class EventHandler implements AncestorListener, HierarchyListener {
@Override
public void ancestorAdded(AncestorEvent event) {
System.out.println("CardlayoutTest.EventHandler.ancestorAdded()");
}
@Override
public void ancestorMoved(AncestorEvent event) {
System.out.println("CardlayoutTest.EventHandler.ancestorMoved()");
}
@Override
public void ancestorRemoved(AncestorEvent event) {
System.out.println("CardlayoutTest.EventHandler.ancestorRemoved()");
}
@Override
public void hierarchyChanged(HierarchyEvent e) {
System.out.println("CardlayoutTest.EventHandler.hierarchyChanged()");
}
}
public static void main(String[] args) {
CardlayoutTest t = new CardlayoutTest();
t.setSize(500, 500);
System.out.println("CardlayoutTest.main()------------------------ FIRST");
t.card.show(t.getContentPane(), "A");
t.setVisible(true);
System.out.print("\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("CardlayoutTest.main()------------------------ SECOND");
t.card.show(t.getContentPane(), "B");
System.out.print("\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("CardlayoutTest.main()------------------------ THIRD");
t.card.show(t.getContentPane(), "B");
System.out.print("\n");
}
}
응답 전에 질문을주의 깊게 읽으십시오 : 특정 카드를 보여주는 방법을 이해합니다. 외부에서 상태를 추적하는 대신 구성 요소 자체를 호출하여 어떤 카드가 표시되는지 확인하는 데 관심이 있습니다. –
구체적으로 좀 상세 해 주실 수 있습니까? 당신이 제공 한 링크를 통해 읽은 후에, 당신이 말하는 것을 찾을 수 없습니까? –
@ 톰, 네가 옳았다. 나는 튜토리얼을 잘못 읽었다 - 내 잘못. 내 편집을 참조하십시오. – mre