Java에서 일련의 이미지에 애니메이션을 적용하고 있습니다. 지금까지 아무 문제없이 움직일 수있었습니다. 이 문제는 컨트롤 (시작, 중지 등)에 추가 할 때만 발생합니다. 내 GUI에서 시작을 누르면 GUI가 애니메이션을 표시하지 않고 애니메이션이 끝난 후 마지막 프레임 만 표시됩니다.일련의 이미지에 애니메이션 적용
몇 가지 방법을 시도했지만 그 중 아무 것도 작동하지 않아서 스레딩 문제 또는 페인팅 문제인지 확실하지 않습니다.
public class SwingAnimation extends JPanel implements ActionListener {
protected JFrame frame;
protected JLabel lblDisplay;
protected JButton BtnStart, BtnStop, BtnPause;
protected JCheckBox chkLoop;
protected Thread th;
public static void main(String[] args) {
SwingAnimation sa = new SwingAnimation();
}
public SwingAnimation() {
frame = new JFrame("Animation");
Panel panel = new Panel();
lblDisplay = new JLabel();
BtnStart = new JButton("Start");
BtnStop = new JButton("Stop");
BtnPause = new JButton("Pause");
chkLoop = new JCheckBox("Loop");
BtnStop.setEnabled(false);
BtnPause.setEnabled(false);
BtnStart.setActionCommand("start");
BtnStop.setActionCommand("stop");
BtnPause.setActionCommand("pause");
panel.add(lblDisplay);
panel.add(BtnStart);
panel.add(BtnPause);
panel.add(BtnStop);
panel.add(chkLoop);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set the frame in the center of the screen
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
int screen_x = (screensize.width - frame.getWidth())/2;
int screen_y = (screensize.height - frame.getHeight())/2;
frame.setLocation(screen_x, screen_y);
BtnStart.addActionListener(this);
BtnStop.addActionListener(this);
BtnPause.addActionListener(this);
chkLoop.addActionListener(this);
th = new Thread();
//ImageAnimator();
}
public void ImageAnimator() {
try {
for (int i = 0; i <= 299; i++) {
ImageIcon images = new ImageIcon("C:\\Users\\Desktop\\Images\\Snap" + i + ".jpg");
lblDisplay.setIcon(images);
th.sleep(25);
}
} catch (InterruptedException e) {
}
}
public void actionPerformed(ActionEvent e) {
if ("start".equals(e.getActionCommand())) {
BtnStart.setEnabled(false);
BtnStop.setEnabled(true);
BtnPause.setEnabled(true);
lblDisplay.setVisible(true);
ImageAnimator();
} else if ("stop".equals(e.getActionCommand())) {
BtnStart.setText("Start");
BtnStart.setEnabled(true);
BtnStop.setEnabled(false);
BtnPause.setEnabled(false);
lblDisplay.setVisible(false);
th = null;
} else if ("pause".equals(e.getActionCommand())) {
BtnStart.setText("Resume");
BtnStart.setEnabled(true);
BtnStop.setEnabled(true);
BtnPause.setEnabled(false);
}
}
}
문제가 아니지만 'th'에 저장된 스레드를 만들 필요가 없습니다. 'sleep' 메서드는 정적이며'Thread.sleep (25)'로 호출되어야합니다. –