开发者

Is it possible to switch off word wraping in JTable?

开发者 https://www.devze.com 2023-02-14 23:02 出处:网络
I have a JTable Component. In one column I ins开发者_如何学Cert HTML code and if a line in this column is longer than column width, the text is wrapped. Is it possible to switch off wrap?

I have a JTable Component. In one column I ins开发者_如何学Cert HTML code and if a line in this column is longer than column width, the text is wrapped. Is it possible to switch off wrap?

@sandlex

public Object getValueAt(int row, int col) {
            return new String(
                    "<html>dgdfsgsdfg dfgdsfg sdfgs dfgsdfgsdfgsdfgsd afsdf asdfasd</html>");
        }

Check your code with this function. It will display text in few lines - not in one.


Is it possible to take a look at your code?

For example in this simplest example nothing is wrapped:

public class TableTest {

    public static void main(String[] args) {
        JFrame frm = new JFrame();

        TableModel dataModel = new AbstractTableModel() {

            public int getColumnCount() {
                return 10;
            }

            public int getRowCount() {
                return 10;
            }

            public Object getValueAt(int row, int col) {
                return new String(
                    "<a href=\"127.0.0.1\">row*col*1000000000</a>");
            }
        };

        JTable table = new JTable(dataModel);

        table.getColumnModel().getColumn(2).setMaxWidth(120);
        table.getColumnModel().getColumn(2).setPreferredWidth(120);
        table.getColumnModel().getColumn(2).setMinWidth(120);

        frm.getContentPane().add(table);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setPreferredSize(new Dimension(300, 300));
        frm.pack();
        frm.setVisible(true);

    }
}

Edited @latata You can try to create your own CellRenderer and play around with it applying to needed column:

table.getColumnModel().getColumn(0).setCellRenderer(new NonWrappedCellRenderer());

Renderer may look like this:

class NonWrappedCellRenderer extends JTextArea implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(
                    JTable table,
                    Object value,
                    boolean isSelected,
                    boolean hasFocus,
                    int row,
                    int column) {
            this.setText((String)value);
            this.setLineWrap(false);                 
            return this;
    }
}

Here line won't be wrapped cuz JTextArea by default use

setLineWrap(false)

The problem is JTextArea cannot display html tags properly as I can see. So you will solve this somehow. You can try JTextPane or something else that can deal with tags and check if this has wrapping property. Alternatively you can calculate font metrics, cell width and trim text by hands.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号