import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyFrame extends JFrame { private JButton myButton; public MyFrame() { // Create a button myButton = new JButton("Click me!"); // Set an icon for the button ImageIcon icon = new ImageIcon(getClass().getResource("my-icon.png")); myButton.setIcon(icon); // Add the button to the frame add(myButton); // Set some frame properties setTitle("My Frame"); setSize(400, 300); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new MyFrame().setVisible(true); } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyFrame extends JFrame implements ActionListener { private JButton myButton; public MyFrame() { // Create a button myButton = new JButton("Click me!"); // Register a listener for the button myButton.addActionListener(this); // Add the button to the frame add(myButton); // Set some frame properties setTitle("My Frame"); setSize(400, 300); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { if(e.getSource() == myButton) { // Set a new icon for the button myButton.setIcon(new ImageIcon(getClass().getResource("my-new-icon.png"))); } } public static void main(String[] args) { new MyFrame().setVisible(true); } }This example sets an initial icon for a button in a JFrame, and then changes the icon when the button is clicked. The new image file is located in the same directory as the code and is named "my-new-icon.png". The package library used is javax.swing.