Only one component shows up in JFrame

The content pane of a JFrame has a BorderLayout. If you place a component in a BL with no constraints it ends up in the CENTER. The center can only display one component. For an immediate effect, I suggest: f.add(top, BorderLayout.PAGE_START); f.add(mid); f.add(bot, BorderLayout.PAGE_END); Other points. Take out f.setSize(500, 500); and call pack() immediately before … Read more

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; … Read more

How to add an image to a JPanel?

If you are using JPanels, then are probably working with Swing. Try this: BufferedImage myPicture = ImageIO.read(new File(“path-to-file”)); JLabel picLabel = new JLabel(new ImageIcon(myPicture)); add(picLabel); The image is now a swing component. It becomes subject to layout conditions like any other component.

Java: maintaining aspect ratio of JPanel background image

Well, the quickest and easiest solution is to use Image.getScaledInstance g.drawImage(img.getScaledInstance(newWidth, -1, Image. SCALE_SMOOTH), x, y, this); If your wondering about the negative number, the java docs say: If either width or height is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions. If both width … Read more