Reputation: 1123
I have some long text in a JLabel e.g. "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua". I want to hide some text if the user resizes the window and there is no much space. I want to get something like this "Lorem ipsum dolor sit...". Is it possible in a JLabel or JTextArea?
Upvotes: 0
Views: 256
Reputation: 801
JLabel
by default will truncate text with an ellipsis (...) if it detects that there is not enough space to display the text. However, if you are using a layout manager in your application then whether or not there is enough space is up to the opinion of the layout manager. For example, BoxLayout
and the default layout will pay attention to the size of the window and allow the label to truncate:
fun labelInBoxLayout() {
val frame = JFrame()
frame.size = Dimension(300, 200)
val panel = JPanel()
panel.layout = BoxLayout(panel, BoxLayout.PAGE_AXIS)
val longString = "WWWWWWWWWWWWWWWWW WWWWWWWWWWWWWWW WWWWWWWWWWW"
val label = JLabel(longString)
panel.add(label)
frame.add(panel)
frame.isVisible = true
}
whereas FlowLayout
will insist that the label should continue for the full width of its text regardless of current window width:
fun labelInFlowLayout() {
val frame = JFrame()
frame.size = Dimension(300, 200)
frame.layout = FlowLayout()
val longString = "WWWWWWWWWWWWWWWWW WWWWWWWWWWWWWWW WWWWWWWWWWW"
val label = JLabel(longString)
frame.add(label)
frame.isVisible = true
}
I found the same to be true for BorderLayout
and SpringLayout
, as well as a BoxLayout
JPanel
nested inside of a FlowLayout
JFrame
. If you have control over which layout you use in your application I recommend experimenting with different ones to find which have the desired effects. Remember that you can add layouts to JPanel
s, so you can start with a frame-wide layout that allows for truncation and then use other layouts in specific sub-sections of your frame.
Upvotes: 2