I have a JPanel with specific size. I have added a JLabel on it. Now the text of JLabel is dynamic and comes from the database. When I add 开发者_Go百科this data to JLabel, instead of it staying in the JPanel, it spreads out.
When it happens, the data inside the JPanel is visible but the one outside the JPanel is not visible (which is obvious). I want to know if there is a way by which the data instead of going out of JPanel, will stay in JPanel itself (means it automatically adds a newline and moves to newline instead of going out).
JLabel doesn't have a method for that. But you have a few options:
- Use HTML tags in text you set
"Hello<br/>World"
. - Use JTextArea or JEditorPane and disable editing. JTextArea have the
setLineWrap(true)
method, and JEditorPane wraps lines by default.
You'll want to use something more robust than a simple JLabel
, like a JTextArea
. Your best place to learn how to achieve the desired effect would be to read the Swing tutorial here. Since you know the size of your JPanel
you can set the size of your JTextArea
and it should automatically line-wrap to accommodate for your variable-sized strings.
精彩评论