【发布时间】:2012-04-01 22:28:59
【问题描述】:
我想在面板中添加图像和描述,但每当我在组合框中选择年份时,描述只会出现在列表中,问题是图像没有显示在面板的下部.我猜我的代码有问题。有人可以帮我解决这个问题吗?
这是我迄今为止尝试过的:
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 控制台吗?为什么要编写小程序而不是框架?我可能会猜到它失败的原因,但这对你更有指导意义。顺便说一句 - 用
DefaultComboBoxModel替换String[]并循环到addElement()22 次。 -
在您的
ActionListener中尝试使用label.setIcon(new ImageIcon("chicken.gif"))我不确定创建一个新图像是否足够。 (如果你这样做,标签应该在类中声明,而不是在 init() 中)