简体   繁体   中英

Scrollbars inside a JTable cell

I am trying to display HTML text inside a JTable's cell but the scrollbars arent showing up at all. Below is my code...

public class TableCellTextRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,     
        boolean hasFocus, int row, int column) {

        final JTextPane jtextPane = new JTextPane();
        JScrollPane scrollPane = new JScrollPane(jtextPane);
        scrollPane.setPreferredSize(new Dimension(350,350));
        scrollPane.setVisible(true);
        jtextPane.setEditable(false);
        jtextPane.setAutoscrolls(true);
        jtextPane.setContentType("text/html");
        jtextPane.setText(myHtmlText);
        jtextPane.setVisible(true);
        jtextPane.setPreferredSize(new Dimension(350,350));

        //this setViewPort has no effect 
        scrollPane.setViewportView(jtextPane);

        jtextPane.setVisible(true);
        scrollPane.setAutoscrolls(true);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel jpanel = new JPanel();
        jpanel.setVisible(true);
        jpanel.setPreferredSize(new Dimension(360, 360));
        jpanel.add(scrollPane);

        return jpanel;
    }
}

The scroll bars appear, but the scrolling handles dont appear. Can you please tell me what I am missing?

The table looks like this:

jTable的第一行

I'm afraid this is not going to work the way you'd want it to. The way JTables work is by obtaining a renderer component to draw the cell once, then cache it. In simplest terms, the component you're returning is basically just used to draw the cell, but it does not work the way normal components do - for instance, it does not receive events. You can use a cell editor (which will receive events), but the user would have to select the cell manually.

There are a couple of tricks you can use by installing custom mouse listeners, but this stuff will get very complicated. It'd probably be better to ask yourself if you're really looking for a JTable (as opposed to a custom layout), or if it would perhaps be possible to embed a JavaFX table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM