Skip to content
Advertisement

How do I adjust the button sizes and move them to be in a different place?

I’m trying to get some of the buttons to be bigger and be able to move them around to get them more to what my professor wants them to be but I’m not sure how to do it.

I decided to use a GridBagLayout but my professor never talked about it so I’m not sure if I’m missing anything or how exactly it works.

The image is what he wants us to get it too. Exactly like this.

LayoutQuestion

JavaScript

Advertisement

Answer

There are some improvements you can do to your code:

  1. Don’t use static variables, and place your program on the EDT, an easy way to do this is:

    JavaScript
  2. Don’t call setSize(...) on your JFrame, it’s going to make your window smaller than you think, it’s taking the frame decorations into the calculation for the size, instead call frame.pack(), or override the getPreferredSize() of your JPanel, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for a more in-depth explanation.

  3. Don’t call frame.setVisible(true) before you’ve added all your components to your JFrame, otherwise you’ll get strange bugs related to invisible components, that line should be the last one on your code.

  4. Divide and conquer, you can use multiple JPanels with different Layout Managers, and you can combine them and join them together later on.

One possible approach (which isn’t exactly as your teacher wants it to be but is close enough) is this one:

JavaScript

enter image description here

Play around with the code, and try to find a different approach by combining the layouts, divide each piece of the window in your head and see how to apply a different layout manager to each of them, divide them in methods as I did to make things easier to follow.

Find a way to left align the elements in the JCheckBoxes for example, and other things

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