/*
* $Id: JDataGridBean.java,v 1.48 2006/01/16 04:02:28 zfq Exp zfq $
*
* Copyright (C) 2001-2003 Extreme Component, Inc. All rights reserved.
* Use is subject to license terms.
*/
package com.zfqjava.swing;
import com.zfqjava.chart.Node;
import com.zfqjava.chart.geom.RectangleNode;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.util.*;
import java.text.MessageFormat;
import java.net.URL;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.beans.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.undo.*;
import javax.swing.filechooser.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import com.zfqjava.swing.cell.*;
import com.zfqjava.swing.datagrid.ComponentFactory;
import com.zfqjava.swing.event.WorkBookDataEvent;
import java.applet.Applet;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* JDataGridBean provides a JavaBean ready to use.
*
* @author $Author: zfq $
* @version $Revision: 1.48 $ $Date: 2006/01/16 04:02:28 $
*/
public class JDataGridBean extends JBean {
// class fields
private static final Logger log = Logger.getLogger(JDataGridBean.class.getName()); // util.Logger
private static final boolean DEBUG = false;
private static final Icon ICON_16X16 = new EmptyIcon(16, 16);
private static final String NAME = "JDataGridBean";
private static final String VERSION = "2.5.0";
private static final String BUNDLE =
"com.zfqjava.swing.resources.datagridbean";
private static final String MRU_COMMAND = "mru";
/**
* Identifies the main menubar.
*/
public static final String MAIN_MENUBAR = "main-menubar";
/**
* Identifies the main toolbar.
*/
public static final String MAIN_TOOLBAR = "main-toolbar";
/**
* Identifies the chart toolbar.
*/
public static final String CHART_TOOLBAR = "chart-toolbar";
/**
* Identifies the shape toolbar.
*/
public static final String SHAPE_TOOLBAR = "shape-toolbar";
/**
* Identifies the formula toolbar.
*/
public static final String FORMULA_TOOLBAR = "formula-toolbar";
/**
* Identifies the style toolbar.
*/
public static final String STYLE_TOOLBAR = "style-toolbar";
/**
* Identifies the datagrid popup menu.
*/
private static final String DATAGRID_POPUPMENU = "datagrid-popupmenu";
/**
* Identifies the row header popup menu.
*/
private static final String ROWHEADER_POPUPMENU = "rowheader-popupmenu";
/**
* Identifies the columnheader popup menu.
*/
private static final String COLUMNHEADER_POPUPMENU = "columnheader-popupmenu";
/**
* Identifies the toolbar popup menu.
*/
private static final String TOOLBAR_POPUPMENU = "toolbar-popupmenu";
private void setAppProperties() {
try {
if(isDefaultPropertiesEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
System.setProperty("application.name", NAME);
System.setProperty("application.version", VERSION);
return null;
}
});
}
} catch(Exception e) {
e.printStackTrace();
}
}
// instance fields
private JPanel centerPanel;
private JDataGrid dataGrid;
private JDataGridChart chart;
private JMenuBar menuBar;
private JToolBar toolBar;
// private JStyleBar styleBar;
// private JFormulaBar formulaBar;
// private JChartBar chartBar;
// private JShapeBar shapeBar;
private UndoManager undo;
// private PageFormat pageFormat;
private File file;
// private Map actionMap;
private Handler handler;
private java.util.List mruMenuItems;
private java.util.List mruFiles;
private Map uiMap = new HashMap(2);
private final int MRU_COUNT = 4;
private final int MIN_ROWS = 99;
private final int MIN_COLUMNS = 26;
// action row and column
// for doColumnWidth, doHideColumn action
private int actionRow = -1;
private int actionColumn = -1;
// toolbar
private Map toolBarMap = new HashMap(4);
private JScrollPane scrollPane;
public JDataGridBean() {
super();
// setLogLevel(".datagrid", Level.FINE);
verifyLicense(NAME, VERSION);
initComponents();
}
private void initComponents() {
getResourceManager().addBundle(BUNDLE);
setAppProperties();
boolean hideSplash = Boolean.getBoolean(JDataGridBean.class.getName()+".hideSplash");
// ImageIcon icon = new ImageIcon(getClass().getResource("/com/zfqjava/swing/beaninfo/images/JDataGridColor16.gif"));
if(!hideSplash) {
doSplash();
}
setTitle(createTitle());
// actionMap = new HashMap(30);
// undo = createUndoManager();
getAction(UNDO).setEnabled(false);
getAction(REDO).setEnabled(false);
mruFiles = new ArrayList(MRU_COUNT);
mruMenuItems = new ArrayList(MRU_COUNT);
add(createNorthPanel(), BorderLayout.NORTH);
centerPanel = createCenterPanel();
setDataGrid(createDataGrid());
add(centerPanel, BorderLayout.CENTER);
add(createSouthPanel(), BorderLayout.SOUTH);
for(int i=0,n=menuBar.getMenuCount(); i 0 && model.getColumnCount() > 0) {
workSheet.getCellSelectionModel().setSelectionCell(new Cell(0, 0));
}
return workSheet;
}
// TODO: set default properties enabled?
// TODO: add setWorkBookEnabled();
// TODO: completed TransferHandler feature. only use it when update to 1.6.
// TODO: integrate into Netbeans 5.5 feature.
// should consider develop 3 version JDataGrid for jdk1.4.2, jdk1.5, jdk 1.6?
// 1.good TransferHandler support.
// 2.good JTabbedPane with component tab support.
// 3.good feature?
/**
* Sets the bean's work book to the specified workBook.
*
* @param workBook the work book
* @see #getWorkBook
* @since JDataGrid 2.0
*/
public void setWorkBook(WorkBook workBook) {
WorkBook oldValue = this.workBook;
this.workBook = workBook;
if(oldValue != workBook) {
if(oldValue != null) {
oldValue.removeChangeListener(getHandler());
if(xscrollBar != null) {
xscrollBar.setWorkBook(null);
}
}
if(workBook != null) {
if(workBook.getSelectedSheet() == null && workBook.getSheetCount() > 0) {
workBook.setSelectedIndex(0);
}
workBook.addChangeListener(getHandler());
if(xscrollBar != null) {
xscrollBar.setWorkBook(workBook);
}
}
if(dataGrid != null) {
// System.out.println("sheet="+workBook.getSelectedSheet());
if(workBook != null && workBook.getSelectedSheet() != null) {
WorkSheet sheet = workBook.getSelectedSheet();
dataGrid.setModel(sheet.getModel());
CellSelectionModel cellSelectionModel = sheet.getCellSelectionModel();
SizeModel columnSizeModel = sheet.getColumnSizeModel();
SizeModel rowSizeModel = sheet.getRowSizeModel();
if(columnSizeModel != null) {
dataGrid.setColumnSizeModel(columnSizeModel);
}
if(rowSizeModel != null) {
dataGrid.setRowSizeModel(rowSizeModel);
}
if(cellSelectionModel != null) {
dataGrid.setCellSelectionModel(cellSelectionModel);
}
if(dataGrid.getRowCount() > 0 && dataGrid.getColumnCount() > 0) {
dataGrid.setFreezeCell(sheet.getFreezeRow(), sheet.getFreezeColumn());
}
} else {
// TODO: has problem??
dataGrid.setModel(createModel());
}
}
}
firePropertyChange("workBook", oldValue, workBook);
}
/**
* Returns the work book in use.
*
* @return the work book in use
* @since JDataGrid 2.0
*/
public WorkBook getWorkBook() {
return workBook;
}
private XScrollBar xscrollBar;
private JScrollPane createScrollPane(JDataGrid dataGrid) {
JScrollPane scrollPane = new JScrollPane(dataGrid) {
public JScrollBar createHorizontalScrollBar() {
JScrollBar scrollBar = super.createHorizontalScrollBar();
xscrollBar = createXScrollBar(scrollBar);
return xscrollBar;
}
};
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
return scrollPane;
}
private XScrollBar createXScrollBar(JScrollBar scrollBar) {
XScrollBar xscrollBar = new XScrollBar(this, scrollBar);
if(getWorkBook() != null) {
xscrollBar.setWorkBook(getWorkBook());
}
return xscrollBar;
}
// a JScrollBar wrapper
// 1.add JTabbedPane
// 2.add JScrollBar
static class XScrollBar extends JScrollBar implements ListDataListener, MouseListener, PropertyChangeListener {
private JScrollBar scrollBar;
private JTabbedPane tabbedPane;
private JSplitPane splitPane;
private JDataGridBean bean;
public XScrollBar(JDataGridBean bean, JScrollBar scrollBar) {
super(scrollBar.getOrientation());
this.bean = bean;
setModel(scrollBar.getModel());
this.scrollBar = scrollBar;
this.tabbedPane = createTabbedPane();
this.selectionModel = tabbedPane.getModel();
Component[] comps = getComponents();
for(int i=0; i= 2) {
int index = getTabIndexAt(tabbedPane, e.getX(), e.getY());
bean.setActionSheetIndex(index);
if(index != -1) {
bean.doRenameSheet();
}
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
showPopup(e);
}
public void mouseReleased(MouseEvent e) {
showPopup(e);
}
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if(propertyName.equals("name")) {
WorkSheet sheet = (WorkSheet)e.getSource();
int index = workBook.indexOfSheet(sheet);
String sheetName = (String)e.getNewValue();
tabbedPane.setTitleAt(index, sheetName);
}
}
private void showPopup(MouseEvent e) {
int index = getTabIndexAt(tabbedPane, e.getX(), e.getY());
bean.setActionSheetIndex(index);
if(index != -1) {
if(e.isPopupTrigger()) {
bean.getPopupMenu("worksheet-popupmenu").show(tabbedPane, e.getX(), e.getY());
}
}
}
}
private int actionSheetIndex;
private void setActionSheetIndex(int index) {
this.actionSheetIndex = index;
}
public void doInsertSheet() {
if(workBook == null) {
return;
}
int index = actionSheetIndex;
if(index == -1) {
index = workBook.getSelectedIndex();
}
workBook.addSheet(index, createWorkSheet());
}
public void doDeleteSheet() {
if(workBook == null) {
return;
}
int index = actionSheetIndex;
if(index == -1) {
index = workBook.getSelectedIndex();
}
int value = JOptionPane.showConfirmDialog(this, getString("deleteSheetMessage"));
if(value == JOptionPane.YES_OPTION) {
workBook.removeSheet(index);
}
}
public void doRenameSheet() {
if(workBook == null) {
return;
}
int index = actionSheetIndex;
if(index == -1) {
index = workBook.getSelectedIndex();
}
if(index != -1) {
String s = JOptionPane.showInputDialog(this, getString("inputSheetMessage"));
if(s != null) {
getWorkBook().getSheet(index).setName(s);
}
}
}
/**
* Returns the datagrid for this bean.
*
* @return the datagrid for this bean
* @since JDataGrid 1.5.1
*/
public JDataGrid getDataGrid() {
return dataGrid;
}
private Font getDefaultFont() {
// Font font = dataGrid.getFont();
Font font = new Font("Dialog", Font.PLAIN, 12);
return font;
}
// move to JDataGrid? JDataGrid.createDefaultCellAttributes
private AttributeSet createAttributes(JDataGrid dataGrid) {
Font font = getDefaultFont();
dataGrid.setFont(font);
SimpleAttributeSet a = new SimpleAttributeSet();
Color fgColor = dataGrid.getForeground();
Color bgColor = dataGrid.getBackground();
StyleConstants.setFontFamily(a, font.getFamily());
StyleConstants.setFontSize(a, font.getSize());
StyleConstants.setBold(a, font.isBold());
StyleConstants.setItalic(a, font.isItalic());
StyleConstants.setForeground(a, fgColor);
StyleConstants.setBackground(a, bgColor);
log.fine("default attributes: " + a);
return a;
}
/**
* Creates a datagrid for this bean.
*
* @return a new datagrid
* @since JDataGrid 1.5.1
*/
protected JDataGrid createDataGrid() {
JDataGrid dataGrid = new JDataGrid();
// dataGrid.putClientProperty("JDataGrid.toggleSelectionOnCtrlDown", Boolean.TRUE);
// JDataGrid dataGrid = new JDataGrid(new DefaultColumnSorter(createModel()));
// dataGrid.putClientProperty("CellEditor.dispatchEventOnStopEditingDisabled", Boolean.TRUE);
// dataGrid.setZoomFactor(2);
// dataGrid.putClientProperty("JDataGrid.activateLinkOnModifierDown", Boolean.TRUE);
// dataGrid.putClientProperty("JDataGrid.columnSortingEnabled", Boolean.TRUE);
// dataGrid.putClientProperty("JDataGrid.switchUnsortedOrderEnabled", Boolean.TRUE);
// disable press key to start editing
// dataGrid.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);
// clear the cell text when start editing
dataGrid.putClientProperty("JDataGrid.clearCellOnStartsEdit", Boolean.TRUE);
// change the start click count to 2
// dataGrid.putClientProperty("JDataGrid.clickCountToStartsEdit", new Integer(2));
// auto sets the cell class
dataGrid.putClientProperty("JDataGrid.autoSetsCellClass", Boolean.TRUE);
dataGrid.putClientProperty("JDataGrid.autoSetsCellValue", Boolean.TRUE);
// sets the string escape char to "'"
// dataGrid.putClientProperty("JDataGrid.stringEscapeChar", new Character('\''));
// set the modern selection style
dataGrid.putClientProperty("JDataGrid.selectionStyle", "Modern");
// set fill cell value only
// dataGrid.putClientProperty("JDataGrid.fillCellValueOnly", Boolean.TRUE);
// set selectionBorderPainted property
dataGrid.setSelectionBorderPainted(true);
// set the fill handle painted
dataGrid.setFillHandlePainted(true);
// set the editing stop behavior
dataGrid.setEditingStopBehavior(JDataGrid.COMMIT_OR_EDITING);
// set the selection mode
dataGrid.setCellSelectionEnabled(true);
// dataGrid.setRowSelectionAllowed(false);
// dataGrid.setColumnSelectionAllowed(true);
dataGrid.selectCell(0, 0, true);
// set the auto resize mode
dataGrid.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// dataGrid.setRowHeight(0, 40);
// dataGrid.setRowHeight(4, 40);
dataGrid.setSurrendersFocusOnKeystroke(true);
if(DEBUG) {
// debug graphics
dataGrid.setDebugGraphicsOptions(DebugGraphics.FLASH_OPTION);
RepaintManager repaintManager = RepaintManager.currentManager(dataGrid);
repaintManager.setDoubleBufferingEnabled(false);
// end debug graphics
}
return dataGrid;
}
/**
* Creates the default DataGridModel for the JDataGrid.
*
* @return the default DataGridModel
* @since JDataGrid 1.5.1
*/
protected DataGridModel createModel() {
DataGridModel model = new DefaultDataGridModel(99, 26);
// LargeDataGridModel model = new LargeDataGridModel(19, 26);
return model;
}
// private CellFormulaContext context;
// private FormulaContext getFormulaContext(TableModel model, int row, int column) {
// if(context == null) {
// context = new CellFormulaContext();
// WorkSheet sheet = new WorkSheet("test", model);
// WorkSheet[] sheets = new WorkSheet[1];
// sheets[0] = sheet;
// WorkBook book = new WorkBook(sheets);
// context.setWorkBook(book);
// context.setWorkSheet(sheet);
// }
// context.setCell(row, column);
// return context;
// }
/**
* Returns the current AbstractChart.
*
* @return the current AbstractChart
* @since JDataGrid 2.0
*/
public AbstractChart getAbstractChart() {
return getChart();
}
private JDataGridChart getChart() {
if(chart == null) {
chart = createChart();
}
return chart;
}
private JDataGridChart createChart() {
JDataGridChart chart = new JDataGridChart();
// chart.setRenderingHints(null);
return chart;
}
private JPanel toolBarPanel;
private JPanel createNorthPanel() {
menuBar = createMenuBar("main-menubar");
toolBar = createToolBar("main-toolbar");
JPanel panel = new JPanel(new BorderLayout());
panel.add(menuBar, BorderLayout.NORTH);
toolBarPanel = new JPanel(new BorderLayout());
toolBarPanel.add(toolBar, BorderLayout.NORTH);
toolBarPanel.add(getStyleBar(), BorderLayout.CENTER);
toolBarPanel.add(getFormulaBar(), BorderLayout.SOUTH);
panel.add(toolBarPanel, BorderLayout.CENTER);
return panel;
}
private JPanel southPanel;
private JPanel createSouthPanel() {
// shapeBar = createShapeBar();
JPanel panel = new JPanel(new BorderLayout());
// panel.add(shapeBar, BorderLayout.NORTH);
panel.add(getStatusBar(), BorderLayout.CENTER);
southPanel = panel;
return panel;
}
private JShapeBar getShapeBar() {
return getShapeBar(true);
}
private JShapeBar getShapeBar(boolean create) {
JShapeBar shapeBar = null;
if(toolBarMap != null) {
shapeBar = (JShapeBar)toolBarMap.get("shapeBar");
}
if(create && shapeBar == null) {
shapeBar = createShapeBar();
toolBarMap.put("shapeBar", shapeBar);
}
return shapeBar;
}
private JShapeBar createShapeBar() {
JShapeBar shapeBar = new JShapeBar(this);
shapeBar.setForComponent(chart);
shapeBar.addMouseListener(getHandler());
return shapeBar;
}
private JChartBar getChartBar() {
return getChartBar(true);
}
private JChartBar getChartBar(boolean create) {
JChartBar chartBar = null;
if(toolBarMap != null) {
chartBar = (JChartBar)toolBarMap.get("chartBar");
}
if(create && chartBar == null) {
chartBar = createChartBar();
toolBarMap.put("chartBar", chartBar);
}
return chartBar;
}
private JChartBar createChartBar() {
JChartBar chartBar = new JChartBar(this);
chartBar.setForComponent(chart);
chartBar.addMouseListener(getHandler());
return chartBar;
}
private JMenu createMRUMenu() {
JMenu menu = createMenu("recent-file");
menu.setIcon(ICON_16X16);
addMRUMenuItem(menu);
return menu;
}
private void addMRUMenuItem(JMenu menu) {
for(int i=0; iNote:This method is not common API, please do not rely on
* this method even existing.
*/
// public void doChangeModel() {
// Object[] models = { "Basic", "Formula", "JDBC", "Account" };
// JComboBox message = new JComboBox(models);
// int value = JOptionPane.showOptionDialog(this,
// message,
// "Change model",
// JOptionPane.OK_CANCEL_OPTION,
// JOptionPane.INFORMATION_MESSAGE,
// null,
// null,
// null);
// if(value == JOptionPane.OK_OPTION) {
// String item = (String)message.getSelectedItem();
// TableModel model = null;
// if(item.equals("Basic")) {
// model = createModel1();
// } else if(item.equals("Formula")) {
// model = createModel4();
// } else if(item.equals("JDBC")) {
// model = createModel2();
// } else if(item.equals("Account")) {
// model = createModel3();
// }
// if(model != null) {
// dataGrid.setModel(model);
// setFile(null);
// }
// }
// }
/**
* Note:This method is not common API, please do not rely
* on this method even existing.
*/
// public void doDemoInternalFrame() {
// Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
// JFrame f = new JFrame("Demo JInternalFrame");
// JDesktopPane desktop = new JDesktopPane();
// f.getContentPane().add(desktop);
// f.pack();
// f.setSize(d);
// centerOnScreen(f);
// JDataGridBean bean = new JDataGridBean();
// bean.showInternalFrame(desktop);
// f.show();
// }
private static void centerOnScreen(Window window) {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation((d.width - window.getWidth())/2,
(d.height - window.getHeight())/2);
}
public void doNew() {
if(getWorkBook() == null) {
setCurrentFile(null);
dataGrid.setModel(createModel());
dataGrid.selectCell(0, 0, true);
} else {
JFrame frame = getFrame();
JInternalFrame internalFrame = getInternalFrame();
if(frame != null) {
// if the old frame is not null, open new frame
JDataGridBean bean = new JDataGridBean();
bean.showFrame();
} else if(internalFrame != null) {
// if the old internal frame is not null, open new internal frame
JDataGridBean bean = new JDataGridBean();
bean.showInternalFrame(internalFrame);
} else {
// else clear the current frame
setCurrentFile(null);
setWorkBook(this.createWorkBook());
dataGrid.selectCell(0, 0, true);
}
}
}
private String formatOpenMsg(File f) {
String msg = f.getName();
return MessageFormat.format(getString("openfile.msg"), new String[] { msg });
}
private void doOpen(File f) {
if(f == null) return;
File[] files = new File[1];
files[0] = f;
doOpen(files);
}
protected void doOpen(URL[] urls) {
doOpenImpl(urls);
}
private void doOpenImpl(Object[] urls) {
for(int i=0; i=0 && index < mruFiles.size()) {
File f = (File)mruFiles.get(index);
doOpen(f);
}
}
protected void doBeforeClose() throws ActionVetoException {
int option = JOptionPane.showConfirmDialog(this, getString("saveConfirmMessage"));
if(option == JOptionPane.YES_OPTION) {
doSave();
} else if(option == JOptionPane.NO_OPTION) {
// do nothing
} else {
throw new ActionVetoException("Action canceled");
}
}
public void doUndo() {
UndoManager undo = getUndoManager();
try {
undo.undo();
} catch (CannotUndoException ex) {
ex.printStackTrace();
}
updateUndoActions();
}
public void doRedo() {
UndoManager undo = getUndoManager();
try {
undo.redo();
} catch (CannotUndoException ex) {
ex.printStackTrace();
}
updateUndoActions();
}
public void doCut(ActionEvent e) {
invokeAction(CUT, e);
}
public void doCopy(ActionEvent e) {
invokeAction(COPY, e);
}
public void doPaste(ActionEvent e) {
invokeAction(PASTE, e);
}
private void invokeAction(String name, ActionEvent e) {
ActionMap map = dataGrid.getActionMap();
Action action = null;
if (map != null) {
action = map.get(name);
}
if(action != null) {
action.actionPerformed(new ActionEvent(dataGrid,
ActionEvent.ACTION_PERFORMED,
name,
e.getModifiers()));
}
}
public void doFind() {
JTextFinder finder = getTextFinder();
finder.setDialogType(JTextFinder.FIND_DIALOG);
finder.showDialog(this);
}
public void doFindNext() {
JTextFinder finder = getTextFinder();
finder.findNext();
}
public void doReplace() {
JTextFinder finder = getTextFinder();
finder.setDialogType(JTextFinder.REPLACE_DIALOG);
finder.showDialog(this);
}
public void doGoCell() {
String title = getString("goToCellDialog-title");
String rowLabel = getString("goToCellDialog-rowText");
JTextField rowField = new JTextField(9);
String columnLabel = getString("goToCellDialog-columnText");
JTextField columnField = new JTextField(9);
Object[] message = new Object[4];
message[0] = rowLabel;
message[1] = rowField;
message[2] = columnLabel;
message[3] = columnField;
int retValue = JOptionPane.showOptionDialog(this,
message,
title,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
null,
null);
if(retValue == JOptionPane.OK_OPTION) {
String rowText = rowField.getText();
String columnText = columnField.getText();
try {
int row = Integer.parseInt(rowText);
int column = Integer.parseInt(columnText);
row--;
column--;
if(row < 0 || row > dataGrid.getRowCount()-1 ||
column < 0 || column > dataGrid.getColumnCount() -1) {
return;
}
dataGrid.selectCell(row, column, true);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, getString("goToCellDialog-errorMessage"));
}
}
}
public void doClear() {
java.util.List l = dataGrid.getSelectionList();
for(int i=0,n=l.size(); i 0 && cols > 0) {
Cell c = new Cell(0, rows-1, 0, cols-1);
clearCell(c);
}
}
private void clearCell(Cell c) {
TableModel model = dataGrid.getModel();
if(model instanceof AbstractDataGridModel) {
boolean clear = ((AbstractDataGridModel)model).clear(c);
if(clear) {
System.out.println("The cell has been cleared and need not clear or \nCannot clear selected cells");
}
} else {
ModelFactory.clearTableModel(model, c);
}
}
public void doSelectAll() {
dataGrid.selectAll();
}
private boolean isButtonSelected(ActionEvent e) {
return ((AbstractButton)e.getSource()).isSelected();
}
public void doViewToolBar(ActionEvent e) {
boolean b = isButtonSelected(e);
toolBar.setVisible(b);
}
public void doViewStyleBar(ActionEvent e) {
boolean b = isButtonSelected(e);
// getStyleBar().setVisible(b);
if(b) {
if(getStyleBar().getParent() == null) {
toolBarPanel.add(getStyleBar(), BorderLayout.CENTER);
}
} else {
if(getStyleBar().getParent() != null) {
toolBarPanel.remove(getStyleBar());
}
}
}
public void doViewFormulaBar(ActionEvent e) {
boolean b = isButtonSelected(e);
// getFormulaBar().setVisible(b);
if(b) {
if(getFormulaBar().getParent() == null) {
toolBarPanel.add(getFormulaBar(), BorderLayout.SOUTH);
}
} else {
if(getFormulaBar().getParent() != null) {
toolBarPanel.remove(getFormulaBar());
}
}
}
public void doViewShapeBar(ActionEvent e) {
boolean b = isButtonSelected(e);
// getShapeBar().setVisible(b);
if(b) {
if(getShapeBar().getParent() == null) {
southPanel.add(getShapeBar(), BorderLayout.NORTH);
}
} else {
if(getShapeBar().getParent() != null) {
southPanel.remove(getShapeBar());
}
}
}
public void doViewChartBar(ActionEvent e) {
boolean b = isButtonSelected(e);
getChartBar().setVisible(b);
}
public void doViewStatusBar(ActionEvent e) {
boolean b = isButtonSelected(e);
getStatusBar().setVisible(b);
}
public void doViewRowHeader(ActionEvent e) {
boolean b = isButtonSelected(e);
Component header = dataGrid.getRowHeader();
if(header != null && header.getParent() instanceof JViewport) {
header.getParent().setVisible(b);
}
}
public void doViewColumnHeader(ActionEvent e) {
boolean b = isButtonSelected(e);
Component header = dataGrid.getTableHeader();
if(header != null && header.getParent() instanceof JViewport) {
header.getParent().setVisible(b);
}
}
public void doFormula() {
if(getFormulaBar() != null) {
getFormulaBar().setVisible(!getFormulaBar().isVisible());
}
}
public void doChart() {
ComponentFactory.showInsertChartDialog(this);
}
public void doSpell() {
JTextSpeller speller = getTextSpeller();
speller.showDialog(this);
}
public void doInsertRowBefore() {
doInsertRow(true);
}
public void doInsertRowAfter() {
doInsertRow(false);
}
private void doInsertRow(boolean before) {
DefaultDataGridModel model = getModel();
if(model != null) {
int row = dataGrid.getSelectionModel().getLeadSelectionIndex();
if(row != -1) {
if(before) {
model.addRow(row, null);
} else {
model.addRow(row+1, null);
}
}
}
}
public void doDeleteRow() {
DefaultDataGridModel model = getModel();
if(model != null) {
Cell c = dataGrid.getSelectedCell();
if(c != null && c.isFullRow(0, model.getColumnCount()-1)) {
model.removeRow(c.getFirstRow(), c.getLastRow());
} else {
int row = dataGrid.getSelectionModel().getLeadSelectionIndex();
if(row != -1) {
model.removeRow(row);
}
}
}
}
public void doInsertColumnBefore() {
doInsertColumn(true);
}
public void doInsertColumnAfter() {
doInsertColumn(false);
}
private void doInsertColumn(boolean before) {
DefaultDataGridModel model = getModel();
if(model != null) {
int column = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
if(column != -1) {
if(before) {
model.addColumn(column, null);
} else {
model.addColumn(column+1, null);
}
}
}
}
public void doDeleteColumn() {
DefaultDataGridModel model = getModel();
if(model != null) {
Cell c = dataGrid.getSelectedCell();
if(c != null && c.isFullColumn(0, model.getRowCount()-1)) {
model.removeColumn(c.getFirstColumn(), c.getLastColumn());
} else {
int column = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
if(column != -1) {
model.removeColumn(column);
}
}
}
}
public void doMergeCell() {
Cell c = dataGrid.getSelectedCell();
DataGridModel model = dataGrid.getDataGridModel();
if(c != null && model != null) {
if(!model.merge(c)) {
JOptionPane.showMessageDialog(this, getString("mergeCellErrorMessage"));
}
}
}
public void doSplitCell() {
Cell c = dataGrid.getSelectedCell();
DataGridModel model = dataGrid.getDataGridModel();
if(c != null && model != null) {
if(!model.split(c)) {
JOptionPane.showMessageDialog(this, getString("splitCellErrorMessage"));
}
}
}
public void doSort() {
ComponentFactory.showSortDialog(this);
}
public void doSortAscending() {
doSort(true);
}
public void doSortDescending() {
doSort(false);
}
private void doSort(boolean ascending) {
Cell c = dataGrid.getSelectedCell();
DefaultDataGridModel model = getModel();
if(c != null && model != null) {
int leadRow = dataGrid.getSelectionModel().getLeadSelectionIndex();
int leadColumn = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
// convert to model row?
// default is by row, use column index
boolean byColumn = false;
int index = 0;
if(byColumn) {
if(c.containsRow(leadRow)) {
index = leadRow - c.getFirstRow();
}
} else {
if(c.containsColumn(leadColumn)) {
index = leadColumn - c.getFirstColumn();
}
}
model.sort(c, ascending, index, byColumn, true);
}
}
public void doColumnName() {
int column = actionColumn;
if(column == -1) {
column = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
}
if(column == -1) {
return;
}
DataGridModel model = dataGrid.getDataGridModel();
if(column >= 0 && model != null) {
String name = JOptionPane.showInputDialog(this, getString("columnNameDialog-message"));
if(name != null) {
model.setColumnName(name, column);
}
}
}
public void doCellAttributes() {
ComponentFactory.showCellAttributesDialog(this);
}
public void doFunction() {
ComponentFactory.showInsertFunctionDialog(this);
}
public void doHyperlink() {
ComponentFactory.showInsertHyperlinkDialog(this);
}
public void doImage() {
ComponentFactory.showInsertImageDialog(this);
}
public void doFreeze() {
if(dataGrid.getFreezeRow() > 0 || dataGrid.getFreezeColumn() > 0) {
dataGrid.setFreezeCell(0, 0);
} else {
int leadRow = dataGrid.getSelectionModel().getLeadSelectionIndex();
int leadColumn = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
if(leadRow != -1 && leadColumn != -1) {
dataGrid.setFreezeCell(leadRow, leadColumn);
}
}
}
private void configureFreezeAction(boolean freeze) {
Action a = getAction("freeze");
String name = (freeze ? getString("unfreeze.name") : getString("freeze.name"));
if(a != null) {
a.putValue(Action.NAME, name);
}
}
private ASplitPane asplitPane;
private java.util.List dataGridList;
private void configureDataGrid(JDataGrid grid) {
grid.setModel(dataGrid.getModel());
grid.setCellSelectionModel(dataGrid.getCellSelectionModel());
grid.setRowSizeModel(dataGrid.getRowSizeModel());
grid.setColumnSizeModel(dataGrid.getColumnSizeModel());
// if(!rowHeader) {
// grid.setRowHeader(null);
// }
// if(!columnHeader) {
// grid.setTableHeader(null);
// }
}
private void configureScrollPane(JScrollPane scrollPane, boolean rowHeader, boolean columnHeader, boolean showHorizontalBar, boolean showVerticalBar) {
if(!showHorizontalBar) {
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
} else {
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
if(!showVerticalBar) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
} else {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
scrollPane.addNotify();
scrollPane.getRowHeader().setVisible(rowHeader);
scrollPane.getColumnHeader().setVisible(columnHeader);
}
public void doSplit() {
if(asplitPane != null && (asplitPane.getDividerX() > 0 || asplitPane.getDividerY() > 0)) {
asplitPane.setDividerLocation(0, 0);
configureSplitAction(false);
JScrollPane scrollPane = (JScrollPane)dataGrid.getParent().getParent();
configureScrollPane(scrollPane, true, true, true, true);
centerPanel.removeAll();
centerPanel.add(scrollPane, BorderLayout.CENTER);
} else {
configureSplitAction(true);
int leadRow = dataGrid.getSelectionModel().getLeadSelectionIndex();
int leadColumn = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
if(leadRow != -1 && leadColumn != -1) {
Rectangle bounds = dataGrid.getCellRect(leadRow, leadColumn, false);
int x = bounds.x;
int y = bounds.y;
if(asplitPane == null) {
asplitPane = new ASplitPane();
asplitPane.removeAll();
dataGridList = new ArrayList(3);
JDataGrid grid = createDataGrid();
configureDataGrid(grid);
JScrollPane scrollPane = new JScrollPane(grid);
configureScrollPane(scrollPane, true, true, false, false);
dataGridList.add(grid);
asplitPane.add(scrollPane, ASplitPane.TOP_LEFT);
grid = createDataGrid();
configureDataGrid(grid);
scrollPane = new JScrollPane(grid);
configureScrollPane(scrollPane, false, true, false, true);
dataGridList.add(grid);
asplitPane.add(scrollPane, ASplitPane.TOP_RIGHT);
grid = createDataGrid();
configureDataGrid(grid);
scrollPane = new JScrollPane(grid);
configureScrollPane(scrollPane, false, false, true, true);
dataGridList.add(grid);
asplitPane.add(scrollPane, ASplitPane.BOTTOM_RIGHT);
}
// JScrollPane scrollPane = centerPanel.get
Component c = centerPanel.getComponent(0);
if(!(c instanceof ASplitPane)) {
centerPanel.removeAll();
centerPanel.add(asplitPane, BorderLayout.CENTER);
if(c instanceof JScrollPane) {
asplitPane.add(c, ASplitPane.BOTTOM_LEFT);
JScrollPane scrollPane = (JScrollPane)c;
configureScrollPane(scrollPane, true, false, true, false);
}
}
asplitPane.setDividerLocation(x, y);
}
}
}
private void configureSplitAction(boolean split) {
Action a = getAction("split");
String name = (split ? getString("unsplit.name") : getString("split.name"));
if(a != null) {
a.putValue(Action.NAME, name);
}
}
public void doNewWindow() {
JDataGridBean bean = new JDataGridBean();
if(getWorkBook() != null) {
bean.setWorkBook(getWorkBook());
} else {
bean.setWorkBook(null);
bean.getDataGrid().setModel(bean.getDataGrid().getModel());
}
bean.showFrame();
}
public void doComment() {
doInsertComment0();
}
public void doInsertComment() {
doInsertComment0();
}
// TODO: edit and delete comment need set the comment menu item visible?
// public void doEditComment() {
// }
public void doDeleteComment() {
final int leadRow = dataGrid.getSelectionModel().getLeadSelectionIndex();
final int leadColumn = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
if(leadRow != -1 && leadColumn != -1) {
AttributeSet as = dataGrid.getCellAttributes(leadRow, leadColumn);
if(as != null) {
CellStyle.Comment comment = CellStyle.getComment(as);
if(comment != null) {
if(comment.getHelper() instanceof Node) {
Node node = (Node)comment.getHelper();
getAbstractChart().getChart().removeNode(node);
}
MutableAttributeSet a = new SimpleAttributeSet();
a.addAttributes(as);
a.removeAttribute(CellStyle.COMMENT);
// CellStyle.setComment(a, null);
dataGrid.setCellAttributes(a, leadRow, leadColumn);
}
}
}
}
private Node createCommentNode(Rectangle rect) {
// TextNode node = new TextNode();
RectangleNode node = new RectangleNode();
// node.setFillPaint(Color.WHITE);
node.setBounds(rect.x + rect.width, rect.y, 120, 80);
return node;
}
private void doInsertComment0() {
final int leadRow = dataGrid.getSelectionModel().getLeadSelectionIndex();
final int leadColumn = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
if(leadRow != -1 && leadColumn != -1) {
Node commentNode = null;
AttributeSet as = dataGrid.getCellAttributes(leadRow, leadColumn);
if(as != null) {
CellStyle.Comment comment = CellStyle.getComment(as);
if(comment != null) {
if(comment.getHelper() instanceof Node) {
commentNode = (Node)comment.getHelper();
}
}
}
Rectangle rect = dataGrid.getCellRect(leadRow, leadColumn, false);
final AbstractChart chart = getAbstractChart();
final Node node = (commentNode != null ? commentNode : createCommentNode(rect));
if(commentNode == null) {
// new node, so add it
chart.getChart().addNode(node, 0);
}
chart.getChart().select(node);
chart.getChart().startEditingAtNode(node);
chart.requestFocusInWindow();
final com.zfqjava.swing.cell.AbstractCellEditor editor = chart.getChart().getEditor();
final CellEditorListener listener = new CellEditorListener() {
public void editingStopped(ChangeEvent e) {
String text = (String)editor.getCellEditorValue();
String author = null;
Object helper = node;
System.out.println("text="+text);
if(text != null && text.length() == 0) {
text = null;
}
AttributeSet as = dataGrid.getCellAttributes(leadRow, leadColumn);
if(text != null) {
CellStyle.Comment comment = new CellStyle.Comment(text, author, helper);
MutableAttributeSet a = new SimpleAttributeSet();
if(as != null) {
a.addAttributes(as);
}
CellStyle.setComment(a, comment);
dataGrid.setCellAttributes(a, leadRow, leadColumn);
node.setVisible(false);
chart.getChart().removeSelection(node);
} else {
if(as != null) {
MutableAttributeSet a = new SimpleAttributeSet();
a.addAttributes(as);
a.removeAttribute(CellStyle.COMMENT);
// CellStyle.setComment(a, null);
dataGrid.setCellAttributes(a, leadRow, leadColumn);
}
chart.getChart().removeNode(node);
}
}
public void editingCanceled(ChangeEvent e) {
editor.removeCellEditorListener(this);
}
};
editor.addCellEditorListener(listener);
}
}
//
// utility methods
//
/**
* Returns the print preview component.
*
* @return the print preview component
* @since JDataGrid 1.5.1
*/
public JPrintPreview getPrintPreview() {
return getPrintPreview(true);
}
private JPrintPreview getPrintPreview(boolean create) {
JPrintPreview printPreview = null;
if(uiMap != null) {
printPreview = (JPrintPreview)uiMap.get("print-preview");
}
if(printPreview == null && create) {
printPreview = createPrintPreview();
uiMap.put("print-preview", printPreview);
}
return printPreview;
}
private JPrintPreview createPrintPreview() {
JPrintPreview printPreview = new JPrintPreview();
return printPreview;
}
/**
* Creates the printable for the specified data grid.
*
* @param dataGrid the dataGrid
* @return the printable
* @since JDataGrid 1.5.1
*/
protected Printable createPrintable(JDataGrid dataGrid) {
Map map = null;
if(workBook != null) {
WorkSheet workSheet = workBook.getSelectedSheet();
if(workSheet != null) {
map = workSheet.getPrintProperties();
}
}
if(map == null) {
map = (printProperties != null ? printProperties : createPrintProperties());
}
if(printSelectedCell) {
map.put(PrintFactory.TABLE_PRINT_AREA, dataGrid.getSelectedCell());
}
return PrintFactory.createPrintable(dataGrid, map);
}
private Map printProperties;
/**
* Returns the print properties.
* @return the print properties
* @since JDataGrid 2.5.0
*/
public Map getPrintProperties() {
return printProperties;
}
/**
* Sets the print properties.
* @param printProperties the print properties
* @since JDataGrid 2.5.0
*/
public void setPrintProperties(Map printProperties) {
Map oldValue = this.printProperties;
this.printProperties = printProperties;
firePropertyChange("printProperties", oldValue, printProperties);
}
private boolean printSelectedCell;
/**
* Determines whether print the selected cell area.
* @return true if print the selected cell area, false otherwise
* @since JDataGrid 2.5.0
*/
public boolean isPrintSelectedCell() {
return printSelectedCell;
}
/**
* Sets whether print the selected cell area.
* @param printSelectedCell
* @since JDataGrid 2.5.0
*/
public void setPrintSelectedCell(boolean printSelectedCell) {
this.printSelectedCell = printSelectedCell;
}
/**
* Creates the default print properties.
* @return the print properties
* @since JDataGrid 2.5.0
*/
public Map createPrintProperties() {
Map map = new HashMap();
map.put(PrintFactory.HORIZONTAL_ALIGNMENT, new Integer(SwingConstants.CENTER));
// map.put(PrintFactory.ORIENTATION, new Integer(SwingConstants.VERTICAL));
map.put(PrintFactory.CENTER_MARGIN, new Insets(6, 0, 6, 0));
map.put(PrintFactory.HEADER_FORMAT, new MessageFormat(getTitle()));
map.put(PrintFactory.HEADER_MARGIN, new Insets(0, 0, 6, 0));
map.put(PrintFactory.HEADER_TEXT_ALIGNMENT, new Integer(SwingConstants.CENTER));
map.put(PrintFactory.HEADER_ICON, getIcon("logo-small-image"));
map.put(PrintFactory.FOOTER_FORMAT, new MessageFormat(getString("printPageText")));
map.put(PrintFactory.FOOTER_MARGIN, new Insets(6, 0, 0, 0));
map.put(PrintFactory.FOOTER_ALIGNMENT, new Integer(SwingConstants.RIGHT));
map.put(PrintFactory.SHOW_HEADER_LINE, Boolean.TRUE);
map.put(PrintFactory.SHOW_FOOTER_LINE, Boolean.TRUE);
map.put(PrintFactory.TABLE_SHOW_ROW_HEADER, Boolean.TRUE);
map.put(PrintFactory.TABLE_SHOW_COLUMN_HEADER, Boolean.TRUE);
map.put(PrintFactory.TABLE_SHOW_GRID_LINE, Boolean.TRUE);
map.put(PrintFactory.TABLE_PRINT_AREA, dataGrid.getSelectedCell());
// set fit width or height
map.put(PrintFactory.KEEP_ASPECT_RADIO, Boolean.TRUE);
map.put(PrintFactory.FIT_WIDTH, Boolean.TRUE);
// map.put(PrintFactory.FIT_HEIGHT, Boolean.TRUE);
return map;
}
private Set supportedFileSuffix;
/**
* Returns the supported file suffix.
* @return the supported file suffix
* @since JDataGrid 2.5.0
*/
public Set getSupportedFileSuffix() {
return supportedFileSuffix == null ? null : new HashSet(supportedFileSuffix);
}
/**
* Sets the supported file suffix.
* @param supportedFileSuffix
* @since JDataGrid 2.5.0
*/
public void setSupportedFileSuffix(Set supportedFileSuffix) {
this.supportedFileSuffix = (supportedFileSuffix == null ? null : new HashSet(supportedFileSuffix));
}
private JTextFinder getTextFinder() {
return getTextFinder(true);
}
private JTextFinder getTextFinder(boolean create) {
JTextFinder finder = null;
if(uiMap != null) {
finder = (JTextFinder)uiMap.get("finder");
}
if(finder == null && create) {
finder = createTextFinder();
finder.setForComponent(dataGrid);
uiMap.put("finder", finder);
}
return finder;
}
private JTextFinder createTextFinder() {
JTextFinder finder = new JTextFinder();
return finder;
}
private JTextSpeller getTextSpeller() {
return getTextSpeller(true);
}
private JTextSpeller getTextSpeller(boolean create) {
JTextSpeller speller = null;
if(uiMap != null) {
speller = (JTextSpeller)uiMap.get("speller");
}
if(speller == null && create) {
speller = createTextSpeller();
speller.setForComponent(dataGrid);
uiMap.put("speller", speller);
}
return speller;
}
private JTextSpeller createTextSpeller() {
JTextSpeller speller = new JTextSpeller();
return speller;
}
private JFileChooser createFileChooser() {
// JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
JFileChooser fc = new JFileChooser();
DefaultFileFilter[] a = {
new DefaultFileFilter("xls", getString("xls.desc")),
new DefaultFileFilter(new String[] {"html","htm"}, getString("html.desc")),
new DefaultFileFilter("xml", getString("xml.desc")),
new DefaultFileFilter("csv", getString("csv.desc")),
new DefaultFileFilter("txt", getString("txt.desc")),
new DefaultFileFilter("ser", getString("ser.desc"))
};
if(supportedFileSuffix != null) {
fc.setAcceptAllFileFilterUsed(false);
FileFilter defaultFileFilter = null;
for (int i = 0; i < a.length; i++) {
DefaultFileFilter filter = a[i];
if(supportedFileSuffix.contains(filter.getPreferredExtensionName())) {
fc.addChoosableFileFilter(filter);
if(defaultFileFilter == null) {
defaultFileFilter = filter;
}
}
}
if(defaultFileFilter != null) {
fc.setFileFilter(defaultFileFilter);
}
} else {
for (int i = 0; i < a.length; i++) {
fc.addChoosableFileFilter(a[i]);
}
fc.setFileFilter(a[0]);
}
return fc;
}
private JFileChooser createFileChooserForImage() {
// JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
JFileChooser fc = new JFileChooser();
fc.setAccessory(new FilePreviewer(fc));
// String[] formats = {"gif", "jpg", "jpeg", "png"};
String[] formats = ImageIO.getReaderFormatNames();
fc.addChoosableFileFilter(new DefaultFileFilter(formats, getString("image.desc")));
return fc;
}
private File currentDirectory;
private File getCurrentDirectory() {
if(currentDirectory != null) {
return currentDirectory;
}
File currentFile = getCurrentFile();
if(currentFile != null) {
return currentFile.getParentFile();
}
return null;
}
private void setCurrentDirectory(File currentDirectory) {
this.currentDirectory = currentDirectory;
}
private File getCurrentFile() {
return file;
}
private void setCurrentFile(File file) {
setCurrentFileImpl(file);
}
private URL url;
private void setCurrentFileImpl(Object urlObject) {
// if(file != null) {
// setCurrentDirectory(file.getParentFile());
// }
File file = (urlObject instanceof File ? (File)urlObject : null);
URL url = (urlObject instanceof URL ? (URL)urlObject : null);
this.file = file;
this.url = url;
resetUndoManager();
setTitle(createTitle());
if(file != null) {
if(mruFiles.contains(file)) {
mruFiles.remove(file);
mruFiles.add(0, file);
} else {
mruFiles.add(0, file);
if(mruFiles.size() > MRU_COUNT) {
mruFiles.remove(mruFiles.size()-1);
}
}
//updateMRUMenuItems();
}
if(chart != null) {
chart.getChart().removeAllNode();
}
}
private String createTitle() {
String appTitle = getString("title");;
String fileTitle = null;
if(file != null) {
fileTitle = file.getName();
} else if(url != null) {
fileTitle = url.toExternalForm();
} else {
fileTitle = getString("untitledText");
}
return fileTitle + " - " + appTitle;
}
private UndoManager createUndoManager() {
UndoManager undo = new UndoManager() {
protected void undoTo(UndoableEdit edit) throws CannotUndoException {
super.undoTo(edit);
selectCell(edit, true);
}
protected void redoTo(UndoableEdit edit) throws CannotRedoException {
super.redoTo(edit);
selectCell(edit, false);
}
private void selectCell(UndoableEdit edit, boolean undo) {
Cell c = null;
if(edit instanceof CellEditTracking) {
CellEditTracking cellEditTracking = (CellEditTracking)edit;
if(undo) {
c = cellEditTracking.getUndoCell();
} else {
c = cellEditTracking.getRedoCell();
}
}
if(c != null && getDataGrid() != null) {
getDataGrid().selectCell(c);
}
}
};
return undo;
}
private UndoManager getUndoManager() {
return getUndoManager(true);
}
private UndoManager getUndoManager(boolean create) {
if(create && undo == null) {
undo = createUndoManager();
}
return undo;
}
private void resetUndoManager() {
UndoManager undo = getUndoManager(false);
if(undo != null) {
undo.discardAllEdits();
}
updateUndoActions();
}
private void updateUndoActions() {
UndoManager undo = getUndoManager(false);
if(undo != null) {
getAction(UNDO).setEnabled(undo.canUndo());
getAction(REDO).setEnabled(undo.canRedo());
}
}
private DefaultDataGridModel getModel() {
DataGridModel model = dataGrid.getDataGridModel();
if(model instanceof DefaultDataGridModel) {
return (DefaultDataGridModel)model;
}
return null;
}
private void setBackgroundImage(int row, int col, URL url) {
DataGridModel model = dataGrid.getDataGridModel();
if(model != null) {
AttributeSet a = model.getCellAttributes(row, col);
if(a instanceof MutableAttributeSet) {
((MutableAttributeSet)a).addAttribute("background-image", url);
model.setCellAttributes(a, row, col);
} else {
SimpleAttributeSet newa = new SimpleAttributeSet();
if(a != null) {
newa.addAttributes(a);
}
newa.addAttribute("background-image", url);
model.setCellAttributes(newa, row, col);
}
}
}
private Handler getHandler() {
if(handler == null) {
handler = new Handler();
}
return handler;
}
// inner class
private class Handler implements UndoableEditListener,
ListSelectionListener,
ChangeListener,
ActionListener,
MouseListener,
MouseMotionListener,
PropertyChangeListener {
public void undoableEditHappened(UndoableEditEvent e) {
UndoableEdit edit = e.getEdit();
UndoManager undo = getUndoManager();
undo.addEdit(edit);
updateUndoActions();
log.fine("edit="+edit);
}
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) {
int row = dataGrid.getSelectionModel().getLeadSelectionIndex();
int column = dataGrid.getColumnModel().getSelectionModel().getLeadSelectionIndex();
if(row != -1 && column != -1) {
if(dataGrid.getSelectionModel().isSelectedIndex(row) &&
dataGrid.getColumnModel().getSelectionModel().isSelectedIndex(column)) {
getStyleBar().setAttributes(dataGrid.getCellAttributes(row, column));
}
}
}
}
private void doCellAttributesChanged() {
AttributeSet a = getStyleBar().getChangedAttributes();
if(a == null) {
// should not handle it
return;
}
dataGrid.setCellAttributes(a);
}
// TODO: move this method and setWorkBook METHOD together.
private void doWorkSheetChanged() {
JDataGrid dataGrid = getDataGrid();
WorkBook workBook = getWorkBook();
if(dataGrid != null && workBook != null) {
WorkSheet workSheet = workBook.getSelectedSheet();
if(workSheet != null) {
TableModel model = dataGrid.getModel();
dataGrid.setCellSelectionModel(new DefaultCellSelectionModel());
dataGrid.setColumnSizeModel(new DefaultSizeModel("Column Size Model", model.getColumnCount(), 75));
dataGrid.setRowSizeModel(new DefaultSizeModel("Row Size Model", model.getRowCount(), 16));
dataGrid.setModel(workSheet.getModel());
if(workSheet.getCellSelectionModel() != null) {
dataGrid.setCellSelectionModel(workSheet.getCellSelectionModel());
}
if(workSheet.getColumnSizeModel() != null) {
dataGrid.setColumnSizeModel(workSheet.getColumnSizeModel());
}
if(workSheet.getRowSizeModel() != null) {
dataGrid.setRowSizeModel(workSheet.getRowSizeModel());
}
if(dataGrid.getRowCount() > 0 && dataGrid.getColumnCount() > 0) {
dataGrid.setFreezeCell(workSheet.getFreezeRow(), workSheet.getFreezeColumn());
}
}
}
}
public void stateChanged(ChangeEvent e) {
if(e.getSource() instanceof JStyleBar) {
doCellAttributesChanged();
} else if(e.getSource() instanceof WorkBook) {
doWorkSheetChanged();
}
}
public void actionPerformed(ActionEvent e) {
}
// mouse events
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
showPopup(e);
}
public void mouseReleased(MouseEvent e) {
showPopup(e);
}
public void mouseEntered(MouseEvent e) {
String msg = "";
if(e.getSource() instanceof AbstractButton) {
Action a = ((AbstractButton)e.getSource()).getAction();
if(a != null) {
msg = (String)a.getValue(Action.LONG_DESCRIPTION);
} else {
msg = ((AbstractButton)e.getSource()).getToolTipText();
}
} else if(e.getSource() instanceof JComponent) {
msg = ((JComponent)e.getSource()).getToolTipText();
}
showStatus(msg);
}
public void mouseExited(MouseEvent e) {
showStatus("");
}
private void showPopup(MouseEvent e) {
if(e.getSource() instanceof JDataGrid) {
JDataGrid dataGrid = (JDataGrid)e.getSource();
if(e.isPopupTrigger()) {
Point p = e.getPoint();
int row = dataGrid.rowAtPoint(p);
int column = dataGrid.columnAtPoint(p);
if(row != -1 && column != -1) {
if(!dataGrid.isCellSelected(row, column)) {
dataGrid.selectCell(row, column, true);
}
getPopupMenu().show(dataGrid, p.x, p.y);
}
}
} else if(e.getSource() instanceof JTableHeader) {
JTableHeader columnHeader = (JTableHeader)e.getSource();
if(e.isPopupTrigger()) {
Point p = e.getPoint();
int column = columnHeader.columnAtPoint(p);
// action column
actionColumn = column;
if(column != -1) {
if(!dataGrid.isFullColumnSelected(column)) {
dataGrid.selectColumn(column);
}
getPopupMenu(COLUMNHEADER_POPUPMENU).show(columnHeader, p.x, p.y);
}
}
} else if(e.getSource() instanceof JLineBar || (e.getSource() instanceof Component && ((Component)e.getSource()).getParent() instanceof JLineBar)) {
Component rowHeader = (Component)e.getSource();
JLineBar lineBar = null;
if(rowHeader instanceof JLineBar) {
lineBar = (JLineBar)rowHeader;
} else {
lineBar = (JLineBar)rowHeader.getParent();
}
if(e.isPopupTrigger()) {
Point p = e.getPoint();
int row = lineBar.lineAtPoint(p);
// action row
actionRow = row;
if(row != -1) {
if(!dataGrid.isFullRowSelected(row)) {
dataGrid.selectRow(row);
}
getPopupMenu(ROWHEADER_POPUPMENU).show(rowHeader, p.x, p.y);
}
}
} else if(e.getSource() instanceof JToolBar || e.getSource() instanceof JMenuBar) {
JComponent c = (JComponent)e.getSource();
if(e.isPopupTrigger()) {
Point p = e.getPoint();
getPopupMenu(TOOLBAR_POPUPMENU).show(c, p.x, p.y);
}
}
}
// PropertyChangeListener
public void propertyChange(PropertyChangeEvent e) {
String property = e.getPropertyName();
if(property.equals("model")) {
// clear the undo edit
resetUndoManager();
} else if(property.equals("columnModel")) {
TableColumnModel oldValue = (TableColumnModel)e.getOldValue();
TableColumnModel newValue = (TableColumnModel)e.getNewValue();
oldValue.getSelectionModel().removeListSelectionListener(this);
newValue.getSelectionModel().addListSelectionListener(this);
} else if(property.equals("selectionModel")) {
ListSelectionModel oldValue = (ListSelectionModel)e.getOldValue();
ListSelectionModel newValue = (ListSelectionModel)e.getNewValue();
oldValue.removeListSelectionListener(this);
newValue.addListSelectionListener(this);
} else if(property.equals("freezeRow") || property.equals("freezeColumn")) {
int freezeRow = dataGrid.getFreezeRow();
int freezeColumn = dataGrid.getFreezeColumn();
boolean freeze = false;
if(freezeRow > 0 || freezeColumn > 0) {
freeze = true;
}
configureFreezeAction(freeze);
if(getWorkBook() != null) {
WorkSheet workSheet = getWorkBook().getSelectedSheet();
if(workSheet != null && (workSheet.getModel() == dataGrid.getModel() || workSheet.getModel() == dataGrid.getDataGridModel())) {
workSheet.setFreezeCell(freezeRow, freezeColumn);
}
}
}
}
public void mouseDragged(MouseEvent e) {
}
private Node saveNode;
public void mouseMoved(MouseEvent e) {
JDataGrid dataGrid = (JDataGrid)e.getSource();
Point p = e.getPoint();
int row = dataGrid.rowAtPoint(p);
int column = dataGrid.columnAtPoint(p);
if(row != -1 && column != -1) {
AttributeSet a = dataGrid.getCellAttributes(row, column);
if(a != null) {
CellStyle.Comment comment = CellStyle.getComment(a);
if(comment != null && comment.getHelper() instanceof Node) {
if(saveNode != null) {
saveNode.setVisible(false);
saveNode = null;
}
Node node = (Node)comment.getHelper();
node.setVisible(true);
this.saveNode = node;
return;
}
}
}
if(saveNode != null) {
saveNode.setVisible(false);
saveNode = null;
}
}
}
private void showStatus(String status) {
getStatusBar().setText(status);
}
private JPopupMenu getPopupMenu() {
return getPopupMenu("datagrid-popupmenu");
}
private JPopupMenu getPopupMenu(String name) {
JPopupMenu popupMenu = null;
if(uiMap != null) {
popupMenu = (JPopupMenu)uiMap.get(name);
}
if(popupMenu == null) {
popupMenu = createPopupMenu(name);
uiMap.put(name, popupMenu);
addListeners(popupMenu);
}
return popupMenu;
}
private void addListeners(Container comp) {
if(comp instanceof MenuElement) {
MenuElement[] mes = ((MenuElement)comp).getSubElements();
addListeners(mes);
} else {
for(int i=0,n=comp.getComponentCount(); i 90) {
thumbnail = new ImageIcon(
tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
} else {
thumbnail = tmpIcon;
}
}
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (prop == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {
if(isShowing()) {
loadImage((File) e.getNewValue());
repaint();
}
}
}
protected void paintComponent(Graphics g) {
if(thumbnail != null) {
int x = getWidth()/2 - thumbnail.getIconWidth()/2;
int y = getHeight()/2 - thumbnail.getIconHeight()/2;
if(y < 0) {
y = 0;
}
if(x < 5) {
x = 5;
}
thumbnail.paintIcon(this, g, x, y);
}
}
}
/**
* Returns the JScrollPane the JDataGrid use.
*
* @since JDataGrid 2.2.3
*/
public JScrollPane getScrollPane() {
return scrollPane;
}
/**
* Sets the JScrollPane the JDataGrid use.
*
* @since JDataGrid 2.2.3
*/
public void setScrollPane(JScrollPane scrollPane) {
JScrollPane oldValue = this.scrollPane;
this.scrollPane = scrollPane;
if (oldValue != scrollPane) {
if (centerPanel != null) {
if (oldValue != null) {
configureChangeListener(oldValue, false);
centerPanel.remove(oldValue);
}
if (scrollPane != null) {
centerPanel.add(scrollPane, BorderLayout.CENTER);
configureChangeListener(scrollPane, true);
}
}
}
}
private boolean autoAdjustRowColumCount;
/**
* Determines whether auto adjust the row and column count.
*
* @since JDataGrid 2.2.3
*/
public boolean isAutoAdjustRowColumCount() {
return autoAdjustRowColumCount;
}
/**
* Sets whether auto adjust the row and column count.
*
* @since JDataGrid 2.2.3
*/
public void setAutoAdjustRowColumCount(boolean autoAdjustRowColumCount) {
this.autoAdjustRowColumCount = autoAdjustRowColumCount;
}
private ChangeListener handler1;
private ChangeListener handler2;
private void configureChangeListener(JScrollPane scrollPane, boolean add) {
if (add) {
handler1 = new ChangeHandler(true);
handler2 = new ChangeHandler(false);
scrollPane.getVerticalScrollBar().getModel().addChangeListener(handler2);
scrollPane.getHorizontalScrollBar().getModel().addChangeListener(handler1);
}
else {
scrollPane.getVerticalScrollBar().getModel().removeChangeListener(handler2);
scrollPane.getHorizontalScrollBar().getModel().removeChangeListener(handler1);
}
}
class ChangeHandler implements ChangeListener {
private boolean column;
public ChangeHandler(boolean column) {
this.column = column;
}
public void stateChanged(ChangeEvent e) {
if (isAutoAdjustRowColumCount()) {
BoundedRangeModel model = (BoundedRangeModel) e.getSource();
if (model.getValue() + model.getExtent() >= model.getMaximum()) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DataGridModel m = getDataGrid().getDataGridModel();
if (column) {
m.setColumnCount(m.getColumnCount() + 1);
}
else {
m.setRowCount(m.getRowCount() + 1);
}
}
});
}
}
}
}
}