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:

JOptionPane YES NO OPTION

You should actually take the result from the option pane: Otherwise, it remains set to JOptionPane.YES_NO_OPTION. Cleaner would be: Although, I’m not sure what this line is expected to do in the posted code: remove(dialogButton);. For more details and examples check out How to Make Dialogs tutorial.

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:

Resizing image in Java

If you have an java.awt.Image, rezising it doesn’t require any additional libraries. Just do: Ovbiously, replace newWidth and newHeight with the dimensions of the specified image.Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing. There are algorithms that produce a very precise result, however these take a large time to complete.You can use any of the following … Read more

Simple Java 2D graphics: draw a rectangle?

To draw a rectangle in Swing you should: First of all, never draw directly in the JFrame or other top-level window. Instead draw in a JPanel, JComponent or other class that eventually extends from JComponent. You should override the paintComponent(Graphics g) method. You should be sure to call the super method You should draw your rectangle with … Read more