Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the JTable table in Java Swing programming

2025-02-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about what the JTable table in Java Swing programming is, many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Table is one of the most widely used but also the most troublesome controls in GUI programming. Tables are used to display two-dimensional data and provide editing, selection and other functions. If you just display the data, this is still very easy, as long as you pass a two-dimensional array or collection into the JTable, eg

Public class SimpleTable {JFrame jf = new JFrame ("simple form"); JTable table / define a two-dimensional array as tabular data Object [] [] tableData = {new Object [] {"Li Qingzhao", 29, "female"}, new Object [] {"Socrates", 56, "male"}, new Object [] {"Li Bai", 35, "male"}, new Object [] {"make jade", 18, "female"} New Object [] {"Tiger head", 2, "male"} / define one-dimensional data as column headings Object [] columnTitle = {"name", "age", "gender"}; public void init () {/ / create a JTable object table = new JTable (tableData, columnTitle) with a two-dimensional array and an one-dimensional array / / place the JTable object in the JScrollPane and put the JScrollPane in the window to display jf.add (new JScrollPane (table)); jf.pack (); jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); jf.setVisible (true);} public static void main (String [] args) {new SimpleTable (). Init ();}}

Here's an example of how JTable tables are adjusted and selected, eg.

Public class AdjustingWidth {JFrame jf = new JFrame ("adjust table column width"); JMenuBar menuBar = new JMenuBar (); JMenu adjustModeMenu = new JMenu ("adjust mode"); JMenu selectUnitMenu = new JMenu ("select unit"); JMenu selectModeMenu = new JMenu ("select mode"); / / define 5 radio box buttons to control the width adjustment mode of the table JRadioButtonMenuItem [] adjustModesItem = new JRadioButtonMenuItem [5] / define three radio box buttons to control how the table is selected: JRadioButtonMenuItem [] selectModesItem = new JRadioButtonMenuItem [3]; JCheckBoxMenuItem rowsItem = new JCheckBoxMenuItem ("Select rows"); JCheckBoxMenuItem columnsItem = new JCheckBoxMenuItem ("Select columns"); JCheckBoxMenuItem cellsItem = new JCheckBoxMenuItem ("Select cells"); ButtonGroup adjustBg = new ButtonGroup (); ButtonGroup selectBg = new ButtonGroup () / / define an array of int type to hold all the width adjustment modes of the table int [] adjustModes = new int [] {JTable.AUTO_RESIZE_OFF, JTable.AUTO_RESIZE_NEXT_COLUMN, JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS, JTable.AUTO_RESIZE_LAST_COLUMN, JTable.AUTO_RESIZE_ALL_COLUMNS} Int [] selectModes = new int [] {ListSelectionModel.MULTIPLE_INTERVAL_SELECTION, ListSelectionModel.SINGLE_INTERVAL_SELECTION, ListSelectionModel.SINGLE_SELECTION}; JTable table / define a two-dimensional array as tabular data Object [] [] tableData = {new Object [] {"Li Qingzhao", 29, "female"}, new Object [] {"Socrates", 56, "male"}, new Object [] {"Li Bai", 35, "male"}, new Object [] {"make jade", 18, "female"} New Object [] {"Tiger head", 2, "male"} / define one-dimensional data as column headings Object [] columnTitle = {"name", "age", "gender"}; public void init () {/ / create a JTable object table = new JTable (tableData, columnTitle) with a two-dimensional array and an one-dimensional array / /-menu to set table adjustment mode for window installation-adjustModesItem [0] = new JRadioButtonMenuItem ("adjust table only"); adjustModesItem [1] = new JRadioButtonMenuItem ("adjust only next column"); adjustModesItem [2] = new JRadioButtonMenuItem ("average adjustment balance below") AdjustModesItem [3] = new JRadioButtonMenuItem ("adjust last column only"); adjustModesItem [4] = new JRadioButtonMenuItem ("average adjust all columns"); menuBar.add (adjustModeMenu); for (int I = 0; I)

< adjustModesItem.length ; i++) { //默认选中第三个菜单项,即对应表格默认的宽度调整方式 if (i == 2) { adjustModesItem[i].setSelected(true); } adjustBg.add(adjustModesItem[i]); adjustModeMenu.add(adjustModesItem[i]); final int index = i; //为设置调整方式的菜单项添加监听器 adjustModesItem[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { //如果当前菜单项处于选中状态,表格使用对应的调整方式 if (adjustModesItem[index].isSelected()) { table.setAutoResizeMode(adjustModes[index]); } } }); } //-----------为窗口安装设置表格选择方式的菜单----------- selectModesItem[0] = new JRadioButtonMenuItem("无限制"); selectModesItem[1] = new JRadioButtonMenuItem("单独的连续区"); selectModesItem[2] = new JRadioButtonMenuItem("单选"); menuBar.add(selectModeMenu); for (int i = 0; i < selectModesItem.length ; i++) { //默认选中第一个菜单项,即对应表格默认的选择方式 if (i == 0) { selectModesItem[i].setSelected(true); } selectBg.add(selectModesItem[i]); selectModeMenu.add(selectModesItem[i]); final int index = i; //为设置选择方式的菜单项添加监听器 selectModesItem[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { //如果当前菜单项处于选中状态,表格使用对应的选择方式 if (selectModesItem[index].isSelected()) { table.getSelectionModel().setSelectionMode(selectModes[index]); } } }); } menuBar.add(selectUnitMenu); //-----------为窗口安装设置表格选择单元的菜单----------- rowsItem.setSelected(table.getRowSelectionAllowed()); columnsItem.setSelected(table.getColumnSelectionAllowed()); cellsItem.setSelected(table.getCellSelectionEnabled()); rowsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { table.clearSelection(); //如果该菜单项处于选中状态,设置表格的选择单元是行 table.setRowSelectionAllowed(rowsItem.isSelected()); //如果选择行、选择列同时被选中,其实质是选择单元格 cellsItem.setSelected(table.getCellSelectionEnabled()); } }); selectUnitMenu.add(rowsItem); columnsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { table.clearSelection(); //如果该菜单项处于选中状态,设置表格的选择单元是列 table.setColumnSelectionAllowed(columnsItem.isSelected()); //如果选择行、选择列同时被选中,其实质是选择单元格 cellsItem.setSelected(table.getCellSelectionEnabled()); } }); selectUnitMenu.add(columnsItem); cellsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { table.clearSelection(); //如果该菜单项处于选中状态,设置表格的选择单元是单元格 table.setCellSelectionEnabled(cellsItem.isSelected()); //该选项的改变会同时影响选择行、选择列两个菜单 rowsItem.setSelected(table.getRowSelectionAllowed()); columnsItem.setSelected(table.getColumnSelectionAllowed()); } }); selectUnitMenu.add(cellsItem); jf.setJMenuBar(menuBar); //分别获取表格的三个表格列,并设置三列的最小宽度,最佳宽度和最大宽度 TableColumn nameColumn = table.getColumn(columnTitle[0]); nameColumn.setMinWidth(40); TableColumn ageColumn = table.getColumn(columnTitle[1]); ageColumn.setPreferredWidth(50); TableColumn genderColumn = table.getColumn(columnTitle[2]); genderColumn.setMaxWidth(50); //将JTable对象放在JScrollPane中,并将该JScrollPane放在窗口中显示出来 jf.add(new JScrollPane(table)); System.out.println(table.getModel()); jf.pack(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } public static void main(String[] args) { new AdjustingWidth().init(); } } 和JList,JTree类似,JTable采用TableModel来保存表格中的所有状态数据,采用TableColumnModel来保存所有列的数据。eg public class TestDefaultTableModel { JFrame mainWin = new JFrame("管理数据行、数据列"); final int COLUMN_COUNT = 5; DefaultTableModel model; JTable table; //用于保存被隐藏列的List集合 ArrayList hiddenColumns = new ArrayList(); public void init() { model = new DefaultTableModel(COLUMN_COUNT ,COLUMN_COUNT); for (int i = 0; i < COLUMN_COUNT ; i++ ) { for (int j = 0; j < COLUMN_COUNT ; j++ ) { model.setValueAt("老单元格值 " + i + " " + j , i , j); } } table = new JTable(model); mainWin.add(new JScrollPane(table), BorderLayout.CENTER); //为窗口安装菜单 JMenuBar menuBar = new JMenuBar(); mainWin.setJMenuBar(menuBar); JMenu tableMenu = new JMenu("管理"); menuBar.add(tableMenu); JMenuItem hideColumnsItem = new JMenuItem("隐藏选中列"); hideColumnsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { //获取所有选中列的索引 int[] selected = table.getSelectedColumns(); TableColumnModel columnModel = table.getColumnModel(); //依次把每一个选中的列隐藏起来,并使用List把这些列保存起来 for (int i = selected.length - 1; i >

= 0; iMel -) {TableColumn column = columnModel.getColumn (selected [I]); table.removeColumn (column); / / Save the hidden columns to ensure that hiddenColumns.add (column) can be displayed later ); tableMenu.add (hideColumnsItem); JMenuItem showColumnsItem = new JMenuItem ("Show Hidden columns") ShowColumnsItem.addActionListener (new ActionListener () {public void actionPerformed (ActionEvent event) {/ / show all hidden columns in turn for (TableColumn tc: hiddenColumns) {/ / show all hidden columns in turn Table.addColumn (tc) } / / clear the List collection that holds hidden columns hiddenColumns.clear ();}}); tableMenu.add (showColumnsItem); JMenuItem addColumnItem = new JMenuItem ("insert selected column") AddColumnItem.addActionListener (new ActionListener () {public void actionPerformed (ActionEvent event) {/ / get the index of all selected columns int [] selected = table.getSelectedColumns (); TableColumnModel columnModel = table.getColumnModel () / / add the selected column to JTable after for (int I = selected.length-1; I > = 0; iMel -) {TableColumn column = columnModel.getColumn (selected [I]); table.addColumn (column);}) TableMenu.add (addColumnItem); JMenuItem addRowItem = new JMenuItem ("add rows"); addRowItem.addActionListener (new ActionListener () {public void actionPerformed (ActionEvent event) {/ / create an String array as the content of a new line String [] newCells = new string [column _ COUNT] For (int I = 0; I

< newCells.length; i++) { newCells[i] = "新单元格值 " + model.getRowCount() + " " + i; } //向TableModel中新增一行。 model.addRow(newCells); } }); tableMenu.add(addRowItem); JMenuItem removeRowsItem = new JMenuItem("删除选中行"); removeRowsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { //获取所有选中行 int[] selected = table.getSelectedRows(); //依次删除所有选中行 for (int i = selected.length - 1; i >

= 0; iMel -) {model.removeRow (selectable [I]);}); tableMenu.add (removeRowsItem); mainWin.pack (); mainWin.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); mainWin.setVisible (true) } public static void main (String [] args) {new TestDefaultTableModel () .init ();}}

But pay attention to the increase in columns, only show the original hidden columns, not really add columns, if you want to add, then re-new JTable

In the table mentioned earlier, the cells are all strings. This is because what we passed in is DefaultTableModel. It finally calls the toString method to draw the table. The specific method to customize the cell is as follows, eg.

Public class TestTableCellRenderer {JFrame jf = new JFrame ("use cell painter"); JTable table / define 2D array as tabular data Object [] [] tableData = {"Li Qingzhao", 29, "female", new ImageIcon ("icon/3.gif"), true}, new Object [] {"Socrates", 56, "male", new ImageIcon ("icon/1.gif"), false}, new Object [] {"Li Bai", 35 "male", new ImageIcon ("icon/4.gif"), true}, new Object [] {"Nanyu", 18, "female", new ImageIcon ("icon/2.gif"), true}, new Object [] {"Tiger head", 2, "male", new ImageIcon ("icon/5.gif"), true}} / define one-dimensional data as column headings String [] columnTitle = {"name", "age", "gender", "main avatar", "whether Chinese"}; public void init () {/ / create an ExtendedTableModel object ExtendedTableModel model = new ExtendedTableModel (columnTitle, tableData) with a two-dimensional array and an one-dimensional array / / use ExtendedTableModel to create JTable table = new JTable (model); table.setRowSelectionAllowed (false); table.setRowHeight (40); / / get the third column TableColumn lastColumn = table.getColumnModel (). GetColumn (2); / / A custom cell painter lastColumn.setCellRenderer (new GenderTableCellRenderer ()) is used for the third column / / place the JTable object in the JScrollPane and put the JScrollPane in the window to display jf.add (new JScrollPane (table)); jf.pack (); jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); jf.setVisible (true);} public static void main (String [] args) {new TestTableCellRenderer (). Init () }} class ExtendedTableModel extends DefaultTableModel {/ / re-provides a constructor whose implementation is delegated to the DefaultTableModel parent class public ExtendedTableModel (String [] columnNames, Object [] [] cells) {super (cells, columnNames) } / / override the getColumnClass method to return its real data type public Class getColumnClass (int c) {return getValueAt (0, c). GetClass () based on the first value of each column;}} class GenderTableCellRenderer extends JPanel implements TableCellRenderer {private String cellValue; / / defines the width and height of the icon final int ICON_WIDTH = 23; final int ICON_HEIGHT = 21 Public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {cellValue = (String) value; / / set to draw border if (hasFocus) {setBorder (UIManager.getBorder ("Table.focusCellHighlightBorder"));} else {setBorder (null) } return this } / / override the paint method, which is responsible for drawing the cell content public void paint (Graphics g) {/ / if the table value is "male" or "male" Then draw a male icon if (cellValue.equalsIgnoreCase ("male") | | cellValue.equalsIgnoreCase ("male")) {drawImage (g, new ImageIcon ("icon/male.gif") .getImage ()) } / / if the table value is "female" or "female", draw a female icon if (cellValue.equalsIgnoreCase ("female") | | cellValue.equalsIgnoreCase ("female")) {drawImage (g, new ImageIcon ("icon/female.gif"). GetImage ()) Private void drawImage (Graphics g, Image image) {g.drawImage (image, (getWidth ()-ICON_WIDTH) / 2, (getHeight ()-ICON_HEIGHT) / 2, null);}}

I just implemented a different control for each column here, and you can customize a table with a different control for each column, so you need to get the cell and then setCellRender.

After reading the above, do you have any further understanding of what JTable tables are in Java Swing programming? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report