我的jscrollpane不起作用

时间:2013-12-11 19:31:21

标签: java jscrollpane

public class Gui extends JFrame{
    JTextField tf_input;
    JTextArea ta_output;
    JScrollPane sp_taop;

    private class klis implements KeyListener{    
        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub
            if (e.getKeyCode()==KeyEvent.VK_ENTER){
                //System.out.println("enter");  //debug
                if (!tf_input.getText().isEmpty()){
                    String input = tf_input.getText();

                    ta_output.setText(ta_output.getText()+input+'\n');

                    System.out.println(input);  //debug
                    System.out.println("ok!");  //debug
                    sp_taop.validate(); 
                    tf_input.setText(null);
                }
            }
        }
    }   

    Gui(){
        System.out.println("hello");
        inti();
        render();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void inti() {
        setSize(800, 600);
        //text field input
        tf_input = new JTextField();
        tf_input.setSize(550, 24);
        tf_input.addKeyListener(new klis());
        //text Area
        ta_output = new JTextArea("hello World\n",30,60);
        ta_output.setSize(ta_output.getPreferredSize());
        ta_output.setLineWrap(true);
        ta_output.setEditable(false);
        sp_taop = new JScrollPane();
        sp_taop.add(ta_output);
        sp_taop.setSize(ta_output.getSize().width+20,ta_output.getSize().height);
        sp_taop.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    }   
    private void render() {
        Panel p = new Panel(null);

        ta_output.setLocation(0, 0);
        sp_taop.setLocation(10, 10);
        tf_input.setLocation(10, (sp_taop.getSize().height+20));
        ta_output.repaint();

        //adding
        p.add(sp_taop);
        p.add(tf_input);
        add(p);
    }
}

我在vbox 4.3.4 lUbuntu上的java 1.7.0_25上运行它

问题是jscroll没有自行更新!我该怎么办? 我一直在谷歌搜索几个小时,我没有发现任何接近我正在寻找的东西。

顺便说一下,如果没有它,很难解释这个问题。

1 个答案:

答案 0 :(得分:0)

请勿使用JScrollPane#add,这不是滚动窗格的工作方式,而是尝试使用JScrollPane#setViewportView

查看How to use Scroll Panes

不要将文本字段添加到另一个容器。组件只能有一个父组件,因此将其添加到第二个容器中会将其从第一个组件中删除。

旁注。我会避免使用KeyListener,文本组件有能力消耗关键事件,这意味着您的监听器可能实际上没有得到通知。此外,如果它被调用,组件将处于变异操作的中间(它将尝试更新它的模型),这可能导致意外问题和可能的脏更新。

在这种情况下,我可能想要使用DocumentListener,但您需要对其进行测试。

我也会避免使用null布局。首先,您将无法在滚动窗格的上下文中影响文本字段的位置,因为滚动窗格使用它自己的布局管理器。

此外,操作系统,视频驱动程序和字体之间的差异使潜在的渲染输出无穷无尽。布局管理人员在处理这些情况时会采取猜测工作

相关问题