从 JTable 到直方图 - Swing

From JTable to Histogram - Swing

我有一个包含三列的 JTable。对于每一行,我都有一个词,它的类型和出现的次数;例如在下一张图片中,字符串 "Rosing Prize" 出现了两次。

从这个 JTable 开始,我想构建一个直方图,将第一列和最后一列作为输入。第一列是柱的名称,最后一列是它的高度;当用户选择一些行时,它们会显示在直方图中。

例如,在这种情况下,我选择了 4 行:

输出是四个 J 帧:第一个只有一个条(代表第一行);在第二个 J 框架中,我有两个条(第一行和第二行);在第三个 JFrame 中,第一行、第二行和第三行有 3 个条,最后在第四个和最后一个 JFrame 中,我得到了正确的输出:

我考虑了两种解决此问题的可能性:

  1. 添加一个 Jbutton 并在按下它后在直方图中绘制选定的行
  2. 将所有 JFrame 添加到 ArrayList 并仅打印最后一个。

有没有更好的解决方案?

如果我理解你的问题,ListSelectionListener将解决你的问题。

先定义一个选择监听器:

class MySelectionListener implements ListSelectionListener {

然后将其添加到您table的选择模型中:

MySelectionListener selectionListener = new MySelectionListener();
table.getSelectionModel().addListSelectionListener(selectionListener);

编辑:

创建 MouseListener。然后将其添加到您的 table。这是一个有效的示例代码:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JTable;

public class TableTest {
    JFrame window = new JFrame();

    private TableTest() {
        createWindow();
    }

    public void createWindow() {
        Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
                { "Row2-Column1", "Row2-Column2", "Row2-Column3" },
                { "Row3-Column1", "Row3-Column2", "Row3-Column3" } };
        Object columnNames[] = { "Column One", "Column Two", "Column Three" };
        JTable table = new JTable(rowData, columnNames);
        table.addMouseListener(new SelectionListener(table));

        window.add(table);
        window.pack();
        window.setVisible(true);

    }

    public static void main(String[] args) {
        new TableTest().createWindow();
    }
}

class SelectionListener extends MouseAdapter {
    JTable table;

    public SelectionListener(JTable table) {
        this.table = table;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        int[] rows = table.getSelectedRows();

        for (int i = 0; i < rows.length; i++) {
            System.out.println(rows[i]);
        }
    }
}

I added a ListSelectionListener listener to my table model.

在你的 ListSelectionListener, update the chart's dataset only when getValueIsAdjusting() 中是 false。这将推迟更新,直到选择稳定。