- Simpy使用CardLayout来交换视图。
- 请使用Swing计时器,而不要使用当前的后台线程,因为您当前的代码对Swing线程而言并不安全,并且存在发生危险的不可预测的线程异常的风险。
- 我会给主JPanel CardLayout,然后添加一个JLabel来保存带有合适的String常量的JPanel。
- 然后,我将使用JPanel添加到主CardLayout中,将一个空的JLabel添加到add方法中的另一个String常量中。即
add(new JLabel(), BLANK_COMPONENT);
- 然后,在Swing Timer中,只需调用
next()
CardLayout对象,传入使用CardLayout的主要组件:cardLayout.next(myMainJPanel);
例如,
import java.awt.CardLayout;import java.awt.Dimension;import java.awt.event.*;import javax.swing.*;public class RepaintTest extends JPanel { private static final int PREF_W = 400; private static final int PREF_H = PREF_W; private static final int LABEL_COUNT = 3; private static final String LABEL_PANEL = "label panel"; private static final Object BLANK_COMPonENT = "blank component"; private static final int TIMER_DELAY = 2000; private CardLayout cardLayout = new CardLayout(); public RepaintTest() { JPanel labelPanel = new JPanel(); for (int i = 0; i < LABEL_COUNT; i++) { labelPanel.add(new JLabel("Label " + (i + 1))); } setLayout(cardLayout); add(labelPanel, LABEL_PANEL); add(new JLabel(), BLANK_COMPONENT); new Timer(TIMER_DELAY, new TimerListener()).start(); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } private class TimerListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { cardLayout.next(RepaintTest.this); } } private static void createAndShowGui() { RepaintTest mainPanel = new RepaintTest(); Jframe frame = new Jframe("RepaintTest"); frame.setDefaultCloseOperation(Jframe.DISPOSE_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); }}


