I am currently writing a Java application to display a list of ideas from a database. Each Idea has a title and a number which i would like to display in a column along with similar ideas. As you can see from the picture below, i am having a bit of a packaging issue.
What i would like is a way to programatically cut off the tail of a long idea name to fit in the allotted space. So:
if the column width is only
########################
A really long idea titl
would become
A really long i... #123
Code
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("#"开发者_StackOverflow社区 + 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();
}
Try and add the titleLabel
to CENTER instead of WEST. Thus it should be resized to fill the space left and automatically add the ellipis to the text. Note that this might not work on every system, see here: 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?
General code. Sees if the string is longer than what you can display. If it is, it cuts of the part that cant be displayed and adds the ...
int colLength = 20;
public void addEntry(String entry)
{
if(entry.length() > colLength)
{
entry = entry.substring(0,colLength -3) + "...";
}
add(entry)
}
Well, in the end, i just decided to paint my own component. I want careful control of the background anyway, so this was the best solution for me.
Upvotes to both of you because your answers were instrumental in helping me find my way!
精彩评论