user5910225
user5910225

Reputation:

JComponents not drawn correctly

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);

Upvotes: 0

Views: 34

Answers (1)

camickr
camickr

Reputation: 324197

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.

Upvotes: 2

Related Questions