我正在尝试通过反复更改JLabel
. 问题是图像的大小不同,当它们大于第一张图像的大小时,它们会被剪裁。
解决此问题的一种方法是设置 PreferredSizeJLabel
以便所有图像都适合 - 但我想必须有一种方法可以动态调整JPanel
包含JLabel
?
在下面的代码中,我也尝试过删除所有JLabel
内容,创建一个新的,然后添加新的,但效果相同。
public class AnimationPanelv2 extends JPanel{
private JButton start = new JButton("Start Animation");
private JLabel img = new JLabel();
private JTextField animSpeed = new JTextField(10);
private JTextField filePrefix = new JTextField(10);
private JTextField noOfImg = new JTextField(10);
private JTextField audioFile = new JTextField(10);
private Timer timer;
private AudioClip clip;
private ArrayList<ImageIcon> icon = new ArrayList<>();
private int step=0;
public AnimationPanelv2() {
//button is for starting the animation
start.addActionListener(new Animatie());
this.setLayout(new BorderLayout());
add(start, BorderLayout.NORTH);
//showing the label with the first frame
Class metaObj = this.getClass();
URL url = metaObj.getResource("/image/L1.gif");
img.setIcon(new ImageIcon(url));
// img.setPreferredSize(new Dimension(500,550));
add(img, BorderLayout.CENTER);
//control panel
JPanel controls = new JPanel(new GridLayout(4,2));
controls.setBorder(new TitledBorder("Enter information for animation"));
controls.add(new JLabel("Animation speed in ms"));
controls.add(animSpeed);
controls.add(new JLabel("Image file prefix"));
controls.add(filePrefix);
controls.add(new JLabel("Number of images"));
controls.add(noOfImg);
controls.add(new JLabel("Audio file"));
controls.add(audioFile);
//
add(controls, BorderLayout.SOUTH);
}
private class TimerAnimation implements ActionListener {
public void actionPerformed(ActionEvent e) {
remove(img);
img = new JLabel(icon.get(step++));
img.setVisible(true);
add(img, BorderLayout.CENTER);
// img.revalidate();
// img.repaint();
validate();
repaint();
updateUI();
if (step==Integer.parseInt(noOfImg.getText())) step=0;
}
}
private class Animatie implements ActionListener {
public void actionPerformed(ActionEvent e) {
//getting data from the text fields
int ms = Integer.parseInt(animSpeed.getText());
String s = filePrefix.getText();
int nr = Integer.parseInt(noOfImg.getText());
String audioFilePath = audioFile.getText();
// clip
Class metaObj = this.getClass();
URL url = metaObj.getResource("/audio/"+audioFilePath);
clip = Applet.newAudioClip(url);
//image loading
for (int i=1; i<=nr; i++){
url = metaObj.getResource("/image/"+s+i+".gif");
System.out.println("/image/"+s+i+".gif");
icon.add(new ImageIcon(url));
}
//timer
timer = new Timer(ms, new TimerAnimation());
timer.start();
clip.loop();
}
}
public static void main(String[] args) {
JFrame jf = new JFrame("This class test");
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(new AnimationPanelv2());
jf.pack();
jf.setVisible(true);
}
}
这整个面板将在一个小程序中使用。
这是截图:http ://screencast.com/t/UmqQFZHJVy
应该是帧的图像应该位于 /images/ 子目录中,如果用户输入n作为帧数,输入 F 作为图像前缀,则文件为 F1、F2 等, 到 Fn (GIF)。声音文件应该在 /audio/ 子目录中,整个文件名由用户给出。