0

I'm wondering what the ideal way is to organize buttons, textfields, text, etc. In JFrame, because the way i'm doing it now takes up a lot of lines and I struggle with making a good layout. I'm currently using GridBagConstraints so a more specific question is how could I have a button between gridx 1 and 2 without a big gap. Here's the code I have.

    myGrid.gridy = 1;
    myGrid.gridx = 1;
    getContentPane().add(firstName, myGrid);
    myGrid.gridx = 2;
    getContentPane().add(firstNameField, myGrid);
    myGrid.gridy = 2;
    myGrid.gridx = 1;
    getContentPane().add(lastName, myGrid);
    myGrid.gridx = 2;
    getContentPane().add(lastNameField, myGrid);
    myGrid.gridy = 3;
    myGrid.gridx = 1;
    getContentPane().add(studentID, myGrid);
    myGrid.gridx = 2;
    getContentPane().add(studentIDField, myGrid);
    myGrid.gridx = 1;
    myGrid.gridy = 4;
    getContentPane().add(grade, myGrid);
    myGrid.gridx = 2;
    getContentPane().add(gradeField, myGrid);
    myGrid.gridx = 1;
    myGrid.gridy = 5;
    getContentPane().add(hours, myGrid);
    myGrid.gridx = 2;
    getContentPane().add(hoursField, myGrid);
Ansharja
  • 1,237
  • 1
  • 14
  • 37
  • 2
    A [mcve] would probably be more helpful. But, I tend to break the UI down into seperate areas of responsibility, use panels to contain components which are related to each other – MadProgrammer Feb 08 '20 at 02:15
  • 1
    The way I usually use GridBagLayout is by creating a method that does everything for me, for example: `public JPanel addComponent(int gridx, int, gridy, int gridheight, int gridwidth, GridBagConstraints gbc)` – Nosrep Feb 08 '20 at 02:28
  • A common strategy to solve complex computing tasks, is to break them into small, well defined manageable tasks. Divide and conquer. This also applies to gui: break the design into small, easy to layout containers. You can see examples [here](https://stackoverflow.com/a/55511724/3992939) [here](https://stackoverflow.com/a/47368681/3992939) and [here](https://stackoverflow.com/a/51342131/3992939). For more help post mre as advised and describe the desired layout. – c0der Feb 12 '20 at 07:37

0 Answers0