使用 Nimbus 外观在 JTable 中水平滚动

Mat*_*w D 5 java swing jtable horizontal-scrolling nimbus

我有一个 JTable,它比它所包含的 JScrollPane 更宽(基本上是这样定义的):

JTable table = new JTable(model);
// I change some things like disallowing reordering, resizing,
// disable column selection, etc.

// I set the default renderer to a DefaultTableCellRenderer
// getTableCellRendererComponent, and then changes the color
// of the cell text depending on the cell value

JPanel panel = new JPanel(new BorderLayout(0, 5));
panel.add(new JScrollPane(table), BorderLayout.CENTER);
// add other stuff to the panel
this.add(panel,  BorderLayout.CENTER);
Run Code Online (Sandbox Code Playgroud)

在我将外观从默认更改为 Nimbus 之前,我能够在 JTable 中左右滚动。(我喜欢 Mac LaF,但 Windows 不支持它,我认为 Windows LaF 很丑),

我直接从 Java 教程中获取了以下代码:

try {
    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
} catch (Exception e) {
    // If Nimbus is not available, you can set the GUI to another look
    // and feel.
}
Run Code Online (Sandbox Code Playgroud)

我重新编译并运行了代码,而没有更改上面的任何表定义内容,而且我无法再在 JTable 中水平滚动。

我似乎无法找到任何会导致这种情况的信息。这是 Nimbus 的正常行为,还是我可以改变它?如果是这样,如何?还是我应该尝试不同的外观和感觉?

编辑:

我发现了两件事:

  1. 我创建了一个扩展 JTable 的新类来测试这个。我getScrollableUnitIncrement从 JTable 源中复制了 的代码,并添加了打印语句。传递的方向似乎总是SwingConstants.VERTICAL,而在默认的外观(Mac Aqua 或其他)中,水平和垂直滚动都有效。我不知道这是为什么。

  2. 该项目的另一部分也依赖于水平滚动。我用两个 LaF 对其进行了测试,默认情况下它运行良好,但 Nimbus 也不允许我水平滚动。

这可能是 Nimbus 的错误吗?

无论哪种方式,我想我都会使用不同的外观......

编辑#2:

我之前应该提到过这一点。我能够在窗口滚动条水平滚动,而不是与我的鼠标我的触控板或滚轮。

Nic*_*ppe 1

根据您提供的信息,我无法重现您的问题(因此无法帮助您找出问题所在)。这是一个适合我的 sscce。你能用这个例子重现这个问题吗?也许问题是从应用程序的不同部分传来的。

public static void main(String[] args){
    try {
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (Exception e) {
        // If Nimbus is not available, you can set the GUI to another look and feel.
    }

    //Create Frame
    JFrame frame = new JFrame("Title");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create Table
    JTable table = new JTable(0, 2);
    ((DefaultTableModel) table.getModel()).addRow(new Object[]{"Sample Text", "Hi Mom!"});
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    // Wrap table in Scroll pane and add to frame
    frame.add(new JScrollPane(table), BorderLayout.CENTER);

    // Finish setting up the frame and display
    frame.setBounds(0, 0, 600,400);
    frame.setPreferredSize(new Dimension(600, 400));
    frame.pack();       
    frame.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)