// 表格列根据内容调整大小 public static void adjustTableColumnWidths(JTable table) { JTableHeader header = table.getTableHeader(); // 表头 int rowCount = table.getRowCount(); // 表格的行数 TableColumnModel cm = table.getColumnModel(); // 表格的列模型 for (int i = 0; i < cm.getColumnCount(); i++) { // 循环处理每一列 TableColumn column = cm.getColumn(i); // 第i个列对象 int width = (int) header .getDefaultRenderer() .getTableCellRendererComponent(table, column.getIdentifier(), false, false, -1, i) .getPreferredSize() .getWidth(); // 用表头的绘制器计算第i列表头的宽度 for (int row = 0; row < rowCount; row++) { // 循环处理第i列的每一行,用单元格绘制器计算第i列第row行的单元格度 int preferedWidth = (int) table .getCellRenderer(row, i) .getTableCellRendererComponent( table, table.getValueAt(row, i), false, false, row, i) .getPreferredSize() .getWidth(); width = Math.max(width, preferedWidth); // 取最大的宽度 } column.setPreferredWidth(width + table.getIntercellSpacing().width); // 设置第i列的首选宽度 } table.doLayout(); // 按照刚才设置的宽度重新布局各个列 }
/** Creates new form OutSideBook */ public OutSideBook() { initComponents(); model3 = (DefaultTableModel) tblBook3.getModel(); JTableHeader jtableHeader = tblBook3.getTableHeader(); DefaultTableCellRenderer rend = (DefaultTableCellRenderer) tblBook3.getTableHeader().getDefaultRenderer(); rend.setHorizontalAlignment(JLabel.CENTER); jtableHeader.setDefaultRenderer(rend); // Tablomuzun Hücrelerini hizalıyoruz... DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); centerRenderer.setHorizontalAlignment(JLabel.CENTER); tblBook3.getColumnModel().getColumn(0).setCellRenderer(centerRenderer); tblBook3.getColumnModel().getColumn(1).setCellRenderer(centerRenderer); tblBook3.getColumnModel().getColumn(2).setCellRenderer(centerRenderer); tblBook3.getColumnModel().getColumn(3).setCellRenderer(centerRenderer); tblBook3.getColumnModel().getColumn(4).setCellRenderer(centerRenderer); tblBook3.getColumnModel().getColumn(5).setCellRenderer(centerRenderer); // Tablomuzun sütünlarının genişliğini ayarlıyoruz... tblBook3.setAutoResizeMode(tblBook3.AUTO_RESIZE_OFF); tblBook3.getColumnModel().getColumn(0).setPreferredWidth(65); tblBook3.getColumnModel().getColumn(1).setPreferredWidth(120); tblBook3.getColumnModel().getColumn(2).setPreferredWidth(106); tblBook3.getColumnModel().getColumn(3).setPreferredWidth(45); tblBook3.getColumnModel().getColumn(4).setPreferredWidth(65); tblBook3.getColumnModel().getColumn(5).setPreferredWidth(140); tabloDoldur3(); }
private static void setupTable(JTable table, Project project) { new TableSpeedSearch(table); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.addMouseListener(new MetricTableMouseListener(project, table)); final JTableHeader tableHeader = table.getTableHeader(); tableHeader.addMouseListener(new MetricTableHeaderMouseListener(project, table)); }
public void testEmptyHeader() { fFrame = new JFrame("Test Window"); // Create a panel to hold all other components JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); // Create a new table instance MyTableModel myModel = new MyTableModel(); fTable = new JTable(myModel); // Add the table to a scrolling pane JScrollPane scrollPane = new JScrollPane(fTable); topPanel.add(scrollPane, BorderLayout.CENTER); fFrame.getContentPane().setLayout(new BorderLayout()); fFrame.getContentPane().add(BorderLayout.CENTER, topPanel); fFrame.setSize(400, 450); fFrame.setLocation(20, 20); fFrame.setVisible(true); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } JTableHeader header = fTable.getTableHeader(); assertTrue( "JTableHeader greater than 5 pixels tall with empty string first element.", header.getSize().height > 5); fFrame.setVisible(false); fFrame.dispose(); }
/** Erzeugt die Tabelle für die Anzeige der Medien. */ private void erzeugeMedienTable() { JScrollPane medienAuflisterScrollPane = new JScrollPane(); medienAuflisterScrollPane.setBorder( BorderFactory.createTitledBorder( null, "Medien", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, UIConstants.HEADER_FONT)); medienAuflisterScrollPane.setBackground(UIConstants.BACKGROUND_COLOR); medienAuflisterScrollPane.getVerticalScrollBar().setBackground(UIConstants.BACKGROUND_COLOR); medienAuflisterScrollPane.getHorizontalScrollBar().setBackground(UIConstants.BACKGROUND_COLOR); _ausleiheMedienTableModel = new MedienverwaltungMedienTableModel(); _medienTable = new JTable(); _medienTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); medienAuflisterScrollPane.setViewportView(_medienTable); _medienTable.setModel(_ausleiheMedienTableModel); JTableHeader tableHeader = _medienTable.getTableHeader(); tableHeader.setFont(UIConstants.HEADER_FONT); tableHeader.setReorderingAllowed(false); tableHeader.setResizingAllowed(false); _medienTable.setFont(UIConstants.TEXT_FONT); _hauptPanel.add(medienAuflisterScrollPane, BorderLayout.CENTER); }
@Override public Dimension getPreferredSize() { if (scrollable == null) { return super.getPreferredSize(); } else { int width = super.getPreferredSize().width; int height = ((JComponent) scrollable).getPreferredSize().height; // the list view has some weird rendering sometimes (double space after last result) // so don't fill full screen on list view if ((scrollable instanceof ListViewTable)) { // old check, if sponsored results aren't showing properlly revert to just using this if (sponsoredResultsPanel.isVisible()) { height = Math.max(height, sponsoredResultsPanel.getPreferredSize().height); } } else { // classic view int headerHeight = 0; // the table headers aren't being set on the scrollpane, so if its visible check its // height and subtract it from the viewport size JTableHeader header = ((JTable) scrollable).getTableHeader(); if (header != null && header.isShowing()) { headerHeight = header.getHeight(); } // if the height of table is less than the scrollPane height, set preferred height // to same size as scrollPane if (height < scrollPane.getSize().height - headerHeight) { height = scrollPane.getSize().height - headerHeight; } } return new Dimension(width, height); } }
public void mouseClicked(MouseEvent e) { JTableHeader h = (JTableHeader) e.getSource(); TableColumnModel columnModel = h.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = columnModel.getColumn(viewColumn).getModelIndex(); if (column != -1) { sorting_column = column; // 0 == priority icon column // 4 == priority text column if (column == 0) sorting_column = 4; if (e.isControlDown()) sorting_column = -1; else opposite = !opposite; TaskTable treetable = ((TaskTable) h.getTable()); // java.util.Collection expanded = treetable.getExpandedTreeNodes(); treetable.tableChanged(); // treetable.setExpandedTreeNodes(expanded); // h.updateUI(); h.resizeAndRepaint(); } }
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { int index = -1; int direction = 0; if (table != null) { if (table.getModel() instanceof ISorterFilterTableModel) { ISorterFilterTableModel model = (ISorterFilterTableModel) table.getModel(); index = table.convertColumnIndexToView(model.getSortColumn()); direction = model.getSortDirection(); } JTableHeader header = table.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); } } setIcon( col == index && direction != ISorterFilterTableModel.NONE ? new SortArrowIcon(direction) : null); setText((value == null) ? "" : value.toString()); setBorder(UIManager.getBorder("TableHeader.cellBorder")); return this; }
/** TableCellRenderer implementation */ public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // Try to set default fore- and background colors if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); AbstractTableModel model = (AbstractTableModel) table.getModel(); column = table.convertColumnIndexToModel(column); setText(model.getColumnName(column)); // set normal border setBorder(javax.swing.UIManager.getBorder("TableHeader.cellBorder")); if (m_sortmode == SortMode.ASCENDING) setIcon(m_upimage); else if (m_sortmode == SortMode.DESCENDING) setIcon(m_downimage); else // if NONE setIcon(m_emptyheaderimage); } } return this; }
/** * auto fit table columns width * * @version 1.0 * @author dinglinhui */ public void FitTableColumns(JTable myTable) { JTableHeader header = myTable.getTableHeader(); int rowCount = myTable.getRowCount(); Enumeration columns = myTable.getColumnModel().getColumns(); while (columns.hasMoreElements()) { TableColumn column = (TableColumn) columns.nextElement(); int col = header.getColumnModel().getColumnIndex(column.getIdentifier()); int width = (int) myTable .getTableHeader() .getDefaultRenderer() .getTableCellRendererComponent( myTable, column.getIdentifier(), false, false, -1, col) .getPreferredSize() .getWidth(); for (int row = 0; row < rowCount; row++) { int preferedWidth = (int) myTable .getCellRenderer(row, col) .getTableCellRendererComponent( myTable, myTable.getValueAt(row, col), false, false, row, col) .getPreferredSize() .getWidth(); width = Math.max(width, preferedWidth); } header.setResizingColumn(column); // 此行很重要 column.setWidth(width + myTable.getIntercellSpacing().width); } }
public HeaderRenderer2(JTableHeader header, final int index) { // index is the column to be modified check.setOpaque(false); check.setFont(header.getFont()); header.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { JTable table = ((JTableHeader) e.getSource()).getTable(); TableColumnModel columnModel = table.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int modelColumn = table.convertColumnIndexToModel(viewColumn); if (modelColumn == index) { check.setSelected(!check.isSelected()); TableModel m = table.getModel(); Boolean f = check.isSelected(); for (int i = 0; i < m.getRowCount(); i++) { m.setValueAt(f, i, index); } ((JTableHeader) e.getSource()).repaint(); } else { return; } } }); }
/** * Set the sounding in the table * * @param sounding the sounding * @throws RemoteException Java RMI problem * @throws VisADException problem dissecting data */ private void setupTable(Field sounding) throws VisADException, RemoteException { Set domain = sounding.getDomainSet(); CoordinateSystem cs = domain.getCoordinateSystem(); numDomainCols = domain.getDimension(); if (cs != null) { numDomainCols++; } RealType[] rangeComps = ((FunctionType) sounding.getType()).getRealComponents(); numRangeCols = rangeComps.length; columnNames = new String[numDomainCols + numRangeCols]; SetType t = (SetType) domain.getType(); Unit[] units = domain.getSetUnits(); RealTupleType rtt = t.getDomain(); RealType[] comps = rtt.getRealComponents(); columnNames[0] = makeColumnName(comps[0], units[0]); if ((cs != null)) { RealTupleType refType = cs.getReference(); RealType[] refComps = refType.getRealComponents(); Unit[] refUnits = cs.getReferenceUnits(); columnNames[1] = makeColumnName(refComps[0], refUnits[0]); } // set for default for (int i = 0; i < rangeComps.length; i++) { columnNames[numDomainCols + i] = makeColumnName(rangeComps[i], rangeComps[i].getDefaultUnit()); } // wind if (rangeComps.length > 2) { csUnits = new Unit[] {rangeComps[2].getDefaultUnit(), rangeComps[3].getDefaultUnit()}; haveUV = (Unit.canConvert(csUnits[0], CommonUnit.meterPerSecond) && Unit.canConvert(csUnits[1], CommonUnit.meterPerSecond)); if (haveUV) { windTransform = new InverseCoordinateSystem( new RealTupleType(Speed.getRealType(), Direction.getRealType()), new PolarHorizontalWind.PolarCoordinateSystem( new RealTupleType(rangeComps[2], rangeComps[3]), CommonUnit.meterPerSecond, CommonUnit.degree)); } else { windTransform = new PolarHorizontalWind.PolarCoordinateSystem(csUnits[0], csUnits[1]); } } if (model == null) { model = new SoundingTableModel(); sorter = new TableSorter(model); JTableHeader header = getTableHeader(); header.setToolTipText("Click to sort"); sorter.setTableHeader(getTableHeader()); setModel(sorter); setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); setPreferredScrollableViewportSize(new Dimension(400, 200)); getTableHeader().setReorderingAllowed(false); } }
/** * Calculates the optimal width for the header of the given table. The calculation is based on the * preferred width of the header renderer. * * @param table the table to calculate the column width * @param col the column to calculate the widths * @return the width, -1 if error */ public static int calcHeaderWidth(JTable table, int col) { if (table == null) return -1; if (col < 0 || col > table.getColumnCount()) { System.out.println("invalid col " + col); return -1; } JTableHeader header = table.getTableHeader(); TableCellRenderer defaultHeaderRenderer = null; if (header != null) defaultHeaderRenderer = header.getDefaultRenderer(); TableColumnModel columns = table.getColumnModel(); TableModel data = table.getModel(); TableColumn column = columns.getColumn(col); int width = -1; TableCellRenderer h = column.getHeaderRenderer(); if (h == null) h = defaultHeaderRenderer; if (h != null) { // Not explicitly impossible Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, col); width = c.getPreferredSize().width + 5; } return width; }
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); // Inherit the colors and font from the header component if (bookTable_ != null) { JTableHeader header = bookTable_.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); } } if (value instanceof JLabel) { setIcon(((JLabel) value).getIcon()); setText(((JLabel) value).getText()); } else { setText((value == null) ? "" : value.toString()); setIcon(null); } setBorder(UIManager.getBorder("TableHeader.cellBorder")); setHorizontalAlignment(JLabel.CENTER); return this; }
private void createUIComponents() { mainPanel = new DollarPanel(); graphicOfPayments = new JTable(); JTableHeader header = graphicOfPayments.getTableHeader(); header.setPreferredSize(new Dimension(graphicOfPayments.getWidth(), HEADERS_HEIGHT)); }
/** * Default constructor/Create the frame of kick player window * * @param lobby the given lobby associated with the frame * @param table the table the player current on */ public KickPlayerWindow(final ILobby lobby, final Table table) { this.setResizable(false); this.isAlwaysOnTop(); List<Player> playerList = table.getPlayers(); // get to delete the moderator from the list to make sure // the moderator doesn't kick himself playerList.remove(table.getModerator()); playerTable = new JTable(); players = new HashMap<Integer, Player>(); setTitle("Kick player"); setBounds(100, 100, 400, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JScrollPane scrollPane = new JScrollPane(playerTable); scrollPane.setBounds(10, 10, 363, 200); contentPane.add(scrollPane, BorderLayout.CENTER); model = new DefaultTableModel(); model.addColumn("ID"); model.addColumn("Display Name"); model.addColumn("Rating"); playerTable.setModel(model); playerTable.setColumnSelectionAllowed(false); playerTable.setRowSelectionAllowed(true); JTableHeader header = playerTable.getTableHeader(); header.setFont(new Font(header.getFont().getFontName(), Font.BOLD, header.getFont().getSize())); updatePlayers(playerList); JButton btnCancel = new JButton("Cancel"); btnCancel.setBounds(280, 228, 89, 23); contentPane.add(btnCancel); btnCancel.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { dispose(); } }); JButton btnKick = new JButton("Kick"); btnKick.setBounds(180, 228, 89, 23); contentPane.add(btnKick); btnKick.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { for (Integer row : playerTable.getSelectedRows()) { Player selected = players.get(model.getValueAt(row, 0)); new LeaveRequest(table, selected).send(lobby); } dispose(); } }); }
/** * Generates a JTable using results from Assessment data * * @param assessment - Assessment object */ public void makeTable(Assessment assessment) { DefaultTableModel model = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { // Disables all cells from being editable return false; } }; // Assigns column headings boolean isAnonymised = !assessment.getResults().get(0).getCandKey().contains("#"); if (isAnonymised) { model.addColumn("Name"); model.addColumn("Student Number"); } else { model.addColumn("Anon Codes"); } model.addColumn("#Ass"); model.addColumn("Module Code"); model.addColumn("Mark"); model.addColumn("Grade"); table = new JTable(model); table.setFont(new Font("Calibri", Font.BOLD, 14)); // Sets column header look JTableHeader header = table.getTableHeader(); header.setFont(new Font("Calibri", Font.BOLD, 16)); header.setBackground(Color.black); header.setForeground(Color.WHITE); // Sets cell selection to single so only one cell is selected table.setCellSelectionEnabled(true); System.out.println("Making JTable"); // Fetches first assessment and adds results data to model for (Result r : assessment.getResults()) { String name = r.getName(); if (r.getName().equals("")) { name = r.getCandKey(); } if (isAnonymised) { model.addRow( new Object[] { name, r.getCandKey(), r.getAssessment(), r.getModuleCode(), r.getMark(), r.getGrade() }); } else { model.addRow( new Object[] { r.getCandKey(), r.getAssessment(), r.getModuleCode(), r.getMark(), r.getGrade() }); } } table.setPreferredScrollableViewportSize(new Dimension(200, 300)); table.setFillsViewportHeight(true); table.setShowGrid(false); }
private void prepareComponent() { CloseEventHandler closeEventHandler = new CloseEventHandler(); addWindowListener(closeEventHandler); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel contentPanel = new JPanel(); // JPanel contentPanel = new FormDebugPanel(); contentPane.add(contentPanel, BorderLayout.CENTER); CellConstraints cc = new CellConstraints(); FormLayout layout = new FormLayout( "4dlu, d:grow, 4dlu", // columns "4dlu, p, 2dlu, fill:100dlu:grow, 4dlu, " + // rows "p, 2dlu, p, 4dlu"); // btn rows PanelBuilder contentPB = new PanelBuilder(layout, contentPanel); int columnCount = layout.getColumnCount(); int rowCount = layout.getRowCount(); JLabel label = new JLabel(Localizer.getString("MediaTypeCondEditor_ConditionToAdd")); contentPB.add(label, cc.xywh(2, 2, 1, 1)); mediaTypeModel = new MediaTypeModel(); mediaTypeTable = new JTable(mediaTypeModel); JTableHeader tableHeader = mediaTypeTable.getTableHeader(); tableHeader.setResizingAllowed(false); tableHeader.setReorderingAllowed(false); // adjust column witdh of checkbox JCheckBox box = (JCheckBox) mediaTypeTable.getDefaultRenderer(Boolean.class); TableColumn column = mediaTypeTable.getColumnModel().getColumn(0); column.setMaxWidth(box.getPreferredSize().width + 2); column.setMinWidth(box.getPreferredSize().width + 2); mediaTypeTable.getColumnModel().getColumn(1).setCellRenderer(new MediaTypeCellRenderer()); // ToolTipManager.sharedInstance().registerComponent( mediaTypeTable ); contentPB.add(new JScrollPane(mediaTypeTable), cc.xywh(2, 4, 1, 1)); // button bar contentPB.add(new JSeparator(), cc.xywh(1, rowCount - 3, columnCount, 1)); JButton okBtn = new JButton(Localizer.getString("OK")); okBtn.addActionListener(new OkBtnListener()); okBtn.setDefaultCapable(true); okBtn.setRequestFocusEnabled(true); JButton cancelBtn = new JButton(Localizer.getString("Cancel")); cancelBtn.addActionListener(closeEventHandler); JPanel btnPanel = ButtonBarFactory.buildOKCancelBar(okBtn, cancelBtn); contentPB.add(btnPanel, cc.xywh(2, rowCount - 1, columnCount - 2, 1)); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); getRootPane().setDefaultButton(okBtn); pack(); setLocationRelativeTo(getParent()); }
protected JTableHeader createDefaultTableHeader() { if (dataTableHeader == null) { dataTableHeader = new JTableHeader(getDataColumnModel()); dataTableHeader.setResizingAllowed(true); dataTableHeader.setTable(dataTable); } return (dataTableHeader); }
public void SetReceivedCount() { JTableHeader th = table.getTableHeader(); TableColumnModel tcm = th.getColumnModel(); TableColumn tc = tcm.getColumn(1); String ttt = String.format("Recd : %d [GT : %d]", TotalReceived, MRKaddtodb.GrandTotal); tc.setHeaderValue(ttt); th.repaint(); }
public void initHeaderTooltips() { ColumnHeaderToolTips tips = new ColumnHeaderToolTips(); for (int c = 0; c < jTablePlayers.getColumnCount(); c++) { String tooltipText = ""; switch (c) { case 0: tooltipText = "<HTML><b>The flag the user has assigned to his profile</b>" + "<br>You can assign the flag in the connect to server dialog window"; break; case 1: tooltipText = "<HTML><b>Name of the user</b>" + "<br>(the number behind the header text is the number of currently connected users to the server)"; break; case 2: tooltipText = "<HTML><b>Number of matches the user played so far</b>" + "<br>Q = number of matches quit" + "<br>I = number of matches lost because of idle timeout" + "<br>T = number of matches lost because of match timeout"; break; case 3: tooltipText = "<HTML><b>Percent-Ratio of matches played related to matches quit</b>" + "<br>this calculation does not include tournament matches"; break; case 4: tooltipText = "<HTML><b>Number of tournaments the user played so far</b>" + "<br>D = number of tournaments left during draft phase" + "<br>C = number of tournaments left during constructing phase" + "<br>R = number of tournaments left during rounds"; break; case 5: tooltipText = "<HTML><b>Percent-Ratio of tournament matches played related to tournament matches quit</b>" + "<br>this calculation does not include non tournament matches"; break; case 6: tooltipText = "<HTML><b>Current activities of the player</b>" + "<BR>the header itself shows the number of currently active games" + "<BR>T: = number of games threads " + "<BR><i>(that can vary from active games because of sideboarding or crashed games)</i>" + "<BR>limt: the maximum of games the server is configured to" + "<BR><i>(if the number of started games exceed that limit, the games have to wait" + "<BR>until active games end)</i>"; break; case 7: tooltipText = "<HTML><b>Latency of the user's connection to the server</b>"; break; } tips.setToolTip(c, tooltipText); } JTableHeader header = jTablePlayers.getTableHeader(); header.addMouseMotionListener(tips); }
/** Initialisation of the UI. */ private void initUI() { JPanel contentPane = (JPanel) getContentPane(); contentPane.setLayout(new BorderLayout()); // Add the menuBar. menuBar = new JMenuBar(); setJMenuBar(menuBar); // Create the File menu. fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); menuBar.add(fileMenu); // Name of the spectrum. SplatName splatName = new SplatName(specData); TitledBorder splatTitle = BorderFactory.createTitledBorder("Spectrum:"); splatName.setBorder(splatTitle); // Goes at the top of window. add(splatName, BorderLayout.NORTH); // Create the table. table = new PrintableJTable(); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setIntercellSpacing(new Dimension(6, 3)); table.setRowSelectionAllowed(true); table.setColumnSelectionAllowed(false); JTableHeader header = table.getTableHeader(); header.setUpdateTableInRealTime(false); JScrollPane scrollPane = new JScrollPane(table); TitledBorder scrollTitle = BorderFactory.createTitledBorder("FITS headers:"); scrollPane.setBorder(scrollTitle); // Goes in the center and takes any extra space. add(scrollPane, BorderLayout.CENTER); // Action bar uses a BoxLayout and is placed at the south. JPanel actionBar = new JPanel(); actionBar.setLayout(new BoxLayout(actionBar, BoxLayout.X_AXIS)); actionBar.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); add(actionBar, BorderLayout.SOUTH); // Print the headers. PrintAction printAction = new PrintAction(); fileMenu.add(printAction).setMnemonic(KeyEvent.VK_P); // Add an action to close the window (appears in File menu and action // bar). CloseAction closeAction = new CloseAction(); fileMenu.add(closeAction).setMnemonic(KeyEvent.VK_C); JButton closeButton = new JButton(closeAction); actionBar.add(Box.createGlue()); actionBar.add(closeButton); actionBar.add(Box.createGlue()); }
/** * Constructs with the specified initial table * * @param table the instance of JTable */ public RowHeaderTableCellRenderer(JTable table) { header = table.getTableHeader(); setOpaque(true); setBorder(UIManager.getBorder("TableHeader.cellBorder")); // setHorizontalAlignment(CENTER); setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); }
RowHeaderRenderer(JTable table) { JTableHeader header = table.getTableHeader(); setOpaque(true); setBorder(BorderFactory.createLineBorder(Color.black)); setHorizontalAlignment(LEFT); setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(app.getPlainFont()); }
/** * Paint cells. * * @param context DOCUMENT ME! * @param g DOCUMENT ME! * @param rMin DOCUMENT ME! * @param rMax DOCUMENT ME! * @param cMin DOCUMENT ME! * @param cMax DOCUMENT ME! */ private void paintCells( SeaGlassContext context, Graphics g, int rMin, int rMax, int cMin, int cMax) { JTableHeader header = table.getTableHeader(); TableColumn draggedColumn = (header == null) ? null : header.getDraggedColumn(); TableColumnModel cm = table.getColumnModel(); int columnMargin = cm.getColumnMargin(); Rectangle cellRect; TableColumn aColumn; int columnWidth; if (table.getComponentOrientation().isLeftToRight()) { for (int row = rMin; row <= rMax; row++) { cellRect = table.getCellRect(row, cMin, false); for (int column = cMin; column <= cMax; column++) { aColumn = cm.getColumn(column); columnWidth = aColumn.getWidth(); cellRect.width = columnWidth - columnMargin; if (aColumn != draggedColumn) { paintCell(context, g, cellRect, row, column); } cellRect.x += columnWidth; } } } else { for (int row = rMin; row <= rMax; row++) { cellRect = table.getCellRect(row, cMin, false); aColumn = cm.getColumn(cMin); if (aColumn != draggedColumn) { columnWidth = aColumn.getWidth(); cellRect.width = columnWidth - columnMargin; paintCell(context, g, cellRect, row, cMin); } for (int column = cMin + 1; column <= cMax; column++) { aColumn = cm.getColumn(column); columnWidth = aColumn.getWidth(); cellRect.width = columnWidth - columnMargin; cellRect.x -= columnWidth; if (aColumn != draggedColumn) { paintCell(context, g, cellRect, row, column); } } } } // Paint the dragged column if we are dragging. if (draggedColumn != null) { paintDraggedArea(context, g, rMin, rMax, draggedColumn, header.getDraggedDistance()); } // Remove any renderers that may be left in the rendererPane. rendererPane.removeAll(); }
/** * This method initializes jTable * * @return javax.swing.JTable */ JTable getJTable() { if (jTable == null) { Event event = new Event(); AdministrateEventController controller = new AdministrateEventController(); event = controller.processRetrieve(); int colWidth = 100; Object[] colNames = {"Event ID", "Event Date", "Event Time", "Event Name", "Status"}; Object[][] data = new Object[event.getEventID_list().size()][colSize]; for (int i = 0; i < event.getEventID_list().size(); i++) { data[i][0] = event.getEventID_list().get(i); data[i][1] = controller.calendarToString(event.getEventDate_list().get(i)); data[i][2] = event.getEventTime_list().get(i); data[i][3] = event.getEventName_list().get(i); data[i][4] = event.getEventStatus_list().get(i); } model.setDataVector(data, colNames); jTable = new JTable(model); if (viewModel != null) { jTable.setModel(viewModel); viewModel = null; } jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int i = 0; i < colSize; i++) { jTable.getColumnModel().getColumn(i).setCellRenderer(new Renderer()); jTable.getColumnModel().getColumn(i).setPreferredWidth(colWidth); } jTable.getColumnModel().getColumn(3).setPreferredWidth(250); jTable.getColumnModel().getColumn(4).setPreferredWidth(172); jTable.setAutoCreateColumnsFromModel(false); sortAllRowsBy(model, 0, true); jTable.setEnabled(false); JTableHeader header = jTable.getTableHeader(); header.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e) { JTableHeader h = (JTableHeader) e.getSource(); int nColumn = h.columnAtPoint(e.getPoint()); if (nColumn != -1) sortAllRowsBy(model, nColumn, true); } }); etbml = new EventTableButtonMouseListener(jTable, source, crudFf); etbml.setSelection(selection); jTable.addMouseListener(etbml); } return jTable; }
/** Fills in the top right corner if a scrollbar appears with an empty table header. */ protected void configureEnclosingScrollPane() { JTableHeader th = new JTableHeader(); th.setDefaultRenderer(new TableCellHeaderRenderer()); // Put a dummy header in the upper-right corner. final Component renderer = th.getDefaultRenderer().getTableCellRendererComponent(null, "", false, false, -1, -1); JPanel cornerComponent = new JPanel(new BorderLayout()); cornerComponent.add(renderer, BorderLayout.CENTER); scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, cornerComponent); }
public void tablasmodelos(final JTable pane, final JPanel panel) { JTableHeader jtableHeader = pane.getTableHeader(); jtableHeader.setDefaultRenderer(new HeaderCellRenderer()); pane.setTableHeader(jtableHeader); jtableHeader.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { base = (DefaultTableModel) pane.getModel(); sortColumn = pane.getSelectedColumn(); int size = base.getRowCount(); row = new int[size]; for (int i = 0; i < size; i++) { row[i] = i; } for (int i = 1; i < row.length; i++) { int j = i; while (j > 0 && compare(j - 1, j) > 0) { int temp = row[j]; row[j] = row[j - 1]; row[j - 1] = temp; j--; } } ArrayList cd = new ArrayList(); for (int i = 0; i < row.length; i++) { cd.add(((Vector) base.getDataVector().elementAt(row[i]))); } while (base.getRowCount() != 0) { base.removeRow(0); } for (int i = 0; i < row.length; i++) { base.addRow(((Vector) cd.get(i)).toArray()); } pane.setModel(base); pane.repaint(); panel.validate(); panel.repaint(); getContentPane().repaint(); } }); }
/** * Implemented to pass the event to the original only if the mouseX doesn't lead to dragging the * column over the first. */ @Override public void mouseDragged(MouseEvent e) { TableColumn dragged = header.getDraggedColumn(); // int index = getViewIndexForColumn(header.getColumnModel(), dragged); // dragged column is at second position, allow only drags to the right int indexColumn = header.getColumnModel().getColumnIndex(columnName); if (indexColumn == 1) { if (e.getX() < maxX) return; } mouseMotionDelegate.mouseDragged(e); }
private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { final Component component = e.getComponent(); if (component instanceof javax.swing.table.JTableHeader) { javax.swing.table.JTableHeader jTableHeader = (javax.swing.table.JTableHeader) component; final JTable jTable1 = jTableHeader.getTable(); getMyTableColumnSelectionPopupMenu(jTable1, e.getX()).show(component, e.getX(), e.getY()); } } }