gpt4 book ai didi

java - 如何使水平滚动条出现在包含 JTextPane 组件的 JScrollPane 中

转载 作者:行者123 更新时间:2023-11-29 05:32:15 24 4
gpt4 key购买 nike

我无法使水平滚动条出现。我试过使用 JTextPane.setSize()、JTextPane.setPreferredSize() 和 JTextPane 的无大小方法。我也在使用 JScrollPane.setPreferredSize()。

垂直滚动条出现,水平滚动条不出现。

这是一个例子:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test {

private int textPaneWidth = 500;
private int textPaneHeigth = 200;
private int scrollPaneWidth = 100;
private int scrollPaneHeigth = 100;
private JTextPane textPane;
private JButton button;
private JFrame frame;
private JScrollPane scrollPane;

public static void main(String[] args) {

Test gui = new Test();
gui.go();

}

private void go() {

frame = new JFrame("Test");
button = new JButton("button");
textPane = new JTextPane();
scrollPane = new JScrollPane(textPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ButtonListener());
textPane.setFont(new Font("Courier", Font.PLAIN, 12));

// Sizes:
// textPane.setSize(textPaneWidth, textPaneHeigth); // ???
// textPane.setPreferredSize(new Dimension(textPaneWidth, textPaneHeigth)); // ???
scrollPane.setPreferredSize(new Dimension(scrollPaneWidth, scrollPaneHeigth));

frame.add(button);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);

}

private class ButtonListener implements ActionListener {

public void actionPerformed(ActionEvent event) {
textPane.setText("==================================================================== \n" +
"==================================================================== \n" +
"==================================================================== \n" +
"==================================================================== \n" +
"==================================================================== \n");
}

}
}

当按下按钮时,字符串被添加到 JTextPane 中。有垂直滚动,但没有水平滚动。

这是我按下按钮后看到的:

no horizontal scrolling :(

我做错了什么?

最佳答案

似乎您需要扩展 JTextPane 以避免换行

https://forums.oracle.com/thread/1210688

class JTextWrapPane extends JTextPane {

boolean wrapState = true;
JTextArea j = new JTextArea();

JTextWrapPane() {
super();
}

public JTextWrapPane(StyledDocument p_oSdLog) {
super(p_oSdLog);
}


public boolean getScrollableTracksViewportWidth() {
return wrapState;
}


public void setLineWrap(boolean wrap) {
wrapState = wrap;
}


public boolean getLineWrap(boolean wrap) {
return wrapState;
}
}

编辑:

//  instead of  private JTextPane jtp = new JTextPane( sdLog );
private JTextWrapPane jtp = new JTextWrapPane( sdLog );
//and set LineWrap = (false):
jtp.setLineWrap(false);

关于java - 如何使水平滚动条出现在包含 JTextPane 组件的 JScrollPane 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20713631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com