Path: blob/master/src/demo/share/jfc/SwingSet2/TableDemo.java
41149 views
/*1*2* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7*8* - Redistributions of source code must retain the above copyright9* notice, this list of conditions and the following disclaimer.10*11* - Redistributions in binary form must reproduce the above copyright12* notice, this list of conditions and the following disclaimer in the13* documentation and/or other materials provided with the distribution.14*15* - Neither the name of Oracle nor the names of its16* contributors may be used to endorse or promote products derived17* from this software without specific prior written permission.18*19* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS20* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,21* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR22* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR23* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,24* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,25* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR26* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF27* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING28* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS29* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.30*/313233import javax.swing.*;34import javax.swing.event.*;35import javax.swing.text.*;36import javax.swing.table.*;37import javax.swing.border.*;38import javax.swing.colorchooser.*;39import javax.swing.filechooser.*;40import javax.accessibility.*;4142import java.awt.*;43import java.awt.event.*;44import java.awt.print.PrinterException;45import java.beans.*;46import java.util.*;47import java.io.*;48import java.applet.*;49import java.net.*;5051import java.text.MessageFormat;5253/**54* Table demo55*56* @author Philip Milne57* @author Steve Wilson58*/59public class TableDemo extends DemoModule {60JTable tableView;61JScrollPane scrollpane;62Dimension origin = new Dimension(0, 0);6364JCheckBox isColumnReorderingAllowedCheckBox;65JCheckBox showHorizontalLinesCheckBox;66JCheckBox showVerticalLinesCheckBox;6768JCheckBox isColumnSelectionAllowedCheckBox;69JCheckBox isRowSelectionAllowedCheckBox;7071JLabel interCellSpacingLabel;72JLabel rowHeightLabel;7374JSlider interCellSpacingSlider;75JSlider rowHeightSlider;7677JComboBox<String> selectionModeComboBox = null;78JComboBox<String> resizeModeComboBox = null;7980JLabel headerLabel;81JLabel footerLabel;8283JTextField headerTextField;84JTextField footerTextField;8586JCheckBox fitWidth;87JButton printButton;8889JPanel controlPanel;90JScrollPane tableAggregate;9192String path = "food/";9394final int INITIAL_ROWHEIGHT = 33;9596/**97* main method allows us to run as a standalone demo.98*/99public static void main(String[] args) {100TableDemo demo = new TableDemo(null);101demo.mainImpl();102}103104/**105* TableDemo Constructor106*/107public TableDemo(SwingSet2 swingset) {108super(swingset, "TableDemo", "toolbar/JTable.gif");109110getDemoPanel().setLayout(new BorderLayout());111controlPanel = new JPanel();112controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS));113JPanel cbPanel = new JPanel(new GridLayout(3, 2));114JPanel labelPanel = new JPanel(new GridLayout(2, 1)) {115public Dimension getMaximumSize() {116return new Dimension(getPreferredSize().width, super.getMaximumSize().height);117}118};119JPanel sliderPanel = new JPanel(new GridLayout(2, 1)) {120public Dimension getMaximumSize() {121return new Dimension(getPreferredSize().width, super.getMaximumSize().height);122}123};124JPanel comboPanel = new JPanel(new GridLayout(2, 1));125JPanel printPanel = new JPanel(new ColumnLayout());126127getDemoPanel().add(controlPanel, BorderLayout.NORTH);128Vector<JComponent> relatedComponents = new Vector<>();129130131// check box panel132isColumnReorderingAllowedCheckBox = new JCheckBox(getString("TableDemo.reordering_allowed"), true);133isColumnReorderingAllowedCheckBox.addActionListener(new ActionListener() {134public void actionPerformed(ActionEvent e) {135boolean flag = ((JCheckBox)e.getSource()).isSelected();136tableView.getTableHeader().setReorderingAllowed(flag);137tableView.repaint();138}139});140141showHorizontalLinesCheckBox = new JCheckBox(getString("TableDemo.horz_lines"), true);142showHorizontalLinesCheckBox.addActionListener(new ActionListener() {143public void actionPerformed(ActionEvent e) {144boolean flag = ((JCheckBox)e.getSource()).isSelected();145tableView.setShowHorizontalLines(flag); ;146tableView.repaint();147}148});149150showVerticalLinesCheckBox = new JCheckBox(getString("TableDemo.vert_lines"), true);151showVerticalLinesCheckBox.addActionListener(new ActionListener() {152public void actionPerformed(ActionEvent e) {153boolean flag = ((JCheckBox)e.getSource()).isSelected();154tableView.setShowVerticalLines(flag); ;155tableView.repaint();156}157});158159// Show that showHorizontal/Vertical controls are related160relatedComponents.removeAllElements();161relatedComponents.add(showHorizontalLinesCheckBox);162relatedComponents.add(showVerticalLinesCheckBox);163buildAccessibleGroup(relatedComponents);164165isRowSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.row_selection"), true);166isRowSelectionAllowedCheckBox.addActionListener(new ActionListener() {167public void actionPerformed(ActionEvent e) {168boolean flag = ((JCheckBox)e.getSource()).isSelected();169tableView.setRowSelectionAllowed(flag); ;170tableView.repaint();171}172});173174isColumnSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.column_selection"), false);175isColumnSelectionAllowedCheckBox.addActionListener(new ActionListener() {176public void actionPerformed(ActionEvent e) {177boolean flag = ((JCheckBox)e.getSource()).isSelected();178tableView.setColumnSelectionAllowed(flag); ;179tableView.repaint();180}181});182183// Show that row/column selections are related184relatedComponents.removeAllElements();185relatedComponents.add(isColumnSelectionAllowedCheckBox);186relatedComponents.add(isRowSelectionAllowedCheckBox);187buildAccessibleGroup(relatedComponents);188189cbPanel.add(isColumnReorderingAllowedCheckBox);190cbPanel.add(isRowSelectionAllowedCheckBox);191cbPanel.add(showHorizontalLinesCheckBox);192cbPanel.add(isColumnSelectionAllowedCheckBox);193cbPanel.add(showVerticalLinesCheckBox);194195196// label panel197interCellSpacingLabel = new JLabel(getString("TableDemo.intercell_spacing_colon"));198labelPanel.add(interCellSpacingLabel);199200rowHeightLabel = new JLabel(getString("TableDemo.row_height_colon"));201labelPanel.add(rowHeightLabel);202203204// slider panel205interCellSpacingSlider = new JSlider(JSlider.HORIZONTAL, 0, 10, 1);206interCellSpacingSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.intercell_spacing"));207interCellSpacingLabel.setLabelFor(interCellSpacingSlider);208sliderPanel.add(interCellSpacingSlider);209interCellSpacingSlider.addChangeListener(new ChangeListener() {210public void stateChanged(ChangeEvent e) {211int spacing = ((JSlider)e.getSource()).getValue();212tableView.setIntercellSpacing(new Dimension(spacing, spacing));213tableView.repaint();214}215});216217rowHeightSlider = new JSlider(JSlider.HORIZONTAL, 5, 100, INITIAL_ROWHEIGHT);218rowHeightSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.row_height"));219rowHeightLabel.setLabelFor(rowHeightSlider);220sliderPanel.add(rowHeightSlider);221rowHeightSlider.addChangeListener(new ChangeListener() {222public void stateChanged(ChangeEvent e) {223int height = ((JSlider)e.getSource()).getValue();224tableView.setRowHeight(height);225tableView.repaint();226}227});228229// Show that spacing controls are related230relatedComponents.removeAllElements();231relatedComponents.add(interCellSpacingSlider);232relatedComponents.add(rowHeightSlider);233buildAccessibleGroup(relatedComponents);234235236// Create the table.237tableAggregate = createTable();238getDemoPanel().add(tableAggregate, BorderLayout.CENTER);239240241// ComboBox for selection modes.242JPanel selectMode = new JPanel();243selectMode.setLayout(new BoxLayout(selectMode, BoxLayout.X_AXIS));244selectMode.setBorder(new TitledBorder(getString("TableDemo.selection_mode")));245246247selectionModeComboBox = new JComboBox<>() {248public Dimension getMaximumSize() {249return getPreferredSize();250}251};252selectionModeComboBox.addItem(getString("TableDemo.single"));253selectionModeComboBox.addItem(getString("TableDemo.one_range"));254selectionModeComboBox.addItem(getString("TableDemo.multiple_ranges"));255selectionModeComboBox.setSelectedIndex(tableView.getSelectionModel().getSelectionMode());256selectionModeComboBox.addItemListener(new ItemListener() {257public void itemStateChanged(ItemEvent e) {258JComboBox<?> source = (JComboBox<?>)e.getSource();259tableView.setSelectionMode(source.getSelectedIndex());260}261});262263selectMode.add(Box.createHorizontalStrut(2));264selectMode.add(selectionModeComboBox);265selectMode.add(Box.createHorizontalGlue());266comboPanel.add(selectMode);267268// Combo box for table resize mode.269JPanel resizeMode = new JPanel();270resizeMode.setLayout(new BoxLayout(resizeMode, BoxLayout.X_AXIS));271resizeMode.setBorder(new TitledBorder(getString("TableDemo.autoresize_mode")));272273274resizeModeComboBox = new JComboBox<>() {275public Dimension getMaximumSize() {276return getPreferredSize();277}278};279resizeModeComboBox.addItem(getString("TableDemo.off"));280resizeModeComboBox.addItem(getString("TableDemo.column_boundaries"));281resizeModeComboBox.addItem(getString("TableDemo.subsequent_columns"));282resizeModeComboBox.addItem(getString("TableDemo.last_column"));283resizeModeComboBox.addItem(getString("TableDemo.all_columns"));284resizeModeComboBox.setSelectedIndex(tableView.getAutoResizeMode());285resizeModeComboBox.addItemListener(new ItemListener() {286public void itemStateChanged(ItemEvent e) {287JComboBox<?> source = (JComboBox<?>)e.getSource();288tableView.setAutoResizeMode(source.getSelectedIndex());289}290});291292resizeMode.add(Box.createHorizontalStrut(2));293resizeMode.add(resizeModeComboBox);294resizeMode.add(Box.createHorizontalGlue());295comboPanel.add(resizeMode);296297// print panel298printPanel.setBorder(new TitledBorder(getString("TableDemo.printing")));299headerLabel = new JLabel(getString("TableDemo.header"));300footerLabel = new JLabel(getString("TableDemo.footer"));301headerTextField = new JTextField(getString("TableDemo.headerText"), 15);302footerTextField = new JTextField(getString("TableDemo.footerText"), 15);303fitWidth = new JCheckBox(getString("TableDemo.fitWidth"), true);304printButton = new JButton(getString("TableDemo.print"));305printButton.addActionListener(new ActionListener() {306public void actionPerformed(ActionEvent ae) {307printTable();308}309});310311printPanel.add(headerLabel);312printPanel.add(headerTextField);313printPanel.add(footerLabel);314printPanel.add(footerTextField);315316JPanel buttons = new JPanel();317buttons.add(fitWidth);318buttons.add(printButton);319320printPanel.add(buttons);321322// Show that printing controls are related323relatedComponents.removeAllElements();324relatedComponents.add(headerTextField);325relatedComponents.add(footerTextField);326relatedComponents.add(printButton);327buildAccessibleGroup(relatedComponents);328329// wrap up the panels and add them330JPanel sliderWrapper = new JPanel();331sliderWrapper.setLayout(new BoxLayout(sliderWrapper, BoxLayout.X_AXIS));332sliderWrapper.add(labelPanel);333sliderWrapper.add(sliderPanel);334sliderWrapper.add(Box.createHorizontalGlue());335sliderWrapper.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));336337JPanel leftWrapper = new JPanel();338leftWrapper.setLayout(new BoxLayout(leftWrapper, BoxLayout.Y_AXIS));339leftWrapper.add(cbPanel);340leftWrapper.add(sliderWrapper);341342// add everything343controlPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 2, 0));344controlPanel.add(leftWrapper);345controlPanel.add(comboPanel);346controlPanel.add(printPanel);347348setTableControllers(); // Set accessibility information349350getDemoPanel().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)351.put(KeyStroke.getKeyStroke("ctrl P"), "print");352353getDemoPanel().getActionMap().put("print", new AbstractAction() {354public void actionPerformed(ActionEvent ae) {355printTable();356}357});358359} // TableDemo()360361/**362* Sets the Accessibility MEMBER_OF property to denote that363* these components work together as a group. Each object364* is set to be a MEMBER_OF an array that contains all of365* the objects in the group, including itself.366*367* @param components The list of objects that are related368*/369void buildAccessibleGroup(Vector<JComponent> components) {370371AccessibleContext context = null;372int numComponents = components.size();373Object[] group = components.toArray();374Object object = null;375for (int i = 0; i < numComponents; ++i) {376object = components.elementAt(i);377if (object instanceof Accessible) {378context = ((Accessible)components.elementAt(i)).379getAccessibleContext();380context.getAccessibleRelationSet().add(381new AccessibleRelation(382AccessibleRelation.MEMBER_OF, group));383}384}385} // buildAccessibleGroup()386387/**388* This sets CONTROLLER_FOR on the controls that manipulate the389* table and CONTROLLED_BY relationships on the table to point390* back to the controllers.391*/392private void setTableControllers() {393394// Set up the relationships to show what controls the table395setAccessibleController(isColumnReorderingAllowedCheckBox,396tableAggregate);397setAccessibleController(showHorizontalLinesCheckBox,398tableAggregate);399setAccessibleController(showVerticalLinesCheckBox,400tableAggregate);401setAccessibleController(isColumnSelectionAllowedCheckBox,402tableAggregate);403setAccessibleController(isRowSelectionAllowedCheckBox,404tableAggregate);405setAccessibleController(interCellSpacingSlider,406tableAggregate);407setAccessibleController(rowHeightSlider,408tableAggregate);409setAccessibleController(selectionModeComboBox,410tableAggregate);411setAccessibleController(resizeModeComboBox,412tableAggregate);413} // setTableControllers()414415/**416* Sets up accessibility relationships to denote that one417* object controls another. The CONTROLLER_FOR property is418* set on the controller object, and the CONTROLLED_BY419* property is set on the target object.420*/421private void setAccessibleController(JComponent controller,422JComponent target) {423AccessibleRelationSet controllerRelations =424controller.getAccessibleContext().getAccessibleRelationSet();425AccessibleRelationSet targetRelations =426target.getAccessibleContext().getAccessibleRelationSet();427428controllerRelations.add(429new AccessibleRelation(430AccessibleRelation.CONTROLLER_FOR, target));431targetRelations.add(432new AccessibleRelation(433AccessibleRelation.CONTROLLED_BY, controller));434} // setAccessibleController()435436public JScrollPane createTable() {437438// final439final String[] names = {440getString("TableDemo.first_name"),441getString("TableDemo.last_name"),442getString("TableDemo.favorite_color"),443getString("TableDemo.favorite_movie"),444getString("TableDemo.favorite_number"),445getString("TableDemo.favorite_food")446};447448ImageIcon apple = createImageIcon("food/apple.jpg", getString("TableDemo.apple"));449ImageIcon asparagus = createImageIcon("food/asparagus.gif", getString("TableDemo.asparagus"));450ImageIcon banana = createImageIcon("food/banana.gif", getString("TableDemo.banana"));451ImageIcon broccoli = createImageIcon("food/broccoli.gif", getString("TableDemo.broccoli"));452ImageIcon cantaloupe = createImageIcon("food/cantaloupe.gif", getString("TableDemo.cantaloupe"));453ImageIcon carrot = createImageIcon("food/carrot.gif", getString("TableDemo.carrot"));454ImageIcon corn = createImageIcon("food/corn.gif", getString("TableDemo.corn"));455ImageIcon grapes = createImageIcon("food/grapes.gif", getString("TableDemo.grapes"));456ImageIcon grapefruit = createImageIcon("food/grapefruit.gif", getString("TableDemo.grapefruit"));457ImageIcon kiwi = createImageIcon("food/kiwi.gif", getString("TableDemo.kiwi"));458ImageIcon onion = createImageIcon("food/onion.gif", getString("TableDemo.onion"));459ImageIcon pear = createImageIcon("food/pear.gif", getString("TableDemo.pear"));460ImageIcon peach = createImageIcon("food/peach.gif", getString("TableDemo.peach"));461ImageIcon pepper = createImageIcon("food/pepper.gif", getString("TableDemo.pepper"));462ImageIcon pickle = createImageIcon("food/pickle.gif", getString("TableDemo.pickle"));463ImageIcon pineapple = createImageIcon("food/pineapple.gif", getString("TableDemo.pineapple"));464ImageIcon raspberry = createImageIcon("food/raspberry.gif", getString("TableDemo.raspberry"));465ImageIcon sparegrass = createImageIcon("food/asparagus.gif", getString("TableDemo.sparegrass"));466ImageIcon strawberry = createImageIcon("food/strawberry.gif", getString("TableDemo.strawberry"));467ImageIcon tomato = createImageIcon("food/tomato.gif", getString("TableDemo.tomato"));468ImageIcon watermelon = createImageIcon("food/watermelon.gif", getString("TableDemo.watermelon"));469470NamedColor aqua = new NamedColor(new Color(127, 255, 212), getString("TableDemo.aqua"));471NamedColor beige = new NamedColor(new Color(245, 245, 220), getString("TableDemo.beige"));472NamedColor black = new NamedColor(Color.black, getString("TableDemo.black"));473NamedColor blue = new NamedColor(new Color(0, 0, 222), getString("TableDemo.blue"));474NamedColor eblue = new NamedColor(Color.blue, getString("TableDemo.eblue"));475NamedColor jfcblue = new NamedColor(new Color(204, 204, 255), getString("TableDemo.jfcblue"));476NamedColor jfcblue2 = new NamedColor(new Color(153, 153, 204), getString("TableDemo.jfcblue2"));477NamedColor cybergreen = new NamedColor(Color.green.darker().brighter(), getString("TableDemo.cybergreen"));478NamedColor darkgreen = new NamedColor(new Color(0, 100, 75), getString("TableDemo.darkgreen"));479NamedColor forestgreen = new NamedColor(Color.green.darker(), getString("TableDemo.forestgreen"));480NamedColor gray = new NamedColor(Color.gray, getString("TableDemo.gray"));481NamedColor green = new NamedColor(Color.green, getString("TableDemo.green"));482NamedColor orange = new NamedColor(new Color(255, 165, 0), getString("TableDemo.orange"));483NamedColor purple = new NamedColor(new Color(160, 32, 240), getString("TableDemo.purple"));484NamedColor red = new NamedColor(Color.red, getString("TableDemo.red"));485NamedColor rustred = new NamedColor(Color.red.darker(), getString("TableDemo.rustred"));486NamedColor sunpurple = new NamedColor(new Color(100, 100, 255), getString("TableDemo.sunpurple"));487NamedColor suspectpink = new NamedColor(new Color(255, 105, 180), getString("TableDemo.suspectpink"));488NamedColor turquoise = new NamedColor(new Color(0, 255, 255), getString("TableDemo.turquoise"));489NamedColor violet = new NamedColor(new Color(238, 130, 238), getString("TableDemo.violet"));490NamedColor yellow = new NamedColor(Color.yellow, getString("TableDemo.yellow"));491492// Create the dummy data (a few rows of names)493final Object[][] data = {494{"Mike", "Albers", green, getString("TableDemo.brazil"), Double.valueOf(44.0), strawberry},495{"Mark", "Andrews", blue, getString("TableDemo.curse"), Double.valueOf(3), grapes},496{"Brian", "Beck", black, getString("TableDemo.bluesbros"), Double.valueOf(2.7182818285), raspberry},497{"Lara", "Bunni", red, getString("TableDemo.airplane"), Double.valueOf(15), strawberry},498{"Roger", "Brinkley", blue, getString("TableDemo.man"), Double.valueOf(13), peach},499{"Brent", "Christian", black, getString("TableDemo.bladerunner"), Double.valueOf(23), broccoli},500{"Mark", "Davidson", darkgreen, getString("TableDemo.brazil"), Double.valueOf(27), asparagus},501{"Jeff", "Dinkins", blue, getString("TableDemo.ladyvanishes"), Double.valueOf(8), kiwi},502{"Ewan", "Dinkins", yellow, getString("TableDemo.bugs"), Double.valueOf(2), strawberry},503{"Amy", "Fowler", violet, getString("TableDemo.reservoir"), Double.valueOf(3), raspberry},504{"Hania", "Gajewska", purple, getString("TableDemo.jules"), Double.valueOf(5), raspberry},505{"David", "Geary", blue, getString("TableDemo.pulpfiction"), Double.valueOf(3), watermelon},506// {"James", "Gosling", pink, getString("TableDemo.tennis"), Double.valueOf(21), donut},507{"Eric", "Hawkes", blue, getString("TableDemo.bladerunner"), Double.valueOf(.693), pickle},508{"Shannon", "Hickey", green, getString("TableDemo.shawshank"), Double.valueOf(2), grapes},509{"Earl", "Johnson", green, getString("TableDemo.pulpfiction"), Double.valueOf(8), carrot},510{"Robi", "Khan", green, getString("TableDemo.goodfellas"), Double.valueOf(89), apple},511{"Robert", "Kim", blue, getString("TableDemo.mohicans"), Double.valueOf(655321), strawberry},512{"Janet", "Koenig", turquoise, getString("TableDemo.lonestar"), Double.valueOf(7), peach},513{"Jeff", "Kesselman", blue, getString("TableDemo.stuntman"), Double.valueOf(17), pineapple},514{"Onno", "Kluyt", orange, getString("TableDemo.oncewest"), Double.valueOf(8), broccoli},515{"Peter", "Korn", sunpurple, getString("TableDemo.musicman"), Double.valueOf(12), sparegrass},516517{"Rick", "Levenson", black, getString("TableDemo.harold"), Double.valueOf(1327), raspberry},518{"Brian", "Lichtenwalter", jfcblue, getString("TableDemo.fifthelement"), Double.valueOf(22), pear},519{"Malini", "Minasandram", beige, getString("TableDemo.joyluck"), Double.valueOf(9), corn},520{"Michael", "Martak", green, getString("TableDemo.city"), Double.valueOf(3), strawberry},521{"David", "Mendenhall", forestgreen, getString("TableDemo.schindlerslist"), Double.valueOf(7), peach},522{"Phil", "Milne", suspectpink, getString("TableDemo.withnail"), Double.valueOf(3), banana},523{"Lynn", "Monsanto", cybergreen, getString("TableDemo.dasboot"), Double.valueOf(52), peach},524{"Hans", "Muller", rustred, getString("TableDemo.eraserhead"), Double.valueOf(0), pineapple},525{"Joshua", "Outwater", blue, getString("TableDemo.labyrinth"), Double.valueOf(3), pineapple},526{"Tim", "Prinzing", blue, getString("TableDemo.firstsight"), Double.valueOf(69), pepper},527{"Raj", "Premkumar", jfcblue2, getString("TableDemo.none"), Double.valueOf(7), broccoli},528{"Howard", "Rosen", green, getString("TableDemo.defending"), Double.valueOf(7), strawberry},529{"Ray", "Ryan", black, getString("TableDemo.buckaroo"),530Double.valueOf(3.141592653589793238462643383279502884197169399375105820974944), banana},531{"Georges", "Saab", aqua, getString("TableDemo.bicycle"), Double.valueOf(290), cantaloupe},532{"Tom", "Santos", blue, getString("TableDemo.spinaltap"), Double.valueOf(241), pepper},533{"Rich", "Schiavi", blue, getString("TableDemo.repoman"), Double.valueOf(0xFF), pepper},534{"Nancy", "Schorr", green, getString("TableDemo.fifthelement"), Double.valueOf(47), watermelon},535{"Keith", "Sprochi", darkgreen, getString("TableDemo.2001"), Double.valueOf(13), watermelon},536{"Matt", "Tucker", eblue, getString("TableDemo.starwars"), Double.valueOf(2), broccoli},537{"Dmitri", "Trembovetski", red, getString("TableDemo.aliens"), Double.valueOf(222), tomato},538{"Scott", "Violet", violet, getString("TableDemo.raiders"), Double.valueOf(-97), banana},539{"Kathy", "Walrath", darkgreen, getString("TableDemo.thinman"), Double.valueOf(8), pear},540{"Nathan", "Walrath", black, getString("TableDemo.chusingura"), Double.valueOf(3), grapefruit},541{"Steve", "Wilson", green, getString("TableDemo.raiders"), Double.valueOf(7), onion},542{"Kathleen", "Zelony", gray, getString("TableDemo.dog"), Double.valueOf(13), grapes}543};544545// Create a model of the data.546TableModel dataModel = new AbstractTableModel() {547public int getColumnCount() { return names.length; }548public int getRowCount() { return data.length;}549public Object getValueAt(int row, int col) {return data[row][col];}550public String getColumnName(int column) {return names[column];}551public Class<?> getColumnClass(int c) {return getValueAt(0, c).getClass();}552public boolean isCellEditable(int row, int col) {return col != 5;}553public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; }554};555556557// Create the table558tableView = new JTable(dataModel);559TableRowSorter<TableModel> sorter = new TableRowSorter<>(dataModel);560tableView.setRowSorter(sorter);561562// Show colors by rendering them in their own color.563DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() {564public void setValue(Object value) {565if (value instanceof NamedColor) {566NamedColor c = (NamedColor) value;567setBackground(c);568setForeground(c.getTextColor());569setText(c.toString());570} else {571super.setValue(value);572}573}574};575576// Create a combo box to show that you can use one in a table.577JComboBox<NamedColor> comboBox = new JComboBox<>();578comboBox.addItem(aqua);579comboBox.addItem(beige);580comboBox.addItem(black);581comboBox.addItem(blue);582comboBox.addItem(eblue);583comboBox.addItem(jfcblue);584comboBox.addItem(jfcblue2);585comboBox.addItem(cybergreen);586comboBox.addItem(darkgreen);587comboBox.addItem(forestgreen);588comboBox.addItem(gray);589comboBox.addItem(green);590comboBox.addItem(orange);591comboBox.addItem(purple);592comboBox.addItem(red);593comboBox.addItem(rustred);594comboBox.addItem(sunpurple);595comboBox.addItem(suspectpink);596comboBox.addItem(turquoise);597comboBox.addItem(violet);598comboBox.addItem(yellow);599600TableColumn colorColumn = tableView.getColumn(getString("TableDemo.favorite_color"));601// Use the combo box as the editor in the "Favorite Color" column.602colorColumn.setCellEditor(new DefaultCellEditor(comboBox));603604colorRenderer.setHorizontalAlignment(JLabel.CENTER);605colorColumn.setCellRenderer(colorRenderer);606607tableView.setRowHeight(INITIAL_ROWHEIGHT);608609scrollpane = new JScrollPane(tableView);610return scrollpane;611}612613private void printTable() {614MessageFormat headerFmt;615MessageFormat footerFmt;616JTable.PrintMode printMode = fitWidth.isSelected() ?617JTable.PrintMode.FIT_WIDTH :618JTable.PrintMode.NORMAL;619620String text;621text = headerTextField.getText();622if (text != null && text.length() > 0) {623headerFmt = new MessageFormat(text);624} else {625headerFmt = null;626}627628text = footerTextField.getText();629if (text != null && text.length() > 0) {630footerFmt = new MessageFormat(text);631} else {632footerFmt = null;633}634635try {636boolean status = tableView.print(printMode, headerFmt, footerFmt);637638if (status) {639JOptionPane.showMessageDialog(tableView.getParent(),640getString("TableDemo.printingComplete"),641getString("TableDemo.printingResult"),642JOptionPane.INFORMATION_MESSAGE);643} else {644JOptionPane.showMessageDialog(tableView.getParent(),645getString("TableDemo.printingCancelled"),646getString("TableDemo.printingResult"),647JOptionPane.INFORMATION_MESSAGE);648}649} catch (PrinterException pe) {650String errorMessage = MessageFormat.format(getString("TableDemo.printingFailed"),651new Object[] {pe.getMessage()});652JOptionPane.showMessageDialog(tableView.getParent(),653errorMessage,654getString("TableDemo.printingResult"),655JOptionPane.ERROR_MESSAGE);656} catch (SecurityException se) {657String errorMessage = MessageFormat.format(getString("TableDemo.printingFailed"),658new Object[] {se.getMessage()});659JOptionPane.showMessageDialog(tableView.getParent(),660errorMessage,661getString("TableDemo.printingResult"),662JOptionPane.ERROR_MESSAGE);663}664}665666class NamedColor extends Color {667String name;668public NamedColor(Color color, String name) {669super(color.getRGB());670this.name = name;671}672673public Color getTextColor() {674int r = getRed();675int g = getGreen();676int b = getBlue();677if(r > 240 || g > 240) {678return Color.black;679} else {680return Color.white;681}682}683684public String toString() {685return name;686}687}688689class ColumnLayout implements LayoutManager {690int xInset = 5;691int yInset = 5;692int yGap = 2;693694public void addLayoutComponent(String s, Component c) {}695696public void layoutContainer(Container c) {697Insets insets = c.getInsets();698int height = yInset + insets.top;699700Component[] children = c.getComponents();701Dimension compSize = null;702for (int i = 0; i < children.length; i++) {703compSize = children[i].getPreferredSize();704children[i].setSize(compSize.width, compSize.height);705children[i].setLocation( xInset + insets.left, height);706height += compSize.height + yGap;707}708709}710711public Dimension minimumLayoutSize(Container c) {712Insets insets = c.getInsets();713int height = yInset + insets.top;714int width = 0 + insets.left + insets.right;715716Component[] children = c.getComponents();717Dimension compSize = null;718for (int i = 0; i < children.length; i++) {719compSize = children[i].getPreferredSize();720height += compSize.height + yGap;721width = Math.max(width, compSize.width + insets.left + insets.right + xInset*2);722}723height += insets.bottom;724return new Dimension( width, height);725}726727public Dimension preferredLayoutSize(Container c) {728return minimumLayoutSize(c);729}730731public void removeLayoutComponent(Component c) {}732}733734void updateDragEnabled(boolean dragEnabled) {735tableView.setDragEnabled(dragEnabled);736headerTextField.setDragEnabled(dragEnabled);737footerTextField.setDragEnabled(dragEnabled);738}739740}741742743