jScrollPane can’t add component

You’re mixing heavy weight (AWT) components with light weight (Swing) components, this is inadvisable as they don’t tend to play well together. JScrollPane contains a JViewPort onto which you can add a child component, AKA the view. (image from the JavaDocs) So the call jScrollPane.getViewport().setLayout(new FlowLayout(FlowLayout.CENTER)); is actually setting the JViewPort‘s layout manager, which really … Read more

Java, setting layout to null

Is there a better way? Layout managers, layout managers, layout managers. If the default provided layout managers aren’t doing what you want, either use a combination of layout managers or maybe try some of the freely available layout managers, like MigLayout (and use them in combination with other layout managers as required) With your code… … Read more

Centering a JLabel in a JPanel

Set GridBagLayout for JPanel, put JLabel without any GridBagConstraints to the JPanel, JLabel will be centered example import java.awt.*; import javax.swing.*; public class CenteredJLabel { private JFrame frame = new JFrame(“Test”); private JPanel panel = new JPanel(); private JLabel label = new JLabel(“CenteredJLabel”); public CenteredJLabel() { panel.setLayout(new GridBagLayout()); panel.add(label); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(panel); … Read more

Why null layouts and absolute positions are bad practice in Swing?

There are multiple problems with absolute positioning: Different screen sizes and resolutions, what looks great on your machine would come out differently on another screen with a different resolution. In the same vein, what happens when a user resizes the screen because they want to run your application side by side with some other application … Read more