如何在不使用 JTextArea 的情况下在 JScrollPane 中包装单个 JLabel 的文本而不是水平滚动

问题描述 投票:0回答:1

(注意我是编程新手,所以这可能是一个简单的答案,或者我的代码写错了)我有一个更大的程序,其中的字符串不断被附加和修剪。它是用 html 编写的,所以它的大部分都有换行符,这不是问题,但有时行的长度足以超出滚动窗格的边缘。我不希望它滚动到一边,而是将文本包裹起来。下面的代码复制

public class Main {
  public static void main(String[] args) {
      JLabel label = new JLabel("<html>really long text here.................................................................................................................................................................................................");
      JScrollPane scrollPane = new JScrollPane(label, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

      JPanel panel = new JPanel();
      JFrame frame = new JFrame();

      scrollPane.setPreferredSize(new Dimension(400,400));      

      SpringLayout layout = new SpringLayout();
      panel.add(scrollPane);
      panel.setLayout(layout);
      
      frame.add(panel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(new Dimension(500,500));
      frame.setVisible(true);
      
  }
}

我已经尝试使用滚动窗格和 jlabel 的最大、最小和首选大小以及不同的约束来做很多事情。我也尝试四处寻找类似的问题,但我只能在滚动窗格中找到有关 jtextareas 的信息,由于主代码中的许多不同因素,我无法开始工作。我不断发现的另一件事是在一个滚动窗格中有多个 jlabels,我的滚动窗格只包含 1 个 jlabel,所以很多修复不适用或者不是正确的问题。

java jlabel jscrollpane
1个回答
0
投票
Try This code : 

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container cp = frame.getContentPane();
        JEditorPane editorPane = new JEditorPane();
        editorPane.setText(Constant.text); // Add your long text here
        editorPane.setEditable(false);
        JScrollPane editorScrollPane = new JScrollPane(editorPane);
        editorScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        cp.add(editorScrollPane, BorderLayout.CENTER);
        frame.setSize(new Dimension(500, 500));
        frame.setVisible(true);
    }

A similar issue was discussed here,  https://stackoverflow.com/questions/685521/multiline-text-in-jlabel
© www.soinside.com 2019 - 2024. All rights reserved.