我正在尝试创建一个 JPanel,它有 3 个组件排列成一行。它应该有一个彩色框、一个标签和一个删除按钮。
我将 JPanel 设置为 GridLayout,其中存储了用于彩色框的 JPanel、用于标签的 JLabel 和带有自定义 ImageIcon 的 JButton。
问题是彩色框和标签之间有一个空白区域。我已经突出显示了每个组件的边界,并且似乎没有任何组件被过度拉伸。
这是我的意思的屏幕截图:
这是我正在使用的代码:标签类:
public class Label extends JPanel {
JButton btnDeleteObject;
// Delete icon
ImageIcon delIcon = new ImageIcon("Delete.png");
Image img = delIcon.getImage();
Image newimg = img.getScaledInstance(28, 28, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaledDelIcon = new ImageIcon(newimg);
Color labelColour;
public Label(String labelName, Color labelColour) {
this.labelColour = labelColour;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
addComponents(labelName);
}
private void addComponents(String labelName) {
JPanel innerContainer = new JPanel(new GridLayout(1, 3));
JLabel name = new JLabel(labelName);
LabelColourBox cBox = new LabelColourBox();
name.setMaximumSize(new Dimension(80, 40));
name.setPreferredSize(new Dimension(80, 40));
name.setSize(new Dimension(80, 40));
name.setBorder(BorderFactory.createLineBorder(Color.blue));
setBorder(BorderFactory.createLineBorder(Color.black));
// name.setBorder(new EmptyBorder(5, 5, 5, 5));
// Add action to delete button for Icon
Action action = new AbstractAction("Button Label", scaledDelIcon) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
System.out.println("delete");
}
};
btnDeleteObject = new JButton(action);
// Remove label, background
btnDeleteObject.setText("");
btnDeleteObject.setContentAreaFilled(false);
setAlignmentX(LEFT_ALIGNMENT);
innerContainer.add(cBox);
innerContainer.add(name);
innerContainer.add(btnDeleteObject);
add(innerContainer);
}
}
这是标签颜色框:
public class LabelColourBox extends JPanel{
public LabelColourBox() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setBorder(BorderFactory.createLineBorder(Color.green));
setMaximumSize(new Dimension(40, 40));
setPreferredSize(new Dimension(40, 40));
setSize(new Dimension(40, 40));
g.setColor(Color.RED);
g.fillRect(0, 0, 40, 40);
}
}