我有一个扩展JPanel的formPanel,它直接以扩展JFrame的MainFrame为中心。
// this is the constructor of the mainframe
public MainFrame() {
super("Invoice Generator");
toolBar=new ToolBar();
formPanel=new FormPanel();
setLayout(new BorderLayout());
add(toolBar, BorderLayout.NORTH);
add(formPanel, BorderLayout.CENTER);
// this is where i add the custom components
setBackground(new Color(170, 175, 255));
setVisible(true);
layout();
setSize(new Dimension(500, 250));
}
public void layout() {
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
/////////////first row/////////////////////////////
gc.gridx=0;
gc.gridy=0;
gc.weightx=1;
gc.weighty=1;
gc.insets=new Insets(2, 2, 2, 2);
gc.anchor=GridBagConstraints.NONE;
add(new JButton("Booked by"), gc);
gc.gridx=1;
gc.gridy=0;
gc.weightx=1;
gc.weighty=1;
gc.insets=new Insets(2, 2, 2, 2);
gc.anchor=GridBagConstraints.NONE;
add(text1, gc);
}我的组件没有出现在我的formPanel上,为什么?
发布于 2015-07-20 12:20:54
您的layout方法似乎是在JFrame上运行,而不是在formPanel上运行
就像..。
public void layout() {
formPanel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
/////////////first row/////////////////////////////
gc.gridx=0;
gc.gridy=0;
gc.weightx=1;
gc.weighty=1;
gc.insets=new Insets(2, 2, 2, 2);
gc.anchor=GridBagConstraints.NONE;
formPanel.add(new JButton("Booked by"), gc);
gc.gridx=1;
gc.gridy=0;
gc.weightx=1;
gc.weighty=1;
gc.insets=new Insets(2, 2, 2, 2);
gc.anchor=GridBagConstraints.NONE;
formPanel.add(text1, gc);
}可能会更好用。
我可能会创建一个自定义类,它扩展自JPanel,封装了这些字段,然后简单地将其添加到框架中。
https://stackoverflow.com/questions/31508597
复制相似问题