Path: blob/master/src/demo/share/jfc/TableExample/TableExample4.java
41149 views
/*1* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6*7* - Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9*10* - Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* - Neither the name of Oracle nor the names of its15* contributors may be used to endorse or promote products derived16* from this software without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS19* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,20* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR21* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR22* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,23* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,24* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29*/3031/*32* This source code is provided to illustrate the usage of a given feature33* or technique and has been deliberately simplified. Additional steps34* required for a production-quality application, such as security checks,35* input validation and proper error handling, might not be present in36* this sample code.37*/38394041import javax.swing.*;42import javax.swing.table.*;43import javax.swing.border.*;44import java.awt.Dimension;45import java.awt.event.WindowAdapter;46import java.awt.event.WindowEvent;47import java.awt.Color;48import java.util.logging.Level;49import java.util.logging.Logger;50import javax.swing.UIManager.LookAndFeelInfo;515253/**54* Another JTable example, showing how column attributes can be refined55* even when columns have been created automatically. Here we create some56* specialized renderers and editors as well as changing widths and colors57* for some of the columns in the SwingSet demo table.58*59* @author Philip Milne60*/61public class TableExample4 {6263public TableExample4() {64JFrame frame = new JFrame("Table");65frame.addWindowListener(new WindowAdapter() {6667@Override68public void windowClosing(WindowEvent e) {69System.exit(0);70}71});7273// Take the dummy data from SwingSet.74final String[] names = { "First Name", "Last Name", "Favorite Color",75"Favorite Number", "Vegetarian" };76final Object[][] data = {77{ "Mark", "Andrews", "Red", Integer.valueOf(2), Boolean.TRUE },78{ "Tom", "Ball", "Blue", Integer.valueOf(99), Boolean.FALSE },79{ "Alan", "Chung", "Green", Integer.valueOf(838), Boolean.FALSE },80{ "Jeff", "Dinkins", "Turquois", Integer.valueOf(8), Boolean.TRUE },81{ "Amy", "Fowler", "Yellow", Integer.valueOf(3), Boolean.FALSE },82{ "Brian", "Gerhold", "Green", Integer.valueOf(0), Boolean.FALSE },83{ "James", "Gosling", "Pink", Integer.valueOf(21), Boolean.FALSE },84{ "David", "Karlton", "Red", Integer.valueOf(1), Boolean.FALSE },85{ "Dave", "Kloba", "Yellow", Integer.valueOf(14), Boolean.FALSE },86{ "Peter", "Korn", "Purple", Integer.valueOf(12), Boolean.FALSE },87{ "Phil", "Milne", "Purple", Integer.valueOf(3), Boolean.FALSE },88{ "Dave", "Moore", "Green", Integer.valueOf(88), Boolean.FALSE },89{ "Hans", "Muller", "Maroon", Integer.valueOf(5), Boolean.FALSE },90{ "Rick", "Levenson", "Blue", Integer.valueOf(2), Boolean.FALSE },91{ "Tim", "Prinzing", "Blue", Integer.valueOf(22), Boolean.FALSE },92{ "Chester", "Rose", "Black", Integer.valueOf(0), Boolean.FALSE },93{ "Ray", "Ryan", "Gray", Integer.valueOf(77), Boolean.FALSE },94{ "Georges", "Saab", "Red", Integer.valueOf(4), Boolean.FALSE },95{ "Willie", "Walker", "Phthalo Blue", Integer.valueOf(4), Boolean.FALSE },96{ "Kathy", "Walrath", "Blue", Integer.valueOf(8), Boolean.FALSE },97{ "Arnaud", "Weber", "Green", Integer.valueOf(44), Boolean.FALSE }98};99100// Create a model of the data.101@SuppressWarnings("serial")102TableModel dataModel = new AbstractTableModel() {103// These methods always need to be implemented.104105public int getColumnCount() {106return names.length;107}108109public int getRowCount() {110return data.length;111}112113public Object getValueAt(int row, int col) {114return data[row][col];115}116117// The default implementations of these methods in118// AbstractTableModel would work, but we can refine them.119@Override120public String getColumnName(int column) {121return names[column];122}123124@Override125public Class<?> getColumnClass(int c) {126return getValueAt(0, c).getClass();127}128129@Override130public boolean isCellEditable(int row, int col) {131return true;132}133134@Override135public void setValueAt(Object aValue, int row, int column) {136System.out.println("Setting value to: " + aValue);137data[row][column] = aValue;138}139};140141// Create the table142JTable tableView = new JTable(dataModel);143// Turn off auto-resizing so that we can set column sizes144// programmatically. In this mode, all columns will get their preferred145// widths, as set blow.146tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);147148// Create a combo box to show that you can use one in a table.149JComboBox<String> comboBox = new JComboBox<>();150comboBox.addItem("Red");151comboBox.addItem("Orange");152comboBox.addItem("Yellow");153comboBox.addItem("Green");154comboBox.addItem("Blue");155comboBox.addItem("Indigo");156comboBox.addItem("Violet");157158TableColumn colorColumn = tableView.getColumn("Favorite Color");159// Use the combo box as the editor in the "Favorite Color" column.160colorColumn.setCellEditor(new DefaultCellEditor(comboBox));161162// Set a pink background and tooltip for the Color column renderer.163DefaultTableCellRenderer colorColumnRenderer =164new DefaultTableCellRenderer();165colorColumnRenderer.setBackground(Color.pink);166colorColumnRenderer.setToolTipText("Click for combo box");167colorColumn.setCellRenderer(colorColumnRenderer);168169// Set a tooltip for the header of the colors column.170TableCellRenderer headerRenderer = colorColumn.getHeaderRenderer();171if (headerRenderer instanceof DefaultTableCellRenderer) {172((DefaultTableCellRenderer) headerRenderer).setToolTipText(173"Hi Mom!");174}175176// Set the width of the "Vegetarian" column.177TableColumn vegetarianColumn = tableView.getColumn("Vegetarian");178vegetarianColumn.setPreferredWidth(100);179180// Show the values in the "Favorite Number" column in different colors.181TableColumn numbersColumn = tableView.getColumn("Favorite Number");182@SuppressWarnings("serial")183DefaultTableCellRenderer numberColumnRenderer184= new DefaultTableCellRenderer() {185186@Override187public void setValue(Object value) {188int cellValue = (value instanceof Number) ? ((Number) value).189intValue() : 0;190setForeground((cellValue > 30) ? Color.black : Color.red);191setText((value == null) ? "" : value.toString());192}193};194numberColumnRenderer.setHorizontalAlignment(JLabel.RIGHT);195numbersColumn.setCellRenderer(numberColumnRenderer);196numbersColumn.setPreferredWidth(110);197198// Finish setting up the table.199JScrollPane scrollpane = new JScrollPane(tableView);200scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED));201scrollpane.setPreferredSize(new Dimension(430, 200));202frame.getContentPane().add(scrollpane);203frame.pack();204frame.setVisible(true);205}206207public static void main(String[] args) {208// Trying to set Nimbus look and feel209try {210for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {211if ("Nimbus".equals(info.getName())) {212UIManager.setLookAndFeel(info.getClassName());213break;214}215}216} catch (Exception ex) {217Logger.getLogger(TableExample4.class.getName()).log(Level.SEVERE,218"Failed to apply Nimbus look and feel", ex);219}220221new TableExample4();222}223}224225226