gpt4 book ai didi

java - 向 JFrame 添加滚动条

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:09:00 25 4
gpt4 key购买 nike

我在寻找在 JFrame 中添加滚动条的方法时遇到了一些问题。我找到了一种将 System.{in,out,err} 重定向到 JTextArea 的方法,但我没有成功添加滚动条。我希望这个问题不是多余的。

public class console extends JTextArea {    

public static JTextArea console(final InputStream out, final PrintWriter in) {
final JTextArea area = new JTextArea();
new SwingWorker<Void, String>() {
@Override protected Void doInBackground() throws Exception {
Scanner s = new Scanner(out);
while (s.hasNextLine()) publish(s.nextLine() + "\n");
return null;
}
@Override protected void process(List<String> chunks) {
for (String line : chunks) area.append(line);
}
}.execute();
area.addKeyListener(new KeyAdapter() {
private StringBuffer line = new StringBuffer();
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c == KeyEvent.VK_ENTER) {
in.println(line);
line.setLength(0);
} else if (c == KeyEvent.VK_BACK_SPACE) {
line.setLength(line.length() - 1);
} else if (!Character.isISOControl(c)) {
line.append(e.getKeyChar());
}
}
});

return area;
}
public static void main(String[] args) throws IOException {
PipedInputStream inPipe = new PipedInputStream();
PipedInputStream outPipe = new PipedInputStream();
System.setIn(inPipe);
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));

PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);

JFrame frame = new JFrame("\"Console\"");

frame.getContentPane().add(console(outPipe, inWriter));
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// my code
}

最佳答案

创建一个新的JScrollPane对象并设置ScrollBarPolicies

如果您不想让 scollbars 一直出现,只需删除策略即可。

编辑

此外,不要在文本组件上使用 KeyListener,而是使用 DocumentListner 和键绑定(bind)的组合。 (感谢@MadProgrammer)


解决方案

JScrollPane jsp = new JScrollPane(console(outPipe, inWriter));
jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(jsp);

输出

enter image description here

关于java - 向 JFrame 添加滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34263625/

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