To add an image to a GUI in Java using WindowBuilder, you can follow these steps:
JLabel
component onto the design surface.Here's an example of how the resulting code might look like:
import java.awt.EventQueue; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class Main { private JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Main window = new Main(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Main() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel label = new JLabel(""); label.setIcon(new ImageIcon("C:\\Users\\user\\workspace\\project\\image.png")); label.setBounds(10, 11, 414, 239); frame.getContentPane().add(label); } }Source:wwal.wutturi.com
In this example, the JLabel
component is used to display the image, and the setIcon
method is used to set the image file as the label's icon. The label is added to the frame using the add
method of the Container
class.
You can use a similar approach to add an image to any GUI component that supports icons, such as a button, a menu item, or a tab. Just make sure to use the appropriate component and the correct method to set the image.
Keep in mind that you need to specify the path to the image file correctly, either as a relative path or an absolute path. You can use the ".." syntax to navigate to the parent directory, or the "" or "/" characters to separate the directories on Windows or Unix-Liunx.