java 怎么加滚动条_java – 向JFrame添加滚动条

我在找到一种在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() {

@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 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和键绑定的组合. (感谢@MadProgrammer)

JScrollPane jsp = new JScrollPane(console(outPipe, inWriter));

jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

frame.getContentPane().add(jsp);

产量

jG2r4.png

标签:jtextarea,swingworker,java,swing

来源: https://codeday.me/bug/20190829/1761459.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值