HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

JPanel rendering too slowly

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
renderingjpanelslowlytoo

Problem

I am working on an application which first loads a 'settings' panel and then loads the application. It all works fine, loading the settings panel takes a few seconds longer than I would like it to. The problem is in loading the settings panel, not the application itself.

I have a simple main method:

public class Main {
    public static void main(String[] args) {
        new FrameInitializer().init();
    }
}


FrameInitializer class:

```
public class FrameInitializer {
JFrame frame;
JPanel wrapper, settings;
public JComboBox bLevel, wLevel;
public JRadioButton bHuman, wHuman, bComputer, wComputer;
public JButton readyButton;

public FrameInitializer() {}
public void init() {
frame = new JFrame();
settings = new SettingsPanel();
wrapper = new JPanel();
wrapper.add(settings);
frame.setContentPane(wrapper);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}

class SettingsPanel extends JPanel {

private static final long serialVersionUID = 1L;

public SettingsPanel() {

BlackRadioListener blackRadioListener = new BlackRadioListener();
WhiteRadioListener whiteRadioListener = new WhiteRadioListener();
Integer[] levels = {1, 2, 3, 4, 5, 6, 7, 8};
Font title = new Font("Sans Serif", Font.BOLD, 18);
setLayout(new BorderLayout());

JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 2));
JLabel black = new JLabel("Black", SwingConstants.CENTER);
black.setFont(title);
JLabel white = new JLabel("White", SwingConstants.CENTER);
white.setFont(title);
topPanel.add(black);
topPanel.add(white);

/ Construct options for black player /
JPanel blackPanel = new JPanel();
blackPanel.setLayout(new BoxLayou

Solution

Looks like most of the time is spent in the frame.pack() call. Replacing it with frame.setSize(222, 181); is a lot faster. I simply ran the code once with frame.pack() and added a line to output the resulting frame size. Then replaced the pack() call.

Setting the size statically like this is faster, since the code doesn't have to dynamically evaluate all the underlying components, but it has the drawback that you'll have to manually update the optimum size of the frame every time you change the components.

Context

StackExchange Code Review Q#25699, answer score: 2

Revisions (0)

No revisions yet.