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 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. frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

Something seems wrong with the layout, JButton showing unexpected behaviour at resize of the window

The problem with your very nice example may be platform dependent, but I can offer a few observations: You’re not adding or removing components, so you don’t need revalidate(). Because the background color is a bound property of the buttons, you don’t need the subsequent calls to repaint(). You do need repaint() in your custom … Read more

Swing: Obtain Image of JFrame

ComponentImageCapture.java import java.awt.BorderLayout; import java.awt.Component; import java.awt.Image; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.InputEvent; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.imageio.ImageIO; import java.io.File; /** Create a screenshot of a component. @author Andrew Thompson */ class ComponentImageCapture { static final String HELP = “Type Ctrl-0 to get a screenshot of the current … Read more

Explain the code to create a textfield using java [closed]

In CreateNewJTextField: this.getContentPane().setLayout(new FlowLayout()); This create a Pane and sets a default layout. Pane is like a piece of paper on which you draw. JTextField field3 = new JTextField(10); add(field3); This creates a text field and adds it to that pane. In createAndShowGUI, you are adding this pane to a JFrame(the frame with minimize, close … Read more