-1

I have a method that is just adding a button to a JPanel. I have a problem however, where there are some properties of this button that I cannot modify.

setBackground and setLocation method don't affect the button at all. I'm trying to move the button to the bottom of the JPannel but nothing seems to happen when I try setting the horizontal alignment or location.

    public static void initButtons() {
        JButton purchaseButton = new JButton();
        purchaseButton.setText("Proceed to Checkout");
        purchaseButton.setPreferredSize(new Dimension(200,50));
        purchaseButton.setIcon(new ImageIcon("/Users/alecr/eclipse-workspace/MakingPurchases/src/shopping_cart_sprite.png"));
// set location method not working
        purchaseButton.setLocation(25, 600);

        JPanel firstPanel = new JPanel(); 
        firstPanel.setBounds(25, 40, 300, 700);
        firstPanel.setBackground(new java.awt.Color(90,90,100));
        firstPanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(3.0f), new Color(70,70,80)));
        frame.add(firstPanel);

        firstPanel.add(purchaseButton);
    }
Hydra
  • 373
  • 3
  • 18
  • 1
    Set a LayoutManager for your panel and add the button with the correct constraints. – Robert Kock Oct 03 '19 at 15:05
  • Provide ASCII art or a simple drawing of the *intended* layout of the GUI at minimum size, and if resizable, with more width and height - to show how the extra space should be used. – Andrew Thompson Oct 03 '19 at 15:50

1 Answers1

1

Instead of using setLocation and setBounds for each component, you should use a proper LayoutManager and let it do the work for you. Having hard coded sizes and locations will not allow your application be scalable for different screen sizes and your JFrame will not be able to be resizable, which is not so user-friendly.

However, if you insist of using absolute-hard coded values (coordinates and dimensions) you must remove the layout manager from the container (a JPanel uses FlowLayout by default), because like I mentioned, it takes care of such things. In order to do that:

JPanel panel = new JPanel(null); //null layout manager allows absolute values

George Z.
  • 6,643
  • 4
  • 27
  • 47
  • I've set the layout manager to `null`, which works for setting the bounds now. I'd also like to switch the colour. Is there a way this could be done as the method `purchaseButton.setBackground(Color.blue);` didn't work. – Hydra Oct 03 '19 at 15:40
  • @Hydra I'm afraid, this is a question for another topic. But before you ask, do some research. Doesn't sound a bit common to you? Maybe it has already an answer out there? – George Z. Oct 03 '19 at 15:42