gpt4 book ai didi

java - 使用 setVisible 方法隐藏和显示图像

转载 作者:行者123 更新时间:2023-12-01 12:06:46 26 4
gpt4 key购买 nike

我编写了一个类,它使用按钮来播放广播到互联网的广播电台。当按下按钮时,我还希望框架中有一系列图像有选择地隐藏和显示。

我试图通过添加图像、设置“setVisible(false);”来做到这一点然后在单击按钮时重写 setVisible 方法。在目前的状态下它是不可行的。有办法做到这一点吗?

我对编写代码还很陌生。

public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
String text = button.getText();

JLabel img = new JLabel(new ImageIcon("resources/1920.png"));
img.setBounds(642, 230, 100, 100); // x, y, width, height
add(img);
img.setVisible(false);

if (text.equals("1920a"))
{
try
{
getMediaPlayer().setURI(mediaPaths[0]);
img.setVisible(true);

}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}

最佳答案

每次按下按钮时,您都会创建一个 JLabel 的新实例并将其添加到屏幕上,但您不会跟踪它们...

// Yet ANOTHER label...which one it is, nobody knows...
JLabel img = new JLabel(new ImageIcon("resources/1920.png"));
img.setBounds(642, 230, 100, 100); // x, y, width, height
add(img);
img.setVisible(false);

如果您一次只想在屏幕上显示一个图像,那么只需更改单个标签的图标标签...

首先声明图片的实例字段...

public class ... {
//...
private JLabel pictureLabel;

将标签添加到屏幕...

public ... { // Public constructor
//...
pictureLabel = new JLabel();
add(pictureLabel);

现在,当您想要更改图片时,只需更改标签的图标属性...

pictureLabel.setIcon(new ImageIcon("resources/1920.png"));

关于java - 使用 setVisible 方法隐藏和显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27536907/

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