简体   繁体   中英

Java Swing GUI: Text Wrap, Center Text, and Custom Font?

I have a JPanel (and I've tried a JTextArea as well) that I would like to have text on it. The text needs to be

  1. Centered
  2. Have word wrap
  3. Use a custom font from a .ttf file that I am currently using that is not installed on the computer. I have already solved this problem, and the font works fine. It does not, however, work when placed in tags as I have seen as a possible solution for my problem.

I can generally get two of these rules to work, but cannot get all three to work at once. I've tried html tags, JLabels, JTextAreas, but none satisfy all conditions. Any suggestions?

    static JTextArea quesLbl;
quesLbl = new JTextArea("");
quesLbl.setWrapStyleWord(true);
quesLbl.setLineWrap(true);
quesLbl.setEditable(false);
quesLbl.setFont(qFont);
quesLbl.setOpaque(true);
quesLbl.setForeground(Color.WHITE);
quesLbl.setBackground(Color.BLUE);

This code results in the text being word wrapped, and the font working, but not being centered.

Assuming you mean horizontally centered, I would suggest using a JTextPane . I did not test, but I would hope, that setting your font would work just as well. For the centering, see Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment , I am quoting the answer there now:

public JTextPane createTextPane(String text){
  JTextPane textPane = new JTextPane();
  tp.setText(text);
  StyledDocument doc = textPane.getStyledDocument();
  SimpleAttributeSet center = new SimpleAttributeSet();
  StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
  doc.setParagraphAttributes(0, doc.getLength(), center, false);+
}

IIRC word wrapping should come free. Hope this helps, if not, clarify the question please.

This did work for the centered and word-wrap part for me:

JLabel label = new JLabel();
label.setText("<html><body style='text-align:center'> This is some very long sentance with many letters and not so much meaning.</body></html>");
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);

The above solution is also working, but I needed that the label is on top of another component of mine (which doesn't work with JTextPane).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM