简体   繁体   中英

How to hide some text if there is no space in JLabel?

I have some long text in a JLabel eg "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?

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.

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