Question

I am very new to Swing, and I'm trying to make a GUI. Using Netbeans' GUI creator thing, I managed to make something I liked. But it makes me feel bad that I used the editor for this, so now I am trying to make the same design using code. Here is a picture of what I am trying to make: what I want to make Right now I am just focusing on creating the "Criteria" section (yes I know I spelled it wrong in the picture) Here is what I currently have so far: what I currently have I've highlighted in red where I want to increase the margin:

  • Between the right of the text boxes and left of the labels
  • Between the top of the Criteria panel and the JFrame
  • Between the left and right sides of the panel and the JFrame

I come from web development where increasing the margins is what I want to do. If this is incorrect terminology, please inform me. Here is the code I am currently using:

public class Criteria extends JPanel {
    JLabel JobLabel = new JLabel();
    JLabel BoxLabel = new JLabel();
    JLabel PartLabel = new JLabel();
    JTextField JobInput = new JTextField();
    JTextField BoxInput = new JTextField();
    JTextField PartInput = new JTextField();

    public Criteria() {
        setLayout(new FlowLayout(FlowLayout.LEADING));
        setBorder(BorderFactory.createTitledBorder("Criteria"));
        JobLabel.setText("Job");
        JobLabel.setLabelFor(JobInput);
        BoxLabel.setText("Box");
        BoxLabel.setLabelFor(BoxInput);
        PartLabel.setText("Part");
        PartLabel.setLabelFor(PartInput);
        JobInput.setColumns(8);
        BoxInput.setColumns(8);
        PartInput.setColumns(8);
        add(JobLabel);
        add(JobInput);
        add(BoxLabel);
        add(BoxInput);
        add(PartLabel);
        add(PartInput);
    }
}

I don't know how I would add margin to these components, so help would be very much appreciated. If I cannot achieve this effect with FlowLayout, then please tell me what I should use instead.

Was it helpful?

Solution

Swing tends to call margins or borders 'gaps'. The FlowLayout class (along with a few other layout classes) allows you to set the horizontal and vertical gaps in its constructor, like so:

private static final int PADDING = 3;   // for example
...
    setLayout(new FlowLayout(FlowLayout.LEADING, PADDING, PADDING));

This would add padding between the labels and their text boxes, however, but you could wrap each pair in a JPanel (probably with a FlowLayout). I would make a custom component class for this.

OTHER TIPS

You should look into using an EmptyBorder to give your components "padding". You can create compound borders or can nest JPanels if you need more than one type of border around a JPanel or other component. For gaps between components, you can use the FlowLayout settings as noted above, or can use a strut from the Box class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top