javaGeek
javaGeek

Reputation: 314

Placing border in desire location inside JPanel

I am trying to put a border around the buttons inside of my JPanel. I have this:

 Border lineBorder = BorderFactory.createLineBorder(Color.black);

 welcomePanel.setBorder(lineBorder);

But that only puts the border around my entire application window, which makes sense. I am wanting to be able to place the border where I want.... I did this when placing my buttons in the desired location

button1.setBounds(10, 10, 60, 30);

And I looked in the API and saw a paintBorder method with parameters of int x, int y, int width, int height, which would make sense to me, but I couldn't get it to work.

Any advicewould be appreciated

Upvotes: 0

Views: 44

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

Start by adding you buttons to another JPanel...

JPanel buttons = new JPanel();
buttons.setLayout(...);
// add buttons...

Set the Border of this panel...

buttons.setBorder(BorderFactory.createLineBorder(Color.black));

Add this to you main container...

welcomePanel.add(buttons);

Pixel perfect layouts are an illusion in modern UI design, you don't control factors like font choices, rendering pipelines, DPI and other factors which will change the requirements needed for each component to be positioned, that is the role of layout managers.

Swing has been designed to work with layout managers, attempting to do without will cause no end of issues and frustration as you try and find more hacks to get around the issues.

You can use things like EmptyBorders to introduce empty space between components or Insets with a GridBagLayout

Upvotes: 2

Related Questions