德克云技术联盟

标题: SWT 同步输入框滚动条位置 [打印本页]

作者: 李昭    时间: 2015-3-30 16:06
标题: SWT 同步输入框滚动条位置
编写DFMsg客户管理端,需要两个框子,左边显示行号,右边显示报文内容。当左右两边任意一边的行发生变化,需要同步另一边输入框的行位置。截图如下:



怎么做呢?

首先页面初始化输入框,将其定位:

        textLeft = new Text(composite_2, SWT.BORDER| SWT.V_SCROLL | SWT.WRAP);
        textLeft.setBounds(3,25,60, 400);
        textLeft.setEditable(false);

        textRight = new Text(composite_2, SWT.BORDER| SWT.V_SCROLL | SWT.WRAP);
        textRight.setBounds(65,25,composite_2.getBounds().width-68, 400);

给textRight添加输入内容改变的事件,事件动作里面是给左边的框子里面增加行号,另外,每次输入后同步左右两边的显示位置:
textRight.addKeyListener(textRightModify);
private KeyListener textRightModify=new KeyListener() {

        @Override
        public void keyPressed(KeyEvent arg0) {
            int rightLineCount=textRight.getLineCount();
            int leftLineCount=textLeft.getLineCount();
            StringBuilder str=new StringBuilder();
            for(int k=0;k<rightLineCount;k++){
                str.append((k+1)+"\r\n");
            }
            textLeft.setText(str.toString());
            //获取输入框滚动的值
            int h=textRight.getTopPixel();
            int lineheight=textRight.getLineHeight();
            textLeft.setTopIndex(h/lineheight);
        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub
            
        }
};

然后对textRight的滚动条添加事件及动作:
ScrollBar hBar= textRight.getVerticalBar();
hBar.addSelectionListener(textRightDrag2);

private SelectionListener textRightDrag2=new SelectionListener() {
        
        @Override
        public void widgetSelected(SelectionEvent arg0) {
            int h=textRight.getTopPixel();
            int lineheight=textRight.getLineHeight();
            textLeft.setTopIndex(h/lineheight);
        }
        
        @Override
        public void widgetDefaultSelected(SelectionEvent arg0) {
            // TODO Auto-generated method stub
            
        }
    };

最后,对行号的输入框滚动条也加上事件及动作:

textLeft.getVerticalBar().addSelectionListener(textRightDrag1);
private SelectionListener textRightDrag1=new SelectionListener() {
        
        @Override
        public void widgetSelected(SelectionEvent arg0) {
            int h=textLeft.getTopPixel();
            int lineheight=textLeft.getLineHeight();
            textRight.setTopIndex(h/lineheight);
        }
        
        @Override
        public void widgetDefaultSelected(SelectionEvent arg0) {
            // TODO Auto-generated method stub
            
        }
    };






欢迎光临 德克云技术联盟 (http://www.decoclouds.com/)