Skip to content
Advertisement

Can’t Change button or panel location in Swing (Java)

I can’t change the location of Button or Panel in “setbounds” in java swing.It’s just stuck to the top. What should I change here? Should I add a “Gridlayout” to the button or something? Changing the panel location does nothing for the button.

public class Main {

public static void main(String[] args) {

    // Declaring In-Game Variables
    final int[] cookieamount = {1};

    // Creating the components
    JLabel cookiecounter = new JLabel();
    JFrame window = new JFrame();
    JButton cookiebutton = new JButton();
    JPanel panel = new JPanel();


    // Window Properties
    window.setSize(900, 550);
    window.setTitle("Cooke Clicker");
    window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    window.setVisible(true);
    window.setBackground(Color.BLUE);

    // Panel Properties
    panel.setBounds(1,1,350,350);
    panel.setBackground(new Color(24, 44, 44));

    // Cookie Counter Properties
    cookiecounter.setLocation(50,50);
    cookiecounter.setForeground(new Color(255, 255, 255));
    cookiecounter.setFont(new Font("Comic Sans MS", Font.BOLD, 60));

    // Cookie Button Properties
    cookiebutton.setBounds(200,200,300,300);
    cookiebutton.setSize(150,50);
    cookiebutton.setIcon(new ImageIcon("assets/cookie.png"));
    cookiebutton.setContentAreaFilled(false);
    cookiebutton.setFocusPainted(false);
    cookiebutton.setBorder(null);

    // Set Cookie Counter text to amount of cookies

    cookiebutton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            cookieamount[0]++;
            cookiecounter.setText(String.valueOf(cookieamount[0]));
        }
    });



    // Adding Components to window
    window.setContentPane(panel);
    window.add(cookiecounter);
    panel.add(cookiebutton);
    window.getContentPane();
}
}

enter image description here

Advertisement

Answer

In Java Swing, a layout manager decides on where the contained components are getting placed. The default layout of a JFrame is BorderLayout which places the components in regions around the border (or center).

If you want to place your components freely, you have to “disable” your layout.

window.setLayout(null);

This should work as intended.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement