我正在尝试使用Java Swing
制作幻灯片。
我开始实现课程PicturePanel
public class PicturePanel extends JPanel {
private int counter = 0;
private ImageIcon[] images = new ImageIcon[10];
private JLabel label;
public PicturePanel()
{
for(int i = 0 ; i <images.length;i++)
{
images[counter] = new ImageIcon("check.png");
label = new JLabel();
add(label);
Timer timer = new Timer(100, new TimerListener());
}
}
private class TimerListener implements ActionListener {
public TimerListener() {
}
@Override
public void actionPerformed(ActionEvent ae) {
counter++;
//counter% =images.length;
label.setIcon(images[counter]);
}
}
}
然后我通过以下代码在Jframe
中调用此类:
panProfil= new PicturePanel();
panProfil
在我的表单中是Jpanel
当我运行我的项目时,我没有收到任何错误,但我的表格中没有任何内容。有人能指出我正确的方向吗?
答案 0 :(得分:1)
所以你还没有开始你的问题Timer
(正如@ItachiUchiha指出的那样)。但你需要做的另一件事是知道何时stop()
Timer
或者它会继续运行
您希望在创建start()
后在构造函数中Timer
。在你ActionListener
中,为了阻止它,你会想要做这样的事情。
private class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
if (counter == images.length) {
((Timer)e.getSource()).stop();
} else {
label.setIcon(images[counter]);
counter++;
}
}
}
如果您想从主GUI类访问Timer
,那么您可以控制它,您希望拥有getter
,并全局声明
public class PicturePanel extends JPanel {
private Timer timer = null;
public PicturePanel() {
timer = new Timer(1000, new TimerListener());
}
public Timer getTimer() {
return timer;
}
}
然后你可以从主GUI类开始和停止它
DrawPanel panel = new DrawPanel();
Timer timer = panel.getTimer();
此外,我没有看到每次迭代创建JLabel
并将其添加到JPanel
的重点。你只需要一个。
答案 1 :(得分:0)
public class Project2 {
int c=0;
public static void main(String arg[]) throws InterruptedException {
JFrame login = new JFrame("Login");
// creating a new frame
login.setSize(700, 500);
JPanel addPanel = new JPanel();
JLabel pic = new JLabel();
Project2 p2= new Project2();
String[] list = {"C:\\Users\\divyatapadia\\Desktop\\pic1.jpg", "C:\\Users\\divyatapadia\\Desktop\\benefit.PNG" , "C:\\Users\\divyatapadia\\Desktop\\pic2.jpg"};
pic.setBounds(40, 30, 500, 300);
JButton log = new JButton("SHOW");ImageIcon[] img = new ImageIcon[3];
for(int time = 0;time<3;time++) {
img[time]= new ImageIcon(list[time]);
}
addPanel.add(pic);
addPanel.add(log);
login.add(addPanel);
login.setVisible(true);
try {
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Timer t ;
t= new Timer(1000,new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(p2.c<3) {
pic.setIcon(img[p2.c]);
p2.c++;
}}
});
t.start();
}
}
);
}catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}