我想在面板中添加一张图片以及描述,但是只要我在组合框中选择一年,描述就会出现在列表中,问题在于图片没有显示在面板的下半部分。我猜我的代码有些问题。有人能帮我解决这个问题吗?如何在面板中添加图像?
这是我到目前为止已经试过:
所有的public class Main extends JApplet
{
private String[] description;
private JList list = new JList();
private DefaultListModel defaultListModel = new DefaultListModel();
private JComboBox c = new JComboBox();
private JButton b = new JButton("Ok");
private ImageIcon image;
public void init()
{
try
{
description = new String[22];
description[0] = "1990";
description[1] = "1991";
description[2] = "1992";
description[3] = "1993";
description[4] = "1994";
description[5] = "1995";
description[6] = "1996";
description[7] = "1997";
description[8] = "1998";
description[9] = "1999";
description[10] = "2000";
description[11] = "2001";
description[12] = "2002";
description[13] = "2003";
description[14] = "2004";
description[15] = "2005";
description[16] = "2006";
description[17] = "2007";
description[18] = "2008";
description[19] = "2009";
description[20] = "2010";
description[21] = "2011";
description[22] = "2012";
}
catch (ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
c = new JComboBox(description);
list = new JList(defaultListModel);
list.setBorder(BorderFactory.createLineBorder(Color.black, 1));
b.setText("<html><b><u>Click</click></b></html>");
list.setFont(new Font("Garamond", Font.BOLD, 17));
list.setForeground(Color.BLUE);
JLabel label = new JLabel(image);
JPanel down = new JPanel();
down.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
down.add(label);
JPanel panel = new JPanel();
panel.add(c);
panel.add(b);
Container cp = getContentPane();
cp.add(list, BorderLayout.CENTER);
cp.add(panel, BorderLayout.NORTH);
cp.add(down, BorderLayout.SOUTH);
this.setVisible(true);
b.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent
event)
{
int select;
select = c.getSelectedIndex();
defaultListModel.clear();
if (select == 0)
{
defaultListModel.addElement("the year of 1990");
image = new ImageIcon("chicken.gif");
}
}
});
}
你是如何运行的代码?你在检查Java控制台吗?为什么要编写一个applet而不是一个框架?我大概可以猜出它为什么会失败,但这对你更具启发性。顺便说一句,用''DefaultComboBoxModel''(http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultComboBoxModel.html)替换'String []'并且循环到'addElement() '22次。 – 2012-03-16 11:31:05
在你的'ActionListener'尝试使用'label.setIcon(new ImageIcon(“chicken.gif”))'我不确定创建一个新的图像是否足够。 (如果你这样做的话,标签应该在类中声明不在init()中) – 2012-03-16 11:39:48