Example usage for javax.swing JTable AUTO_RESIZE_LAST_COLUMN

List of usage examples for javax.swing JTable AUTO_RESIZE_LAST_COLUMN

Introduction

In this page you can find the example usage for javax.swing JTable AUTO_RESIZE_LAST_COLUMN.

Prototype

int AUTO_RESIZE_LAST_COLUMN

To view the source code for javax.swing JTable AUTO_RESIZE_LAST_COLUMN.

Click Source Link

Document

During all resize operations, apply adjustments to the last column only.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Object[][] cellData = { { "1-1", "1-2" }, { "2-1", "2-2" } };
    String[] columnNames = { "col1", "col2" };

    JTable table = new JTable(cellData, columnNames);

    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
}

From source file:MainClass.java

public static void main(String args[]) {
    String rows[][] = { { "A", "a" }, { "B", "b" }, { "E", "e" } };
    String headers[] = { "Upper", "Lower" };

    final int modeKey[] = { JTable.AUTO_RESIZE_ALL_COLUMNS, JTable.AUTO_RESIZE_LAST_COLUMN,
            JTable.AUTO_RESIZE_NEXT_COLUMN, JTable.AUTO_RESIZE_OFF, JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS };

    final JTable table = new JTable(rows, headers);
    JScrollPane scrollPane = new JScrollPane(table);

    String modes[] = { "Resize All Columns", "Resize Last Column", "Resize Next Column", "Resize Off",
            "Resize Subsequent Columns" };

    final JComboBox resizeModeComboBox = new JComboBox(modes);
    int defaultMode = 4;
    table.setAutoResizeMode(modeKey[defaultMode]);
    resizeModeComboBox.setSelectedIndex(defaultMode);
    ItemListener itemListener = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int index = resizeModeComboBox.getSelectedIndex();
            table.setAutoResizeMode(modeKey[index]);
        }/*from  w  w w.j av  a2s  .  c  om*/
    };
    resizeModeComboBox.addItemListener(itemListener);

    JFrame frame = new JFrame("Resizing Table");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(resizeModeComboBox, BorderLayout.NORTH);
    frame.add(scrollPane, BorderLayout.CENTER);

    frame.setSize(300, 150);
    frame.setVisible(true);
}

From source file:ResizeTable.java

public static void main(String args[]) {

    final Object rowData[][] = { { "1", "one", "I" }, { "2", "two", "II" }, { "3", "three", "III" } };
    final String columnNames[] = { "#", "English", "Roman" };

    final JTable table = new JTable(rowData, columnNames);
    JScrollPane scrollPane = new JScrollPane(table);

    String modes[] = { "Resize All Columns", "Resize Last Column", "Resize Next Column", "Resize Off",
            "Resize Subsequent Columns" };

    final int modeKey[] = { JTable.AUTO_RESIZE_ALL_COLUMNS, JTable.AUTO_RESIZE_LAST_COLUMN,
            JTable.AUTO_RESIZE_NEXT_COLUMN, JTable.AUTO_RESIZE_OFF, JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS };

    JComboBox resizeModeComboBox = new JComboBox(modes);

    ItemListener itemListener = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            JComboBox source = (JComboBox) e.getSource();
            int index = source.getSelectedIndex();
            table.setAutoResizeMode(modeKey[index]);
        }/*from  w  w w  . j a v a 2s . co  m*/
    };
    resizeModeComboBox.addItemListener(itemListener);

    JFrame frame = new JFrame("Resizing Table");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(resizeModeComboBox, BorderLayout.NORTH);
    frame.add(scrollPane, BorderLayout.CENTER);

    frame.setSize(300, 150);
    frame.setVisible(true);

}

From source file:ResizeTable.java

public static void main(String args[]) {

    Object rowData[][] = { { "1", "one", "ichi - \u4E00", "un", "I" },
            { "2", "two", "ni - \u4E8C", "deux", "II" }, { "3", "three", "san - \u4E09", "trois", "III" },
            { "4", "four", "shi - \u56DB", "quatre", "IV" }, { "5", "five", "go - \u4E94", "cinq", "V" },
            { "6", "six", "roku - \u516D", "treiza", "VI" }, { "7", "seven", "shichi - \u4E03", "sept", "VII" },
            { "8", "eight", "hachi - \u516B", "huit", "VIII" }, { "9", "nine", "kyu - \u4E5D", "neur", "IX" },
            { "10", "ten", "ju - \u5341", "dix", "X" } };

    String columnNames[] = { "#", "English", "Japanese", "French", "Roman" };

    final JTable table = new JTable(rowData, columnNames);
    JScrollPane scrollPane = new JScrollPane(table);

    String modes[] = { "Resize All Columns", "Resize Last Column", "Resize Next Column", "Resize Off",
            "Resize Subsequent Columns" };
    final int modeKey[] = { JTable.AUTO_RESIZE_ALL_COLUMNS, JTable.AUTO_RESIZE_LAST_COLUMN,
            JTable.AUTO_RESIZE_NEXT_COLUMN, JTable.AUTO_RESIZE_OFF, JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS };
    JComboBox resizeModeComboBox = new JComboBox(modes);
    int defaultMode = 4;
    table.setAutoResizeMode(modeKey[defaultMode]);
    resizeModeComboBox.setSelectedIndex(defaultMode);
    ItemListener itemListener = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            JComboBox source = (JComboBox) e.getSource();
            int index = source.getSelectedIndex();
            table.setAutoResizeMode(modeKey[index]);
        }/* w w w.j av  a 2s  .  co  m*/
    };
    resizeModeComboBox.addItemListener(itemListener);

    JFrame frame = new JFrame("Resizing Table");
    Container contentPane = frame.getContentPane();

    contentPane.add(resizeModeComboBox, BorderLayout.NORTH);
    contentPane.add(scrollPane, BorderLayout.CENTER);

    frame.setSize(300, 150);
    frame.setVisible(true);
}

From source file:Main.java

/**
 * Resizes the columns to match content while keeping the table the same
 * size. This means that the last column may be larger than the content.
 *///from www.  j a  v  a  2  s  .c  om
public static void resizeTableColumns(JTable table) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    int totalWidth = 0;
    for (int i = 0; i < table.getColumnCount(); i++) {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
        TableColumn col = colModel.getColumn(i);

        if (i == table.getColumnCount() - 1) {
            col.setPreferredWidth(table.getWidth() - totalWidth);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
            return;
        }

        int width = 0;
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }
        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, -1,
                i);
        width = Math.max(width, comp.getPreferredSize().width);
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, i);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, i), false, false, r, i);
            width = Math.max(width, comp.getPreferredSize().width);
        }
        totalWidth += width + 2;
        col.setPreferredWidth(width + 2);
    }
}

From source file:ThreadViewer.java

public ThreadViewer() {

    JTable table = new JTable(tableModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

    TableColumnModel colModel = table.getColumnModel();
    int numColumns = colModel.getColumnCount();

    for (int i = 0; i < numColumns - 1; i++) {
        TableColumn col = colModel.getColumn(i);

        col.sizeWidthToFit();// www.  ja va 2  s.c o  m
        col.setPreferredWidth(col.getWidth() + 5);
        col.setMaxWidth(col.getWidth() + 5);
    }

    JScrollPane sp = new JScrollPane(table);

    setLayout(new BorderLayout());
    add(sp, BorderLayout.CENTER);
}

From source file:fxts.stations.util.preferences.PreferencesSheetPanel.java

/**
 * Constructor PreferencesSheetPanel./*from   w  w w .j  a  v a2 s. co  m*/
 *
 * @param aUserName parent dialog included this panel.
 */
public PreferencesSheetPanel(String aUserName) {
    mUserName = aUserName;
    try {
        mResMan = ResourceManager.getManager("fxts.stations.util.preferences.resources.Resources");
    } catch (Exception e) {
        mLogger.error("The fatal error");
        e.printStackTrace();
    }
    mResMan.addLocaleListener(this);

    //Define table
    mTableModel = new PrefTableModel();
    mTable = new AAJTable(mTableModel);
    mTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    PreferencesTableCellRenderer renderer = new PreferencesTableCellRenderer();
    mTable.setDefaultRenderer(AValueEditorPanel.class, renderer);
    mEditor = new PreferencesTableCellEditor();
    mTable.setDefaultEditor(AValueEditorPanel.class, mEditor);
    //Do not change columns order
    mTable.getTableHeader().setReorderingAllowed(false);
    //Assign exterior a table
    mTable.setBorder(new EtchedBorder());
    //Prepare to used Escape key
    mDefaultEditingCancelAction = SwingUtilities.getUIActionMap(mTable).get("cancel");
    AbstractAction exitAction = new AbstractAction() {
        /**
         * Invoked when an action occurs.
         */
        public void actionPerformed(ActionEvent aEvent) {
            if (mEditor.isEditing()) {
                mEditor.cancelCellEditing();
                if (mDefaultEditingCancelAction != null) {
                    mDefaultEditingCancelAction.actionPerformed(aEvent);
                }
            } else {
                mDefaultExitAction.actionPerformed(aEvent);
            }
        }
    };
    KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    mTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, "ExitAction");
    SwingUtilities.getUIActionMap(mTable).put("ExitAction", exitAction);
    super.setViewportView(mTable);
}

From source file:de.tntinteractive.portalsammler.gui.DocumentTable.java

public DocumentTable(final Gui gui, final SecureStore store) {
    this.gui = gui;
    this.store = store;

    this.table = new JTable();
    this.table.setRowSelectionAllowed(true);
    this.refreshContents();
    this.table.addMouseListener(new MouseAdapter() {
        @Override/*from   w  ww.jav  a 2 s  .  c  o m*/
        public void mousePressed(final MouseEvent me) {
            final int r = DocumentTable.this.table.rowAtPoint(me.getPoint());
            if (!DocumentTable.this.table.getSelectionModel().isSelectedIndex(r)) {
                if (r >= 0 && r < DocumentTable.this.table.getRowCount()) {
                    DocumentTable.this.table.setRowSelectionInterval(r, r);
                } else {
                    DocumentTable.this.table.clearSelection();
                }
            }

            if (me.isPopupTrigger()) {
                DocumentTable.this.showPopup(me);
            } else if (me.getClickCount() == 2) {
                DocumentTable.this.openSelectedRows();
            }
        }

        @Override
        public void mouseReleased(final MouseEvent me) {
            if (me.isPopupTrigger()) {
                DocumentTable.this.showPopup(me);
            }
        }
    });
    this.table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    this.table.getColumnModel().getColumn(0).setPreferredWidth(120);
    this.table.getColumnModel().getColumn(1).setPreferredWidth(80);
    this.table.getColumnModel().getColumn(2).setPreferredWidth(100);
    this.table.getColumnModel().getColumn(3).setPreferredWidth(500);
}

From source file:net.brtly.monkeyboard.plugin.ConsolePanel.java

public ConsolePanel(PluginDelegate service) {
    super(service);
    setLayout(new MigLayout("inset 5", "[grow][:100:100][24:n:24][24:n:24]", "[::24][grow]"));

    JComboBox comboBox = new JComboBox();
    comboBox.setToolTipText("Log Level");
    comboBox.setMaximumRowCount(6);//www .j a v  a2  s .  c  om
    comboBox.setModel(
            new DefaultComboBoxModel(new String[] { "Fatal", "Error", "Warn", "Info", "Debug", "Trace" }));
    comboBox.setSelectedIndex(5);
    add(comboBox, "cell 1 0,growx");

    JButton btnC = new JButton("");
    btnC.setToolTipText("Clear Buffer");
    btnC.setIcon(new ImageIcon(ConsolePanel.class.getResource("/img/clear-document.png")));
    btnC.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            logPangrams();
        }
    });
    add(btnC, "cell 2 0,wmax 24,hmax 26");

    tglbtnV = new JToggleButton("");
    tglbtnV.setToolTipText("Auto Scroll");
    tglbtnV.setIcon(new ImageIcon(ConsolePanel.class.getResource("/img/auto-scroll.png")));
    tglbtnV.setSelected(true);
    tglbtnV.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent ev) {
            if (ev.getStateChange() == ItemEvent.SELECTED) {
                _table.setAutoScroll(true);
            } else if (ev.getStateChange() == ItemEvent.DESELECTED) {
                _table.setAutoScroll(false);
            }
        }
    });

    add(tglbtnV, "cell 3 0,wmax 24,hmax 26");

    scrollPane = new JScrollPane();
    scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
        public void adjustmentValueChanged(AdjustmentEvent e) {
            // TODO figure out what to do with this event?
        }
    });

    add(scrollPane, "cell 0 1 4 1,grow");

    _table = new JLogTable("Time", "Source", "Message");

    _table.getColumnModel().getColumn(0).setMinWidth(50);
    _table.getColumnModel().getColumn(0).setPreferredWidth(50);
    _table.getColumnModel().getColumn(0).setMaxWidth(100);

    _table.getColumnModel().getColumn(1).setMinWidth(50);
    _table.getColumnModel().getColumn(1).setPreferredWidth(50);
    _table.getColumnModel().getColumn(1).setMaxWidth(100);

    _table.getColumnModel().getColumn(2).setMinWidth(50);
    _table.getColumnModel().getColumn(2).setWidth(255);

    _table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

    scrollPane.setViewportView(_table);

    _appender = new JLogTableAppender();
    _appender.setThreshold(Level.ALL);
    Logger.getRootLogger().addAppender(_appender);
}

From source file:base.BasePlayer.AddGenome.java

static void checkGenomes() {

    //DefaultMutableTreeNode
    File checkdir = Main.genomeDir, checkAnnodir;
    File[] addDir, annodir;//from www  .  j av  a  2 s . c  o  m
    root.removeAllChildren();
    int counter = 0;
    for (int i = model.getRowCount() - 1; i >= 0; i--) {
        model.removeRow(i);
    }
    for (int i = remmodel.getRowCount() - 1; i >= 0; i--) {
        remmodel.removeRow(i);
    }

    removables.clear();

    int currentlen = 0, length = 0;
    if (checkdir == null) {
        try {
            checkdir = new File(userDir + "/genomes");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    addDir = checkdir.listFiles();
    for (int f = 0; f < addDir.length; f++) {

        try {
            if (!addDir[f].isDirectory()) {
                continue;
            }
            currentlen = genometable.getFontMetrics(genometable.getFont()).stringWidth(addDir[f].getName());
            if (currentlen > length) {
                length = currentlen;
            }

            AddGenome.removables.add(addDir[f].getName());
            checkAnnodir = new File(checkdir + "/" + addDir[f].getName() + "/annotation/");
            annodir = checkAnnodir.listFiles();
            DefaultMutableTreeNode genome = new DefaultMutableTreeNode(addDir[f].getName());
            root.add(genome);
            if (annodir == null) {
                counter++;
                genome.add(new DefaultMutableTreeNode("Add new annotation..."));
            } else {
                counter += annodir.length + 3;
                for (int a = 0; a < annodir.length; a++) {
                    currentlen = genometable.getFontMetrics(genometable.getFont())
                            .stringWidth(annodir[a].getName());
                    if (currentlen > length) {
                        length = currentlen;
                    }
                    genome.add(new DefaultMutableTreeNode(annodir[a].getName()));
                }
                genome.add(new DefaultMutableTreeNode("Add new annotation..."));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (counter == 0) {
        counter = 1;
        length = genometable.getFontMetrics(genometable.getFont()).stringWidth("Add new annotation...");
    }
    counter++;
    root.add(new DefaultMutableTreeNode("Add new reference..."));
    genometable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    for (int i = 0; i < organisms.size(); i++) {
        if (!AddGenome.removables.contains(organisms.get(i))) {
            Object[] row = { organisms.get(i), "" + sizeHash.get(organisms.get(i))[0] / 1048576 };
            model.addRow(row);
            currentlen = genometable.getFontMetrics(genometable.getFont()).stringWidth(organisms.get(i));
            if (currentlen > length) {
                length = currentlen;
            }
        }
    }

    AddGenome.longestName = length;

    if (genometable.getRowCount() > 15) {
        genometable.setPreferredScrollableViewportSize((new Dimension(
                AddGenome.longestName + 20 + Main.defaultFontSize * 8, genometable.getRowHeight() * 15)));
        genometable.setMinimumSize(new Dimension(AddGenome.longestName + 20, genometable.getRowHeight() * 15));
    } else {
        genometable.setPreferredScrollableViewportSize(
                (new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8,
                        genometable.getRowHeight() * (genometable.getRowCount() + 1))));
        genometable.setMinimumSize(new Dimension(AddGenome.longestName + 20,
                genometable.getRowHeight() * (genometable.getRowCount() + 1)));
    }

    if (remtable.getRowCount() > 15) {
        remtable.setPreferredScrollableViewportSize((new Dimension(
                AddGenome.longestName + 20 + Main.defaultFontSize * 8, remtable.getRowHeight() * 15)));
    } else {
        remtable.setPreferredScrollableViewportSize(
                (new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8,
                        remtable.getRowHeight() * (remtable.getRowCount() + 1))));
    }
    //Main.defaultFontSize = 12;
    genometable.getColumnModel().getColumn(0).setPreferredWidth(AddGenome.longestName + 10);
    genometable.getColumnModel().getColumn(0).setMinWidth(AddGenome.longestName + 10);
    //   genometable.getColumnModel().getColumn(1).setPreferredWidth(Main.defaultFontSize*8);
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    model.reload();
    int rowheight = tree.getRowHeight();
    if (rowheight < 1) {
        rowheight = Main.defaultFontSize + 4;
    }

    treescroll.setPreferredSize(
            new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8, counter * rowheight));
    treescroll.setMinimumSize(
            new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8, counter * rowheight));
    remscroll.setPreferredSize(
            new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8, counter * rowheight));
    remscroll.setMinimumSize(
            new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8, counter * rowheight));
    tree.expandPath(new TreePath(root));

    setFonts(Main.menuFont);
}