Question

is it possible to edit the x and y of an item in gridbaglayout from actionperformed without going through another gridbaglayout? sorry, if this is a silly question but i'm new to java.

public void actionPerformed(ActionEvent e){
    for (int i = 0; i < 8; i++){
        if (e.getSource() == buttons[i]){
            gbc.gridx = xNow;
            gbc.gridy = yNow;
        }
    }
}
Was it helpful?

Solution

First you should understand the concept behind the GridBagConstraints. For an example,

First we can define GridBagLayout for a panel like this

panelNote = new JPanel(new GridBagLayout());

then you can define gridbag constraints for components in that panel. In that case first we have to define gridbag constraints.

GridBagConstraints panelNoteConstraints = new GridBagConstraints(you can define constraints here);

Then we add Item like this: panelNote.add(getVisitPanel(), panelNoteConstraints);

Now, the important thing come to play, Assume you want to add another component to the panel. Then you can define gridbag constraints in 2 ways

  1. Define new gridbag constraints like what we did previously or
  2. Edit panelNoteConstraints like:

panelNoteConstraints.gridx = 0; panelNoteConstraints.gridy = 1;

Important thing is the result of these two approaches are same. Because, in both ways what you do is edit constant values in GridBagLaout. Then simply the answer is you don't want to do it. But if you want to edit the position of a component, then revalidate() and repaint() methods 'll helpful.

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