java添加JMenuItem,点击改变图片
时间: 2023-08-22 22:08:36 浏览: 125
你可以使用JMenuItem的addActionListener()方法来添加一个监听器,当用户点击菜单项时,监听器会被调用。在监听器中,你可以使用JLabel的setIcon()方法来改变图片。
以下是一个简单的示例代码,实现了这个功能:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChangeImageMenuItem extends JFrame {
private JLabel label;
private ImageIcon image1, image2;
public ChangeImageMenuItem() {
super("Change Image on MenuItem Click");
image1 = new ImageIcon("image1.jpg");
image2 = new ImageIcon("image2.jpg");
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem menuItem = new JMenuItem("Change Image");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (label.getIcon() == image1) {
label.setIcon(image2);
} else {
label.setIcon(image1);
}
}
});
menu.add(menuItem);
menuBar.add(menu);
setJMenuBar(menuBar);
label = new JLabel(image1);
getContentPane().add(label, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args) {
new ChangeImageMenuItem();
}
}
```
在这个示例中,我们创建了一个JFrame窗口,并在其中添加了一个JLabel,用于显示图片。然后,我们创建了一个JMenuBar,并在其中添加了一个JMenu和一个JMenuItem。我们使用JMenuItem的addActionListener()方法来添加一个监听器,当用户点击菜单项时,监听器会被调用。在监听器中,我们使用JLabel的setIcon()方法来改变图片。最后,我们将JLabel添加到窗口中,并设置窗口的大小和可见性。
阅读全文
相关推荐
















