I currently have a jpanel with layout set to GridBagLayout, with gbc = new GridBagConstraints();, However for whatever value of x, y or gridwidth,gridheight the items don't move at all.
I would greatly appreciate an expert eye to look over my code to see what I am missing, Thanks in advance.
Edit: Added the imports and the main method
Edit 2: turns out I was thinking the x and y values were pixels and that was the reason it wasn't working
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class HomeScreenUI {
public void addobjects(Component componente, Container yourcontainer, GridBagLayout layout, GridBagConstraints gbc, int gridx, int gridy, int gridwidth, int gridheight){
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
layout.setConstraints(componente, gbc);
yourcontainer.add(componente);
}
HomeScreenUI(){
//frame
JFrame frame = new JFrame("Opisa");
//panels, one before button click and one after
JPanel panel = new JPanel();
JPanel panelAfterButtonClick = new JPanel();
GridBagLayout ourlayout;
ourlayout = new GridBagLayout();
panel.setLayout(ourlayout);
panelAfterButtonClick.setLayout(ourlayout);
GridBagConstraints gbc = new GridBagConstraints();
//jlabel that isnt displaying + dimensions
JLabel label = new JLabel("Opisa");
label.setFont(new Font("Helvetica", Font.PLAIN, 70));
//second jlabel that isn't displaying
JLabel label2 = new JLabel("Home");
label2.setFont(new Font("Helvetica", Font.PLAIN, 70));
//adding the labels to the panels
panel.add(label);
panelAfterButtonClick.add(label2);
//button that is displaying both before and after
JButton button = new JButton("Click Me..");
JButton buttonAfterClick = new JButton("Clicked Me..");
//adding the buttons to the jpanel
this.addobjects(label, panel, ourlayout, gbc, 0,0, 3, 1);
this.addobjects(button, panel, ourlayout, gbc, 700, 100, 2, 0);
this.addobjects(label2, panelAfterButtonClick, ourlayout, gbc, 200, 200, 1, 1);
this.addobjects(buttonAfterClick, panelAfterButtonClick, ourlayout, gbc, 700, 10, 2, 0);
//function that changes the panel after the button is clicked
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
frame.setContentPane(panelAfterButtonClick);
frame.invalidate();
frame.validate();
}
});
//adding the panel to the frame and setting the size
frame.add(panel);
frame.setSize(720,1280);
frame.setVisible(true);
}
}
public static void main (String args[]) {
HomeScreenUI hs = new HomeScreenUI();
}
import
statements and amain
method. For better help sooner, edit to add a minimal reproducible example or Short, Self Contained, Correct Example. – Andrew Thompson