我使用的GridBagLayout做一个状态栏,它看起来像的图片。我有4个区域,所以我在第一个区域有一个按钮,然后是第二个区域的信息消息,然后我需要两个区域(并且我还有第五个区域可以建立角落)。
按钮区域非常合适,因为内容总是具有相同宽度的按钮。与角落区域相同。信息区域必须获得所有可用空间。第三和第四区域必须具有固定值,与屏幕大小无关。
我该怎么做?
我当前的代码是:
public MyStatusBar() {
setLayout(new GridBagLayout());
setPreferredSize(new Dimension(getWidth(), 23));
GridBagConstraints c = new GridBagConstraints();
botonDispositivo = new JButton("");
this.setText(0, "Disconnected");
URL imageUrl = getClass().getResource("resources/22x22/dispositivo01.png");
this.setButtonImg(imageUrl);
this.setButtonEnabled(false);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.WEST;
c.gridwidth = 1;
c.gridheight = 1;
this.add(botonDispositivo, c);
c.insets= new Insets(0,10,0,0);
c.gridx ++;
c.gridy = 0;
c.weightx = 0.7;
c.fill = GridBagConstraints.HORIZONTAL;
msgLabel = new JLabel("");
msgLabel.setPreferredSize(new Dimension(500, msgLabel.getHeight()));
this.add(msgLabel, c);
this.setText(1, "Waiting for potentiostat conection");
c.gridx ++;
c.gridy = 0;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
this.add(new SeparatorPanel(Color.GRAY, Color.WHITE), c);
c.gridx ++;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
c.weightx = 0.0;
overErrorLabel = new JLabel("");
overErrorLabel.setSize(new Dimension(150, overErrorLabel.getHeight()));
this.add(overErrorLabel, c);
//this.setText(2, "");
c.gridx ++;
c.gridy = 0;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
this.add(new SeparatorPanel(Color.GRAY, Color.WHITE), c);
c.gridx ++;
c.gridy = 0;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
timeLabel = new JLabel("");
timeLabel.setMinimumSize(new Dimension(150, timeLabel.getHeight()));
//timeLabel.setMaximumSize(new Dimension(150, timeLabel.getHeight()));
this.add(timeLabel, c);
//this.setText(3, "");
JPanel rightPanel = new JPanel(new GridBagLayout());
c.gridx ++;
c.gridy = 0;
c.weightx = 0.0;
c.fill = GridBagConstraints.BOTH;
rightPanel.add(new JLabel(new AngledLinesWindowsCornerIcon()), c);
rightPanel.setOpaque(false);
c.gridx ++;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
this.add(rightPanel, c);
setBackground(SystemColor.control);
}
看起来没问题,但有一个问题: –
当标签为空时,ipadx是区域宽度。但是,当我写入标签并获得例如100px宽时,该区域获得100px + ipadx宽。我希望它始终保持ipadx宽,我该怎么做? –
来自javadoc:ipadx此字段指定组件的内部填充,要添加多少空间以添加到组件的最小宽度。组件的宽度至少是其最小宽度加上ipadx像素。所以它取决于你的内容的最小尺寸。 – StanislavL