Setting background images in JFrame

There is no built-in method, but there are several ways to do it. The most straightforward way that I can think of at the moment is: Create a subclass of JComponent. Override the paintComponent(Graphics g) method to paint the image that you want to display. Set the content pane of the JFrame to be this subclass. Some sample code: Note that … Read more

Adding image to JFrame

There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options: As @Reimeus said: Use a JLabel with an icon. Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel … Read more

How to programmatically close a JFrame

If you want the GUI to behave as if you clicked the X close button then you need to dispatch a window closing event to the Window. The ExitAction from Closing An Application allows you to add this functionality to a menu item or any component that uses Actions easily.

Java GUI: about getContentPane( ) method and content

Every JPanel is a container, so either add it to a panel then add it to the container or directly use add(component) or use the getContentPane().add method. Both add the component to the container in Java 7 (I don’t know if version 6 has a problem with this or not).

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 do I draw a triangle?

You may use Graphics.drawPolygon(int[], int[], int) where the first int[] is the set of x values, the second int[] is the set of y values, and the int is the length of the array. (In a triangle’s case, the int is going to be 3) Example: Output:

How do I draw a triangle?

You may use Graphics.drawPolygon(int[], int[], int) where the first int[] is the set of x values, the second int[] is the set of y values, and the int is the length of the array. (In a triangle’s case, the int is going to be 3) Example: Output: