gpt4 book ai didi

java - 如何在面板中添加图像?

转载 作者:行者123 更新时间:2023-11-30 05:54:02 24 4
gpt4 key购买 nike

我想在面板中添加一张图片和描述,但每当我在组合框中选择年份时,描述只出现在列表中,问题是图片没有显示在面板的下部.我猜我的代码有问题。有人可以帮我解决这个问题吗?

这是我到目前为止尝试过的:

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");
}
}
});
}

最佳答案

首先,你在init()方法的开头有错误,这与你的实际问题无关。你有一个包含 22 个字符串的数组,你正试图为第 23 个索引赋值,这是错误的,除非你放弃它,否则你会得到一个错误。

对于您的实际问题,更改图像的值不会更改/更新标签。在 actionPerformed() 方法中尝试下面的代码片段,但是您需要将标签设置为最终变量或全局变量。

if (select == 0)
{
try
{
label.setIcon(new ImageIcon(ImageIO.read(new File("chicken.gif"))));
} catch (IOException e) {
e.printStackTrace();
}
}

关于java - 如何在面板中添加图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9736261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com