0

I am trying to add Components to my JPanel, however they aren't sized correctly and not in the right location. This my code for the componenent.

button = new JButton();
button.setSize(100, 100);
button.setLocation(400, 400);
button.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
vm.panel.add(button);

It's also behind the other things I'm drawing, so it's not visible (that's why I made the cursor crosshair, to see where my button was). This is what I'm drawing.

g.drawImage(ImageIO.read(getClass().getResourceAsStream("/background.jpg")), 0, 0, vm.panel.getWidth(), vm.panel.getHeight(), null);
g.setColor(Color.WHITE);
g.fillRoundRect(200, 200, 880, 560, 100, 100);
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 48));
g.drawString("Login", 575, 300);
  • 1
    First off, don't load images when drawing. That will destroy your performance. Second, where are you doing your drawing? It should be in `paintComponent(Graphics)`. Some more code may be needed. – Obicere May 28 '16 at 18:09
  • @Obicere Oops, I didn't put it in the paintComponenet. The component now draws correctly, however the size and location for the button aren't set correctly. –  May 28 '16 at 18:24
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson May 28 '16 at 21:02
  • Strategies to change the size of a button: 1) Give it a different sized icon. 2) Shorten or lengthen the text it displays, or use a different font size. 3) Change the [margin thickness](http://docs.oracle.com/javase/8/docs/api/javax/swing/AbstractButton.html#setMargin-java.awt.Insets-) – Andrew Thompson May 28 '16 at 21:05

1 Answers1

2

however the size and location for the button aren't set correctly.

The default layout manager for a JPanel is a FlowLayout. The layout manager will determine the size and location of the button.

So use an appropriate layout manager to the button is displayed how you want it.

For example is you just want the button displayed in the center of the panel you could use a GridBagLayout.

panel.setLayout( new GridBagLayout() );
panel.add(button, new GridBagConstraints());

Read the Swing tutorial on Layout Managers for more information and examples.

camickr
  • 321,443
  • 19
  • 166
  • 288