我有一组存储在数组中的图像,我需要像幻灯片一样显示它们。下一个和上一个有两个JButton允许用户查看图像。但是我无法让按钮工作。有什么建议吗?
由于
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class slides extends JPanel implements ActionListener {
// Data Field
private final ImageIcon imageArray[];
private ImageIcon image;
JButton nextButton;
JButton prevButton;
int page = 0;
int nextPage = page + 1;
int prevPage = page - 1;
int numOfSlides = 28;
// Obtains and stores slides in imageArray
public slides() {
imageArray = new ImageIcon[numOfSlides];
for (int i = 0; i < imageArray.length; i++) {
imageArray[i] = new ImageIcon("Slide " + (i + 1) + ".png");
}
}
// Displays slides
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
boolean began = true;
// creates next button
nextButton = new JButton("next");
nextButton.setBounds(400, 574, 70, 30);
nextButton.addActionListener(this);
add(nextButton);
// creates previous button
prevButton = new JButton("previous");
prevButton.setBounds(0, 574, 85, 30);
prevButton.addActionListener(this);
add(prevButton);
// displays slide 1
if (began == true) {
image = imageArray[page];
image.paintIcon(this, g, 0, 0);
began = false;
}
// displays other slides based on preference
if (page == nextPage) {
image = imageArray[page + 1];
image.paintIcon(this, g, 0, 0);
nextPage = page + 1;
prevPage = page - 1;
}
if (page == prevPage) {
nextPage = page + 1;
prevPage = page - 1;
image = imageArray[page - 1];
image.paintIcon(this, g, 0, 0);
}
// Removes buttons accordingly
if(page == imageArray.length - 1) {
remove(nextButton);
}
if(page == 0){
remove(prevButton);
}
}
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == nextButton) {
page++;
image = imageArray[page];
}
if (event.getSource() == prevButton) {
page--;
image = imageArray[page];
}
}
}
答案 0 :(得分:4)
有什么建议吗?
无需覆盖paintComponent()
;相反,在现有setIcon()
上使用JLabel
。引用了一个完整的示例here。
不要使用setBounds()
;相反,pack()
封闭的Window
让组件采用其首选尺寸。