Java: Difference between the setPreferredSize() and setSize() methods in components

Usage depends on whether the component’s parent has a layout manager or not. setSize() — use when a parent layout manager does not exist; setPreferredSize() (also its related setMinimumSize and setMaximumSize) — use when a parent layout manager exists. The setSize() method probably won’t do anything if the component’s parent is using a layout manager; the places this will typically have an … Read more

How to add an image to a JPanel?

Here’s how I do it (with a little more info on how to load an image): import java.awt.Graphics; import java.awt.image.BufferedImage; import; import; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JPanel; public class ImagePanel extends JPanel{ private BufferedImage image; public ImagePanel() { try { image = File(“image name and path”)); } catch (IOException … Read more

addMouseListener for a JPanel

JPanel doesn’t have ActionListener capabilities. Instead, you need to use a MouseListener import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JPanel; public class CoordBoutons extends JFrame { CoordBoutons() { super(“GridLayout”); setDefaultCloseOperation(EXIT_ON_CLOSE); Container contenant = getContentPane(); contenant.setLayout(new GridLayout(8, 8)); for (int i = 0; i < 8; i++) { for (int … Read more