我想創建一個JPanel,它有3個組件排成一行。它應該有一個彩色框,一個標籤,然後是一個刪除按鈕。jpanels之間不需要的空間
我有一個JPanel設置爲GridLayout,它存儲彩色框的Janel,標籤的JLabel和帶有自定義ImageIcon的JButton。
問題是彩色方塊和標籤之間有空白。我突出了每個組件的邊界,沒有任何組件似乎被過度延伸。
這裏是我的意思截圖:
這裏是我一起工作的代碼: Label類:
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);
}
}
這裏是LabelColourBox:
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);
}
}