jPanel1 = new JPanel();
GridBagLayout layout = new GridBagLayout();
jPanel1.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
filler = new JLabel();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
jPanel1.add(filler, gbc);
我试图通过执行jPanel1.remove(填充)来删除,然后在该位置放置一个新的JLabel,但显然不起作用。我做错了什么?
谢谢!
答案 0 :(得分:1)
如果filler
只是一个JLabel,那么你可以做
filler.setText("add text here");
或者,如果要更换其他组件,更好的方法是创建使用卡片布局的面板。然后你可以交换这两个组件。有关详细信息,请参阅How to Use Card Layout上的Swing教程。
另一种选择可能是做:
GridBagLayout layout = (GridBagLayout)jPanel1.getLayout();
GridbagConstraint gbc = layout.getConstraint(oldComponent);
jPanel1.remove(oldComponent);
jPanel1.add(newComponent, gbc);
jPanel1.revalidate();
jPanel1.repaint();
答案 1 :(得分:1)
至于你遇到问题的原因,我只能想象。
不要忘记将filler
组件添加到最后一个组件的右侧/底部....
例如......
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class GridBagLayoutTest {
public static void main(String[] args) {
new GridBagLayoutTest();
}
public GridBagLayoutTest() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final TestPane pane = new TestPane();
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pane.addNewItem();
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(pane);
frame.add(btn, BorderLayout.SOUTH);
frame.pack();
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int gridX = 0;
private int gridY = 0;
private JLabel filler;
private int columnCount = 4;
public TestPane() {
setLayout(new GridBagLayout());
filler = new JLabel();
}
public void addNewItem() {
remove(filler);
JLabel label = new JLabel("Cell " + gridX + "x" + gridY);
label.setBorder(new EmptyBorder(10, 10, 10, 10));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = gridX;
gbc.gridy = gridY;
add(label, gbc);
gridX++;
if (gridX >= columnCount) {
gridX = 0;
gridY++;
}
gbc = new GridBagConstraints();
gbc.gridx = columnCount;
gbc.gridy = gridY + 1;
gbc.weightx = 1;
gbc.weighty = 1;
add(filler, gbc);
revalidate();
repaint();
}
}
}