JButton需要显示图像阵列
问题描述:
我有一组图像存储在一个数组中,我需要像幻灯片一样显示它们。有两个JButton可以让用户看到图像。但是我无法使按钮工作。任何建议?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];
}
}
}
答
什么建议吗?
没有必要重写
paintComponent()
;相反,在现有的JLabel
上使用setIcon()
。一个完整的例子被引用为here。请勿使用
setBounds()
;相反,pack()
封闭Window
让组件采用他们的首选大小。
什么是完全相同的问题,也就是你所说的“不能让这些按钮的工作”是什么意思?你能向我们展示一个[MCVE](http://stackoverflow.com/help/mcve)吗? – BluesSolo 2014-12-04 11:02:07
paintIcon意思是你必须重写paintIcon,那么paintComponent就没用了 – mKorbel 2014-12-04 11:04:53
从paintComponent里面的代码中删除一切(可以每秒执行几次)其余的是在Oracle教程 – mKorbel 2014-12-04 11:06:09