vrillon99
vrillon99

Reputation: 35

Java swing method setLayout null doesn't work

import javax.swing.*;
import java.awt.*;

class MenuPanel extends JPanel {
    JButton setTextColor;
    JSlider setMobNumber;
    MenuPanel() {
        setLayout(null);
        setBackground(Color.LIGHT_GRAY);

        setTextColor = new JButton("Change Text Color");
        setMobNumber = new JSlider(1, 10);

        setTextColor.setBounds(10, 40, 20, 10);
        setMobNumber.setBounds(10, 80, 20, 10);

        add(setTextColor);
        add(setMobNumber);

        setTextColor.setFocusable(false);
        setMobNumber.setFocusable(false);
    }
}

class GameBoard extends JFrame {
    MenuPanel menuPanel = null;
    GameBoard() {
        setTitle("MyGame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        menuPanel = new MenuPanel();
        add(menuPanel, BorderLayout.WEST);

        setSize(600, 500);
        setVisible(true);
    }
}

public class MyGame {
    public static void main(String args[]) {
        new GameBoard();
    }
}

This is My Java code. I want to make menu panel on main frame. So I made above code and attached "add(menuPanel)" on Main Frame code. But my menu panel doesn't show up. What should I do. I thought hard about this. But I don't know what I did wrong.

Upvotes: 0

Views: 964

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347332

Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

BorderLayout is relying on your MenuPanel preferred size to tell what size it might like to be, this information is typically generated by the layout manager, but because you've set the layout manager to null, it's using the default size of 0x0 instead.

The simple answer would be to make use of an appropriate layout manager and allow the underlying API to make the decisions about how best components should be laid out, which takes into considerations differences in how these components might need to be sized on different systems...

Take a look at Laying Out Components Within a Container for more details

Upvotes: 1

Marv
Marv

Reputation: 3557

I've just tested your code and it works, but the frame doesn't resize to the panel size so it looks like the panel has not been added. However, resizing the frame will reveal the panel. Try giving the panel a prefered size with setPreferredSize(new Dimension(width, height)) and then calling pack() on your frame after adding the MenuPanel.

Upvotes: 0

Related Questions