使用 CardLayout 在 Swing 實現後退/前進按鈕
問題:
問題:答案:
而不是使用堆疊系統,考慮使用 CardLayout。這個佈局管理器可讓您透過簡單的命令在不同的面板之間切換,非常適合建立前進/後退導航系統。
解決方案:
import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.util.Random; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class CardPanel extends JPanel { private static final Random random = new Random(); private static final JPanel cards = new JPanel(new CardLayout()); private final String name; public CardPanel(String name) { this.name = name; this.setPreferredSize(new Dimension(320, 240)); this.setBackground(new Color(random.nextInt())); this.add(new JLabel(name)); } @Override public String toString() { return name; } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { create(); } }); } private static void create() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); for (int i = 1; i < 9; i++) { CardPanel p = new CardPanel("Panel " + String.valueOf(i)); cards.add(p, p.toString()); } JPanel control = new JPanel(); control.add(new JButton(new AbstractAction("\u22b2Prev") { @Override public void actionPerformed(ActionEvent e) { CardLayout cl = (CardLayout) cards.getLayout(); cl.previous(cards); } })); control.add(new JButton(new AbstractAction("Next\u22b3") { @Override public void actionPerformed(ActionEvent e) { CardLayout cl = (CardLayout) cards.getLayout(); cl.next(cards); } })); f.add(cards, BorderLayout.CENTER); f.add(control, BorderLayout.SOUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } }
以下程式碼片段展示瞭如何使用CardLayout 實作前進和後退按鈕:
此增強的解決方案為實現前進/後退按鈕提供了更清晰、更靈活的方法在您的Swing 應用程式中。以上是如何使用 CardLayout 在 Swing GUI 中實現後退和前進按鈕?的詳細內容。更多資訊請關注PHP中文網其他相關文章!