我一直试图在彼此之间显示一些jpanel,每个jpanel之间有不同的时间。我使用swing timer,thread.sleep和int ++计数器来尝试在每个jpanel的显示之间创建间距,每个都没有成功。
在上一篇文章中,我被告知计时器将是最好的选择。我尝试过很多不同的教程,根本没有运气,我真的不明白它的实现。
我启动整个过程的按钮使用了mouseListener,而我读过的所有教程都引用了使用ActionListeners,这让我更加困惑。
我是否可以要求有人启发我如何实现这一过程。
我的评论部分会编码什么?
if (a.getSource() == button){
panel1.setVisible(true);
ActionListener listener = new ActionListener(){
public void actiinPerformed(ActionEvent event){
panel1.setVisible(false);
panel2.setVisible(true);
}
};
Timer timer = new Timer(4000, listener);
timer.start();
// This is one method I tried, and even ifit had worked I wouldnt know where to begin timing the following panels.Would I create a new timer for each part of the panel exchange?
// panel1.setVisible(false);
// panel2.setVisible(true);
// panel2.setVisible(false);
// panel3.setVisible(true);
// panel3.setVisible(false);
// menu.setVisible(true);
}
先谢谢你们。
答案 0 :(得分:2)
一旦我看到改进后的问题和代码,再次提供一些更具体的建议:
next(...)
一样简单。show(...)
方法,传入适合你想要显示的JPanel的常量。那个时候。例如,
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
@SuppressWarnings("serial")
public class PanelSwap extends JPanel {
private static final int CARD_COUNT = 5;
private static final String CARD = "card";
private static final int TIMER_DELAY = 1000;
private CardLayout cardlayout = new CardLayout();
private Random random = new Random();
public PanelSwap() {
setLayout(cardlayout);
for (int i = 0; i < CARD_COUNT; i++) {
add(createCardPanel(i), CARD + i);
}
new Timer(TIMER_DELAY, new TimerListener()).start();;
}
private JPanel createCardPanel(int i) {
JPanel cardPanel = new JPanel(new GridBagLayout());
String name = "Card Number " + i;
JLabel label = new JLabel(name);
cardPanel.add(label, SwingConstants.CENTER);
cardPanel.setName(name);
Dimension preferredSize = new Dimension(300, 200);
cardPanel.setPreferredSize(preferredSize);
// just to give the JPanels different background colors
int[] rgb = new int[3];
for (int j = 0; j < rgb.length; j++) {
rgb[j] = random.nextInt(256);
}
Color background = new Color(rgb[0], rgb[1], rgb[2]);
Color foreground = new Color(256 - rgb[0], 256 - rgb[1], 256 - rgb[2]);
cardPanel.setBackground(background);
label.setForeground(foreground);
return cardPanel;
}
class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
cardlayout.next(PanelSwap.this);
}
}
private static void createAndShowGui() {
PanelSwap mainPanel = new PanelSwap();
JFrame frame = new JFrame("PanelSwap");
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();
}
});
}
}