table增删——LH(勾选项添加)
table增删——LH(勾选项添加)
实现:
1、添加,通过勾选某些选项进行添加,已有值则仅弹出对话框提醒,不进行重复添加
2、删除,点击table的某行,在进行删除,删除前询问是否确认删除
3、查找文件,filechoose
4、设置table的可编辑性,如全部不可编辑,或某几列不可编辑
包括:
class OptPanel 主面板
class Content 将添加的内容作为一个类进行构造
public class CheckDefaultModel extends DefaultTableModel 构造table
public class TableHeaderRender implements TableCellRenderer 表头的全选功能
class Test 测试
class OptPanel 主面板
package optimizetest;import java.awt.BorderLayout;import java.awt.Component;import java.awt.Dimension;import java.awt.GridLayout;import java.awt.Point;import java.awt.Rectangle;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.event.MouseWheelEvent;import java.awt.event.MouseWheelListener;import java.io.File;import java.util.ArrayList;import java.util.List;import java.util.logging.Logger;import javax.swing.BorderFactory;import javax.swing.DefaultListModel;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JComponent;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JList;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTabbedPane;import javax.swing.JTable;import javax.swing.JTextField;import javax.swing.JToolBar;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;import javax.swing.filechooser.FileFilter;import javax.swing.table.JTableHeader;import javax.swing.table.TableCellRenderer;import org.openide.DialogDescriptor;import org.openide.DialogDisplayer;import org.openide.NotifyDescriptor;/** * * @author Administrator */public class OptPanel { JButton addButton = new JButton(); JButton delButton = new JButton(); JButton editButton = new JButton(); ImageIcon addIcon = new ImageIcon(); ImageIcon delIcon = new ImageIcon(); ImageIcon editIcon = new ImageIcon(); JTabbedPane optTabbedPane; CheckDefaultModel tableModel, addTableModel; JTable table = new JTable(tableModel) { public boolean isCellEditable(int row, int column) { return false; } }; JTable addTable = new JTable(addTableModel) { public boolean isCellEditable(int row, int column) { if (column == 1 || column == 2) { return false; } else { return true; } } }; JScrollPane scrollPane = new JScrollPane(table); JScrollPane addScrollPane = new JScrollPane(addTable);// DefaultListModel addListModel; JList optAddList; JScrollPane AddListScroll; JPanel optAdvancedPanel; JPanel addJPanel, editPanel;// JPanel addListJPanel;// JPanel addContentJPanel = new JPanel(); Point mousePoint; JPanel browseJPanel; DialogDescriptor AddDescriptor, EditDescriptor; Content content1 = new Content("Filter1", "Description1", new Boolean(true), "Weight1"); Content content2 = new Content("Filter2", "Description2", new Boolean(true), "Weight2"); Content content3 = new Content("Filter3", "Description3", new Boolean(false), "Weight3");// List<Content> optContentsList = getContentList(); static List<Content> optContentsList = new ArrayList<>(); List<Content> optAddContentsList; List<Content> defaultOptContentsList = getDefaultContentList(); static Content content; String[] columnName = {"Filter", "Description", "Option(AsError)", "Weight"}; Object[] addColumnName = {"Enable", "Filter", "Description", "Option(AsError)", "Weight"};// Object[][] data = {{"Filter1", "Description1", new Boolean(true), "Weight1"}, // {"Filter1", "Description2", new Boolean(false), "Weight2"}, // {"Filter3", "Description3", new Boolean(false), "Weight3"}}; Object[][] data; Object[][] addTableData; Object[] addData; String addDescription, Description; int addRow, editRow; int[] addIndices;// JTextField FilterField;// JCheckBox OptionBox;// JTextField DescriptionField;// JTextField weightField;// JCheckBox headerBox;// JTableHeader tableHeader; Boolean Enable; public OptPanel() { } public void OptFrame() { JFrame mJFrame = new JFrame(); mJFrame.setLayout(new BorderLayout()); mJFrame.setBounds(new Rectangle(new Dimension(500, 350))); mJFrame.setLocationRelativeTo(null); mJFrame.setTitle("OptPanel"); mJFrame.add(optJTabbedPane(), BorderLayout.NORTH); mJFrame.setVisible(true); mJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public JTabbedPane optJTabbedPane() { optTabbedPane = new JTabbedPane(); optTabbedPane.setTabPlacement(JTabbedPane.NORTH); optTabbedPane.addTab("General", null); optTabbedPane.addTab("Advanced", optAdvancedPanel()); return optTabbedPane; } public JPanel optAdvancedPanel() { optAdvancedPanel = new JPanel(new BorderLayout()); JPanel optAdvancedTablePanel = new JPanel(); optAdvancedTablePanel.setLayout(new BorderLayout()); scrollPane.setPreferredSize(new Dimension(200, 200)); optAdvancedTablePanel.add(scrollPane, BorderLayout.NORTH); optAdvancedPanel.add(optAdvancedTablePanel, BorderLayout.CENTER); addIcon = new ImageIcon("Picture/add.png"); addButton.setIcon(addIcon); addButton.setToolTipText("add"); addButton.setMnemonic(KeyEvent.VK_INSERT);//alt+insert delIcon = new ImageIcon("Picture/remove.png"); delButton.setIcon(delIcon); delButton.setToolTipText("remove"); delButton.setMnemonic(KeyEvent.VK_DELETE);//alt+delete editIcon = new ImageIcon("Picture/edit.png"); editButton.setIcon(editIcon); editButton.setToolTipText("edit"); editButton.setMnemonic('E');//alt+E JPanel optAdvancedHeaderPanel = new JPanel(new BorderLayout()); JToolBar tableToolBar = new JToolBar(); tableToolBar.setFloatable(false); tableToolBar.add(addButton); tableToolBar.add(delButton); tableToolBar.add(editButton); optAdvancedHeaderPanel.add(tableToolBar, BorderLayout.WEST); optAdvancedPanel.add(optAdvancedHeaderPanel, BorderLayout.NORTH); optAdvancedPanel.add(browseJPanel("Calculator", "C:/Users/luhong.PLATFORM-DA/Desktop/20130725/MEXData/Wat_NMOS33.txt"), BorderLayout.SOUTH); tableModel = new CheckDefaultModel(getData(optContentsList), columnName); table.setModel(tableModel); table.setToolTipText("table"); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { mousePoint = e.getPoint(); Description = table.getValueAt(table.rowAtPoint(mousePoint), 1).toString(); } }); delButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { int delRow = table.rowAtPoint(mousePoint); if (delRow != -1) { int delresponse = JOptionPane.showConfirmDialog(null, "Are you sure to remove ?", "Warning", JOptionPane.OK_CANCEL_OPTION); if (delresponse == JOptionPane.OK_OPTION) { for (Content mContent : optContentsList) { if (mContent.Description.equals(Description)) { content = mContent; break; } } optContentsList.remove(content); tableModel = new CheckDefaultModel(getData(optContentsList), columnName); table.setModel(tableModel); } } } catch (Exception e2) { JOptionPane.showMessageDialog(null, "please choose remove item first ! ");// Logger.getAnonymousLogger().info("please choose remove item first ! "); } } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { /* * solved the problem : the item still can be editable * if click the editButton to remove the item right after click delButton */ content = new Content(); editRow = table.rowAtPoint(mousePoint); if (editRow != -1) { for (Content mContent : optContentsList) { if (mContent.Description.equals(Description)) { content = mContent; break; } } editPanel = (JPanel) content.getComponent(); EditDescriptor = new DialogDescriptor(editPanel, "edit", true, DialogDescriptor.OK_CANCEL_OPTION, DialogDescriptor.OK_OPTION, null); Object result = DialogDisplayer.getDefault().notify(EditDescriptor); // displays the dialog if (result == NotifyDescriptor.OK_OPTION) { if (content.updateContent()) { tableModel = new CheckDefaultModel(getData(optContentsList), columnName); table.setModel(tableModel); } editPanel.removeAll();// table.updateUI(); } else if (result == NotifyDescriptor.CANCEL_OPTION) { editPanel.removeAll(); } } } catch (Exception e2) { JOptionPane.showMessageDialog(null, "please choose edit item first ! "); } } }); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { addJPanel = new JPanel(new BorderLayout()); addTableModel = new CheckDefaultModel(getAddTableData(defaultOptContentsList), addColumnName); addTable.setModel(addTableModel); addJPanel.add(addScrollPane, BorderLayout.NORTH); try { AddDescriptor = new DialogDescriptor(addJPanel, "add", true, DialogDescriptor.OK_CANCEL_OPTION, DialogDescriptor.OK_OPTION, null); Object result = DialogDisplayer.getDefault().notify(AddDescriptor); // displays the dialog if (result == NotifyDescriptor.OK_OPTION) { for (int i = 0; i < addTableModel.getRowCount(); i++) { Enable = (Boolean) addTable.getValueAt(i, 0); if (Enable) { boolean exist = false; for (Content mContent : optContentsList) { if (mContent.equals(defaultOptContentsList.get(i))) { JOptionPane.showMessageDialog(null, mContent.Description + " has exist !"); exist = true; break; } } if (!exist) { updateContent(addTable, i, defaultOptContentsList.get(i)); optContentsList.add(defaultOptContentsList.get(i)); } } } tableModel = new CheckDefaultModel(getData(optContentsList), columnName); table.setModel(tableModel); } else if (result == NotifyDescriptor.CANCEL_OPTION) { } } catch (Exception e) { JOptionPane.showMessageDialog(null, "please choose first ! "); } } }); return optAdvancedPanel; } public JPanel browseJPanel(String itemPrompt, String defAnswer) { browseJPanel = new JPanel(); browseJPanel.setLayout(new BorderLayout()); JPanel promptPanel = new JPanel(new GridLayout(1, 1, 5, 5)); JPanel editPanel = new JPanel(new GridLayout(1, 1, 5, 5)); JPanel buttonPanel = new JPanel(new GridLayout(1, 1, 5, 5)); final JTextField field = new JTextField(defAnswer.toString()); field.setPreferredSize(new Dimension(280, 30)); JButton browseButton = new JButton("Browse"); promptPanel.add(new JLabel(itemPrompt)); editPanel.add(field); buttonPanel.add(browseButton); browseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String tFileName = field.getText(); /* * JFileChooser.FILES_AND_DIRECTORIES * JFileChooser.FILES_ONLY */ File file = showLoadFileDialog(JFileChooser.FILES_AND_DIRECTORIES, null, tFileName); if (file == null) { return; } field.setText(file.getAbsolutePath()); } }); browseJPanel.add(promptPanel, BorderLayout.WEST); browseJPanel.add(editPanel, BorderLayout.CENTER); browseJPanel.add(buttonPanel, BorderLayout.EAST); return browseJPanel; } File showLoadFileDialog(int mode, FileFilter filter, String tFileName) { JFileChooser chooser = new JFileChooser(); File tFile = new File(tFileName); if (mode == JFileChooser.FILES_ONLY) { if (!tFile.isFile()) { tFile = new File(""); } } chooser.setSelectedFile(tFile); chooser.setFileSelectionMode(mode); chooser.setMultiSelectionEnabled(false); chooser.resetChoosableFileFilters(); chooser.addChoosableFileFilter(filter); chooser.setFileHidingEnabled(false); int answer = chooser.showOpenDialog(browseJPanel); if (answer != JFileChooser.APPROVE_OPTION) { return null; } return chooser.getSelectedFile(); } public List<Content> getDefaultContentList() { defaultOptContentsList = new ArrayList<Content>(); defaultOptContentsList.add(content1); defaultOptContentsList.add(content2); defaultOptContentsList.add(content3); return defaultOptContentsList; } public List<Content> getContentList() { optContentsList = new ArrayList<Content>(); optContentsList.add(content1); optContentsList.add(content2); optContentsList.add(content3); return optContentsList; } public Object[][] getData(List<Content> list) { data = new Object[list.size()][4]; for (int i = 0; i < list.size(); i++) { data[i][0] = list.get(i).Filter; data[i][1] = list.get(i).Description; data[i][2] = list.get(i).Option; data[i][3] = list.get(i).Weight; } return data; } public Object[][] getAddTableData(List<Content> list) { data = new Object[list.size()][5]; for (int i = 0; i < list.size(); i++) { data[i][0] = new Boolean(false); data[i][1] = list.get(i).Filter; data[i][2] = list.get(i).Description; data[i][3] = list.get(i).Option; data[i][4] = list.get(i).Weight; } return data; } public Object[] getAddData(Content c) { addData = new Object[4]; addData[0] = c.Filter.toString(); addData[1] = c.Description.toString(); addData[2] = c.Option; addData[3] = c.Weight.toString(); return addData; } public Content updateContent(JTable addTable, int index, Content addContent) { addContent.Filter = (String) addTable.getValueAt(index, 1); addContent.Description = (String) addTable.getValueAt(index, 2); addContent.Option = (Boolean) addTable.getValueAt(index, 3); addContent.Weight = (String) addTable.getValueAt(index, 4); return addContent; }}
class Content 将添加的内容作为一个类进行构造
package optimizetest;import java.awt.Component;import java.awt.GridLayout;import java.util.ArrayList;import java.util.List;import javax.swing.JCheckBox;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;/* * To change this template, choose Tools | Templates * and open the template in the editor. *//** * * @author Administrator */public class Content { protected String Filter; protected String Description; protected Boolean Option; protected String Weight; ContentPanel contentPanel;// protected Boolean Enable; public Content(String Filter, String Description, Boolean Option, String Weight) { this.Filter = Filter; this.Description = Description; this.Option = Option; this.Weight = Weight; } public Content() { }// public Boolean getEnable() {// return Enable;// }//// public void setEnable(Boolean Enable) {// this.Enable = Enable;// } public String getFilter() { return Filter; } public String getDescription() { return Description; } public Boolean getOption() { return Option; } public String getWeight() { return Weight; } public void setFilter(String Filter) { this.Filter = Filter; } public void setDescription(String Description) { this.Description = Description; } public void setOption(Boolean Option) { this.Option = Option; } public void setWeight(String Weight) { this.Weight = Weight; } public Component getComponent() { contentPanel = new ContentPanel(); return contentPanel.initComponents(); }// public boolean isEnabled() {// return Enable;// } public boolean updateContent() { if (!contentPanel.getPanelWeight().equals(Weight) || !contentPanel.getPanelOption().equals(Option) || !contentPanel.getPanelFilter().equals(Filter) || !contentPanel.getPanelDescription().equals(Description)) { System.out.println("Content update data:"); if (!contentPanel.getPanelFilter().equals(Filter)) { Filter = contentPanel.getPanelFilter(); System.out.println("Filter : " + Filter); } if (!contentPanel.getPanelDescription().equals(Description)) { Description = contentPanel.getPanelDescription(); System.out.println("Description : " + Description); } if (!contentPanel.getPanelOption().equals(Option)) { Option = contentPanel.getPanelOption(); System.out.println("Option : " + Option); } if (!contentPanel.getPanelWeight().equals(Weight)) { Weight = contentPanel.getPanelWeight(); System.out.println("Weight : " + Weight); } return true; } return false; } class ContentPanel extends JPanel {// Boolean optionbBoolean = new Boolean(false); JLabel FilterLabel = new JLabel("Filter"); JLabel DescriptionLabel = new JLabel("Description"); JLabel OptionLabel = new JLabel("Option(AsError)"); JLabel weightLabel = new JLabel("Weight"); JTextField filtField = new JTextField(); JTextField descriptionField = new JTextField(); JCheckBox optionCheckBox = new JCheckBox(); JTextField weightField = new JTextField(); public ContentPanel() {// optionCheckBox.setSelected(Option); optionCheckBox.setSelected(Option);// optionbBoolean.booleanValue(); weightField.setText(Weight); descriptionField.setText(Description); filtField.setText(Filter); } private JPanel initComponents() { JPanel mJPanel = new JPanel(); mJPanel.setLayout(new GridLayout(4, 2, 0, 10)); mJPanel.add(FilterLabel); mJPanel.add(filtField); mJPanel.add(DescriptionLabel); mJPanel.add(descriptionField); mJPanel.add(OptionLabel); mJPanel.add(optionCheckBox); mJPanel.add(weightLabel); mJPanel.add(weightField); mJPanel.setBounds(0, 0, 300, 300); return mJPanel; } public String getPanelWeight() { return weightField.getText().toString().trim(); } public String getPanelFilter() { return filtField.getText().toString().trim(); } public String getPanelDescription() { return descriptionField.getText().toString().trim(); } public Boolean getPanelOption() { return optionCheckBox.isSelected(); } }}
public class CheckDefaultModel extends DefaultTableModel 构造table
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package optimizetest;import javax.swing.table.DefaultTableModel;/** * * @author Administrator */public class CheckDefaultModel extends DefaultTableModel { Object[] columns; Object[][] data;// List<Content> list; public CheckDefaultModel(Object[][] data, Object[] columnNames) { super(data, columnNames);// this.list = list;// this.columns = columnNames; } public CheckDefaultModel() { } public Class<?> getColumnClass(int columnIndex) { return getValueAt(0, columnIndex).getClass(); } public void setAllSelected(boolean value) { for (int i = 0; i < getRowCount(); i++) { this.setValueAt(value, i, 0); } }}
public class TableHeaderRender implements TableCellRenderer 表头的全选功能
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package Test2;import java.awt.Component;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JCheckBox;import javax.swing.JComponent;import javax.swing.JLabel;import javax.swing.JTable;import javax.swing.table.JTableHeader;import javax.swing.table.TableCellRenderer;/** * * @author Administrator */public class TableHeaderRender implements TableCellRenderer { JTable table; JTableHeader tableHeader; CheckDefaultModel model; JCheckBox headerBox; public TableHeaderRender(JTable table) { this.table = table; this.tableHeader = table.getTableHeader(); this.model = (CheckDefaultModel) table.getModel(); headerBox = new JCheckBox(model.getColumnName(0)); headerBox.setSelected(false); tableHeader.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int selectColumn = tableHeader.columnAtPoint(e.getPoint()); if (selectColumn == 0) { boolean value = !headerBox.isSelected(); headerBox.setSelected(value); model.setAllSelected(value); tableHeader.repaint(); } } }); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { String valueStr = (String) value; JLabel label = new JLabel(valueStr); JComponent component = (column == 0) ? headerBox : label; return component; }}
class Test 测试
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package optimizetest;import java.awt.geom.Ellipse2D;import java.awt.geom.Rectangle2D;import javax.swing.BorderFactory;import javax.swing.ButtonGroup;import javax.swing.JProgressBar;import javax.swing.JRadioButton;/** * * @author cao */public class OptimizeTest { /** * @param args the command line arguments */ public static void main(String[] args) { //TODO code application logic here OptPanel mOptPanel = new OptPanel(); mOptPanel.OptFrame(); }}