日期:2014-05-20  浏览次数:20694 次

求大神指导这个程序怎么调出图片,我是按照书上代码打的
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

//使用CardLayout
public class CardJButton extends JFrame{
private CardLayout cl = new CardLayout();
private Container container = getContentPane();

public CardJButton(){
JButton button;
ActionListener listener = new ActionListener(){
public void actionPerformed(ActionEvent e){
cl.next(container);   //container必须是内容窗格
}
};
setLayout(cl);                // 指定布局管理器
for(int index = 0; index < 12; index++){
button = new JButton(new ImageIcon("images/T.gif" + index));
add(button,Integer.toString(index));
button.addActionListener(listener);
}
}

public static void main(String[] args){
CardJButton frame = new CardJButton();
frame.setTitle("测试 CardLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
坐等大神出现

------解决方案--------------------
没看懂你的具体问题是啥,据我的臆测,你的问题应该是出在引用图片路径那块(如果你的意思是为什么没有成功显示出图片);
这是你的代码for(int index = 0; index < 12; index++){
button = new JButton(new ImageIcon("images/T.gif" + index));
add(button,Integer.toString(index));
button.addActionListener(listener);

我揣测意思是这样的,改动后的代码如下:
for(int index = 0; index < 12; index++){
button = new JButton("index",new ImageIcon("images/T"+index+".jpg"));
add(button,Integer.toString(index));
button.addActionListener(listener);
}
}

你要确保你的图片目录下有文件,且命名规则符合要求。
看我的截图