问题
I have this class which creates a grid:
class GridPane extends JPanel{
public GridPane(int row,int col){
setLayout(new GridLayout(row,col));
setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
for (int i =1; i<=(row*col); i++)
{
JPanel pan = new JPanel();
pan.setBackground(Color.RED);
pan.setPreferredSize(new Dimension(3,3));
pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(pan);
}
}
And this which sets up the empty main frame with the group layout:
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGap(0, 440, Short.MAX_VALUE)
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGap(0, 268, Short.MAX_VALUE)
);
contentPane.setLayout(gl_contentPane);
}
I am not very experienced with SWING and I have been trying to add a GridPane object to the Right of the Main Frame for some time. It keeps telling me something like :
java.lang.IllegalStateException: GridPane[,0,0,0x0,invalid,layout=java.awt.GridLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.border.EmptyBorder@6ba7508a,flags=9,maximumSize=,minimumSize=,preferredSize=] is not attached to a vertical/horizontal group
Does anyone know what is going on? What should I do to accomplish what I need? Sorry for posting lots of code. Thanks for the help.
回答1:
I would suggest that in this case you make use of BorderLayout.
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(pan, BorderLayout.LINE_END);
Here is the full code. I hope this is what you are looking for.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
GridPane gp = new GridPane(5, 5);
frame.add(gp, BorderLayout.EAST);
frame.setVisible(true);
frame.setSize(250, 250);
}
}
class GridPane extends JPanel {
public GridPane(int row, int col) {
setLayout(new GridLayout(row, col));
setPreferredSize(new Dimension(125, 125));
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
for (int i = 1; i <= (row * col); i++) {
JPanel pan = new JPanel();
pan.setBackground(Color.RED);
pan.setPreferredSize(new Dimension(3, 3));
pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(pan);
}
}
}
Useful links:
- A Visual Guide to Layout Managers
- How to Use BorderLayout
- How to Use GroupLayout
来源:https://stackoverflow.com/questions/8630213/adding-a-custom-component-manually-in-swing-group-layout