代码之家  ›  专栏  ›  技术社区  ›  heyBad.

如何获取javaswt表中列的值

  •  -1
  • heyBad.  · 技术社区  · 6 年前

    enter image description here

    在本例中,我希望从Column1-Column6(125022305112024523122134)中获取值,并将其总计存储在 文本框。我仍然有一个表,其中有一个复选框,当您选中它时,它将自动显示如图所示的值。我试图得到这些值,但它似乎无法与我现有的代码一起工作。

    TotalItem= 0L;
        for (x= 0; x < tblPrice.length; x++) { 
                for (int y = 0; y < tblPrice[x].getColumnCount(); y++){ //columns
                    if (tblItems[x].getItem(x).getChecked()) {
                        TotalItem = TotalItem+ Long.parseLong(tblPrice[x].getItem(y).getText());
                    }
                } 
            }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Baz    6 年前

    很难分辨出你在挣扎的是哪一部分,但我假设你没有从你想要的表中得到价值。

    你在打电话吗 TableItem#getText() ,它将为您提供该行第一列的值。 如果你想在一个特定的列获取文本,你必须调用 TableItem#getText(int)

    下面的例子应该说明这一点。它显示一个包含三列的表,当您单击一个单元格时,它将打印该单元格的值。

    public static void main(String[] args)
    {
        final Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());
    
        Table table = new Table(shell, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
    
        int cols = 3;
        for (int c = 0; c < cols; c++)
        {
            TableColumn column = new TableColumn(table, SWT.NONE);
            column.setText("Column " + c);
        }
    
        int rows = 10;
        for (int r = 0; r < rows; r++)
        {
            TableItem item = new TableItem(table, SWT.NONE);
    
            for (int c = 0; c < cols; c++)
            {
                item.setText(c, r + " " + c);
            }
        }
    
        for (int c = 0; c < cols; c++)
            table.getColumn(c).pack();
    
        table.addListener(SWT.MouseDown, e -> {
            Point pt = new Point(e.x, e.y);
            TableItem item = table.getItem(pt);
    
            if (item != null)
            {
                for (int c = 0; c < table.getColumnCount(); c++)
                {
                    Rectangle rect = item.getBounds(c);
                    if (rect.contains(pt))
                    {
                        System.out.println(item.getText(c));
                    }
                }
            }
        });
    
        shell.pack();
        shell.open();
        shell.setSize(400, 300);
    
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
        display.dispose();
    }