我目前正在编写一个 Java 应用程序来显示数据库中的想法列表。每个想法都有一个标题和一个数字,我希望将其与类似的想法一起显示在列中。正如您从下图中看到的,我遇到了一些包装问题。
我想要的是一种以编程方式切断长想法名称的尾部以适应分配的空间的方法。所以:
如果列宽仅为
##########################
一个很长的想法标题
会变成
一个很长的我...#123
代码
public class IdeaBar extends JPanel implements MouseListener {
private SortingColumn column;
private Idea idea;
private JPanel headPanel;
private JPanel bodyPanel;
private boolean isShrunk;
private boolean mouseToggle;
public IdeaBar(Idea id) {
this.idea = id;
this.setDoubleBuffered(true);
setLayout(new MigLayout("insets 0, hidemode 2", "[grow]", "[32px:32px:32px]0[]"));
// Head Panel
headPanel = new JPanel();
headPanel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
headPanel.addMouseListener(this);
headPanel.setBorder(new BevelBorder(BevelBorder.RAISED, null, null,
null, null));
headPanel.setBackground(Color.GRAY);
headPanel.setBackground(idea.getStatus().getColor());
headPanel.setLayout(new BorderLayout(0, 0));
// Head Panel Labels
JLabel titleLabel = new JLabel("" + idea.getTitle());
titleLabel.setFont(new Font("Dialog", Font.PLAIN, 20));
titleLabel.setForeground(idea.getStatus().getTextColor());
headPanel.add(titleLabel, BorderLayout.WEST);
JLabel numLabel = new JLabel("New label");
numLabel.setHorizontalAlignment(SwingConstants.RIGHT);
numLabel.setForeground(idea.getStatus().getTextColor());
numLabel.setFont(new Font("Tahoma", Font.PLAIN, 20));
numLabel.setText("#" + idea.getNumber());
headPanel.add(numLabel, BorderLayout.EAST);
add(headPanel, "cell 0 0, grow, wrap");
// Body Panel
bodyPanel= new IdeaBarBodyPanel(idea);
this.add(bodyPanel, "grow");
this.shrink();
}
最佳答案
尝试将 titleLabel
添加到 CENTER 而不是 WEST。因此,应调整其大小以填充剩余空间并自动将省略号添加到文本中。请注意,这可能不适用于每个系统,请参见此处:Java JLabel/JButton: on some systems I get "..." (an ellipsis) and on some systems I don't. how can I force to disable the ellipsis at all?
关于java - JPanels 中的 JLabels 大小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6442078/