Search code examples
javaswingjframejpaneljbutton

JButton wont change size or position on JPanel


I added a button into JPanel and tried to change the size and the position of the button. I've tried different lines of codes but they wont work. Also putting in parent.setLayout(null); or panel.setLayout(null); will just completely remove the button and the background

Here is the code:

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

public class app {

    public static void main(final String[] args) {
        final JFrame parent = new JFrame("CPS TEST");
        JButton button = new JButton("Button");
        JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.add(button);
        panel.setBackground(Color.DARK_GRAY);
        parent.add(panel, BorderLayout.CENTER);
        parent.setSize(500, 300);
        parent.setBackground(Color.CYAN);
        parent.setLocationRelativeTo(null);
        parent.setVisible(true);
        parent.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Solution

  • Here are three ways to increase the size of a button:

    enter image description here

    enter image description here

    enter image description here

    Changing the position of a component is worthy of a separate question, but changing the size of a button is easy.