johnmarco
asked on
Add JButton to the code
I know how to add a JBUTTON, I did it several times in several small projects and did not have any issue.
Can someone please help me to a simple stupid JBUTTON to the code below, it is really not important how it will be called, I just want to see a JBUTTON on this code below, I have the skills to add functionalities to the code:
Please do not gie links, saying that check that out, I have hunders of tutorials saying how to a JBUTTON and they do work, but my try-outs on this code did not work and I already spent almost a day, Thank you
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v ersion");
if (vers.compareTo("1.3") < 0) {
System.out.println("Please use Java 1.3 or above.");
//System.exit(1);
}
try {
UIManager.setLookAndFeel(" javax.swin g.plaf.met al.MetalLo okAndFeel" );
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne w WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add (sp.getScr ollPane()) ;
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f orName("ja va.lang.Ob ject" ), _renderer );
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread Sheet() Can't modify renderer");
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr ue);
setSelectionMode(ListSelec tionModel. SINGLE_INT ERVAL_SELE CTION);
getSelectionModel().addLis tSelection Listener( new ListSelectionListener() {
public void valueChanged(ListSelection Event ev) {
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo l.length];
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c onvertColu mnIndexToM odel(selCo l[c])];
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn (0);
TableCellRenderer aRenderer = getTableHeader().getDefaul tRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn (0);
aRenderer = aColumn.getHeaderRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend ererCompon ent(this,
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground() ;
Color aForeground = aComponent.getForeground() ;
Border border = (Border)UIManager.getDefau lts().get( "TableHead er.cellBor der");
Insets insets = border.getBorderInsets(tab leHeader);
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null );
Dimension dim = new Dimension( metrics.stringWidth("999") +insets.ri ght+insets .left,
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii +1), SwingConstants.CENTER);
lbl.setFont(aFont);
lbl.setBackground(aBackgro und);
lbl.setForeground(aForegro und);
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A UTO_RESIZE _OFF);
Dimension dimScpViewport = getPreferredScrollableView portSize() ;
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot alColumnWi dth()/_num Col;
else
dimScpViewport.width = getColumnModel().getTotalC olumnWidth ();
setPreferredScrollableView portSize(d imScpViewp ort);
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel( column);
_model.setEditMode(row, convertColumnIndexToModel( column));
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven t ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve nt ev) {
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE LEASED) && (modifiers==InputEvent.BUT TON3_MASK) ) {
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals e);
else {
_popupMenu.setTargetCells( _selection );
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x +ev.getX() +1, p.y+ev.getY()+1);
_popupMenu.setVisible(true );
}
}
}
super.processMouseEvent(ev );
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi ngConstant s.CENTER);
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon ent (JTable table, Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun d);
setBackground(sc.backgroun d);
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic k to change the cell's colors.");
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli ck to select a cell, " +
"double-click to edit.");
}
return this;
}
}
}
Can someone please help me to a simple stupid JBUTTON to the code below, it is really not important how it will be called, I just want to see a JBUTTON on this code below, I have the skills to add functionalities to the code:
Please do not gie links, saying that check that out, I have hunders of tutorials saying how to a JBUTTON and they do work, but my try-outs on this code did not work and I already spent almost a day, Thank you
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v
if (vers.compareTo("1.3") < 0) {
System.out.println("Please
//System.exit(1);
}
try {
UIManager.setLookAndFeel("
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr
setSelectionMode(ListSelec
getSelectionModel().addLis
public void valueChanged(ListSelection
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn
TableCellRenderer aRenderer = getTableHeader().getDefaul
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn
aRenderer = aColumn.getHeaderRenderer(
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground()
Color aForeground = aComponent.getForeground()
Border border = (Border)UIManager.getDefau
Insets insets = border.getBorderInsets(tab
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null
Dimension dim = new Dimension( metrics.stringWidth("999")
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii
lbl.setFont(aFont);
lbl.setBackground(aBackgro
lbl.setForeground(aForegro
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A
Dimension dimScpViewport = getPreferredScrollableView
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot
else
dimScpViewport.width = getColumnModel().getTotalC
setPreferredScrollableView
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel(
_model.setEditMode(row, convertColumnIndexToModel(
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent
_model.setDisplayMode(_edi
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven
_model.setDisplayMode(_edi
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals
else {
_popupMenu.setTargetCells(
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x
_popupMenu.setVisible(true
}
}
}
super.processMouseEvent(ev
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun
setBackground(sc.backgroun
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli
"double-click to edit.");
}
return this;
}
}
}
ASKER
Please adjust the JButton in my code, if you can not do it, please do not respond anything or post anything.
Apply the JBUTTON code in my code, do not come with completely another code,
Cheers
Apply the JBUTTON code in my code, do not come with completely another code,
Cheers
Knowing WHERE you want the JButton would really help (unless you said the location and I missed it)
In any case look at lines 28, 224-242 and 417-448 Hope this Helps!!!
========================== ========== ========== ========== ========== ========== =====
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
// Declare your JButton to allow some interaction
private JButton yourFileJButton;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v ersion");
if (vers.compareTo("1.3") < 0) {
System.out.println("Please use Java 1.3 or above.");
//System.exit(1);
}
try {
UIManager.setLookAndFeel(" javax.swin g.plaf.met al.MetalLo okAndFeel" );
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne w WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add (sp.getScr ollPane()) ;
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f orName("ja va.lang.Ob ject" ), _renderer );
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread Sheet() Can't modify renderer");
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr ue);
setSelectionMode(ListSelec tionModel. SINGLE_INT ERVAL_SELE CTION);
getSelectionModel().addLis tSelection Listener( new ListSelectionListener() {
public void valueChanged(ListSelection Event ev) {
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo l.length];
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c onvertColu mnIndexToM odel(selCo l[c])];
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn (0);
TableCellRenderer aRenderer = getTableHeader().getDefaul tRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn (0);
aRenderer = aColumn.getHeaderRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend ererCompon ent(this,
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground() ;
Color aForeground = aComponent.getForeground() ;
Border border = (Border)UIManager.getDefau lts().get( "TableHead er.cellBor der");
Insets insets = border.getBorderInsets(tab leHeader);
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null );
Dimension dim = new Dimension( metrics.stringWidth("999") +insets.ri ght+insets .left,
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii +1), SwingConstants.CENTER);
lbl.setFont(aFont);
lbl.setBackground(aBackgro und);
lbl.setForeground(aForegro und);
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// This sets up yourFileJButton
// Not Sure WHERE you wanted it but you place the block where you want
yourFileJButton = new JButton();
yourFileJButton.setBounds( 5, 600, 130, 40 );
yourFileJButton.setText( "your button" );
contentPane.add( yourFileJButton );
yourFileJButton.addActionL istener(
new ActionListener() // anonymous inner class
{
// event handler called when yourFileJButton is clicked
public void actionPerformed( ActionEvent event )
{
yourFileJButtonActionPerfo rmed( event );
}
} // end anonymous inner class
); // end call to addActionListener
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A UTO_RESIZE _OFF);
Dimension dimScpViewport = getPreferredScrollableView portSize() ;
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot alColumnWi dth()/_num Col;
else
dimScpViewport.width = getColumnModel().getTotalC olumnWidth ();
setPreferredScrollableView portSize(d imScpViewp ort);
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel( column);
_model.setEditMode(row, convertColumnIndexToModel( column));
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven t ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve nt ev) {
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE LEASED) && (modifiers==InputEvent.BUT TON3_MASK) ) {
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals e);
else {
_popupMenu.setTargetCells( _selection );
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x +ev.getX() +1, p.y+ev.getY()+1);
_popupMenu.setVisible(true );
}
}
}
super.processMouseEvent(ev );
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi ngConstant s.CENTER);
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon ent (JTable table, Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun d);
setBackground(sc.backgroun d);
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic k to change the cell's colors.");
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli ck to select a cell, " +
"double-click to edit.");
}
return this;
}
}
}
/* // Then you could use a method for the button
* // You said you already knew how to do this
* // But I placed an example here anyway (commented out)
*
*
private void openFileJButtonActionPerfo rmed( ActionEvent event )
{
// Method action to try here
try
{
// Something
// change state of JButton if you want
yourFileJButton.setEnabled ( false );
;
}
catch ( IOException exception )
{
JOptionPane.showMessageDia log(null,
"Sorry there is problem with something",
"Blah Blah Blah something isn't right",JOptionPane.INFORMA TION_MESSA GE);
}
// end open file
// reset JButton to initial state
resetUserInput();
} // end method yourFileJButtonActionPerfo rmed*/
In any case look at lines 28, 224-242 and 417-448 Hope this Helps!!!
==========================
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
// Declare your JButton to allow some interaction
private JButton yourFileJButton;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v
if (vers.compareTo("1.3") < 0) {
System.out.println("Please
//System.exit(1);
}
try {
UIManager.setLookAndFeel("
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr
setSelectionMode(ListSelec
getSelectionModel().addLis
public void valueChanged(ListSelection
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn
TableCellRenderer aRenderer = getTableHeader().getDefaul
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn
aRenderer = aColumn.getHeaderRenderer(
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground()
Color aForeground = aComponent.getForeground()
Border border = (Border)UIManager.getDefau
Insets insets = border.getBorderInsets(tab
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null
Dimension dim = new Dimension( metrics.stringWidth("999")
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii
lbl.setFont(aFont);
lbl.setBackground(aBackgro
lbl.setForeground(aForegro
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// This sets up yourFileJButton
// Not Sure WHERE you wanted it but you place the block where you want
yourFileJButton = new JButton();
yourFileJButton.setBounds(
yourFileJButton.setText( "your button" );
contentPane.add( yourFileJButton );
yourFileJButton.addActionL
new ActionListener() // anonymous inner class
{
// event handler called when yourFileJButton is clicked
public void actionPerformed( ActionEvent event )
{
yourFileJButtonActionPerfo
}
} // end anonymous inner class
); // end call to addActionListener
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A
Dimension dimScpViewport = getPreferredScrollableView
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot
else
dimScpViewport.width = getColumnModel().getTotalC
setPreferredScrollableView
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel(
_model.setEditMode(row, convertColumnIndexToModel(
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent
_model.setDisplayMode(_edi
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven
_model.setDisplayMode(_edi
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals
else {
_popupMenu.setTargetCells(
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x
_popupMenu.setVisible(true
}
}
}
super.processMouseEvent(ev
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun
setBackground(sc.backgroun
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli
"double-click to edit.");
}
return this;
}
}
}
/* // Then you could use a method for the button
* // You said you already knew how to do this
* // But I placed an example here anyway (commented out)
*
*
private void openFileJButtonActionPerfo
{
// Method action to try here
try
{
// Something
// change state of JButton if you want
yourFileJButton.setEnabled
;
}
catch ( IOException exception )
{
JOptionPane.showMessageDia
"Sorry there is problem with something",
"Blah Blah Blah something isn't right",JOptionPane.INFORMA
}
// end open file
// reset JButton to initial state
resetUserInput();
} // end method yourFileJButtonActionPerfo
ASKER
The location of the button is not that important, it can on the top or at the bottom.
When I run your code, I get an error message at these 2 lines:
contentPane.add( yourFileJButton );
yourFileJButtonActionPerfo rmed( event );
Please correct
When I run your code, I get an error message at these 2 lines:
contentPane.add( yourFileJButton );
yourFileJButtonActionPerfo
Please correct
ASKER
Exception in thread "main" java.lang.NullPointerExcep tion
at tmanfe.spreadsheet.SpreadS heet.<init >(SpreadSh eet.java:2 32)
at tmanfe.spreadsheet.SpreadS heet.<init >(SpreadSh eet.java:2 72)
at tmanfe.spreadsheet.SpreadS heet.main( SpreadShee t.java:76)
Did you try running it? Please modify and adjust and let it run, thanks.
at tmanfe.spreadsheet.SpreadS
at tmanfe.spreadsheet.SpreadS
at tmanfe.spreadsheet.SpreadS
Did you try running it? Please modify and adjust and let it run, thanks.
This compiled fine for me (I did have to make some changes-created specific class and interface method for the content pane)
Remember there is an example of the button usage at the bottom but again you SAID you were well versed with skillz to implement your buttons!
The interface method can be called from the event thread if need be.
Hope this helps!
========================== ========== ========== ========== ========== ========== ========== =========
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v ersion");
if (vers.compareTo("1.3") < 0) {
System.out.println("Please use Java 1.3 or above.");
//System.exit(1);
}
try {
UIManager.setLookAndFeel(" javax.swin g.plaf.met al.MetalLo okAndFeel" );
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne w WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add (sp.getScr ollPane()) ;
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f orName("ja va.lang.Ob ject" ), _renderer );
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread Sheet() Can't modify renderer");
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr ue);
setSelectionMode(ListSelec tionModel. SINGLE_INT ERVAL_SELE CTION);
getSelectionModel().addLis tSelection Listener( new ListSelectionListener() {
public void valueChanged(ListSelection Event ev) {
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo l.length];
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c onvertColu mnIndexToM odel(selCo l[c])];
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn (0);
TableCellRenderer aRenderer = getTableHeader().getDefaul tRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn (0);
aRenderer = aColumn.getHeaderRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend ererCompon ent(this,
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground() ;
Color aForeground = aComponent.getForeground() ;
Border border = (Border)UIManager.getDefau lts().get( "TableHead er.cellBor der");
Insets insets = border.getBorderInsets(tab leHeader);
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null );
Dimension dim = new Dimension( metrics.stringWidth("999") +insets.ri ght+insets .left,
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii +1), SwingConstants.CENTER);
lbl.setFont(aFont);
lbl.setBackground(aBackgro und);
lbl.setForeground(aForegro und);
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// create and position GUI components; register event handlers
class ExampleButton extends JFrame{
// Declare your JButton to allow some interaction
private JButton yourFileJButton;
private void createUserInterface()
{
// get content pane for attaching GUI components
Container contentPane = getContentPane();
// enable explicit positioning of GUI components
contentPane.setLayout( null );
// set up yourFileJButton
yourFileJButton = new JButton();
yourFileJButton.setBounds( 5, 600, 130, 40 );
yourFileJButton.setText( "your button" );
contentPane.add( yourFileJButton );
yourFileJButton.addActionL istener(
new ActionListener() // anonymous inner class
{
// event handler called when yourFileJButton is clicked
public void actionPerformed( ActionEvent event )
{
//yourFileJButtonActionPer formed( event );
}
} // end anonymous inner class
); // end call to addActionListener
} // end method createUserInterface
}
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A UTO_RESIZE _OFF);
Dimension dimScpViewport = getPreferredScrollableView portSize() ;
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot alColumnWi dth()/_num Col;
else
dimScpViewport.width = getColumnModel().getTotalC olumnWidth ();
setPreferredScrollableView portSize(d imScpViewp ort);
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel( column);
_model.setEditMode(row, convertColumnIndexToModel( column));
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven t ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve nt ev) {
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE LEASED) && (modifiers==InputEvent.BUT TON3_MASK) ) {
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals e);
else {
_popupMenu.setTargetCells( _selection );
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x +ev.getX() +1, p.y+ev.getY()+1);
_popupMenu.setVisible(true );
}
}
}
super.processMouseEvent(ev );
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi ngConstant s.CENTER);
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon ent (JTable table, Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun d);
setBackground(sc.backgroun d);
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic k to change the cell's colors.");
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli ck to select a cell, " +
"double-click to edit.");
}
return this;
}
}
}
/* // Then you could use a method for the button
* // You said you already knew how to do this
* // But I placed an example here anyway (commented out)
*
*
private void openFileJButtonActionPerfo rmed( ActionEvent event )
{
// Method action to try here
try
{
// Something
// change state of JButton if you want
yourFileJButton.setEnabled ( false );
;
}
catch ( IOException exception )
{
JOptionPane.showMessageDia log(null,
"Sorry there is problem with something",
"Blah Blah Blah something isn't right",JOptionPane.INFORMA TION_MESSA GE);
}
// end open file
// reset JButton to initial states
resetUserInput();
} // end method yourFileJButtonActionPerfo rmed*/
Remember there is an example of the button usage at the bottom but again you SAID you were well versed with skillz to implement your buttons!
The interface method can be called from the event thread if need be.
Hope this helps!
==========================
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v
if (vers.compareTo("1.3") < 0) {
System.out.println("Please
//System.exit(1);
}
try {
UIManager.setLookAndFeel("
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr
setSelectionMode(ListSelec
getSelectionModel().addLis
public void valueChanged(ListSelection
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn
TableCellRenderer aRenderer = getTableHeader().getDefaul
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn
aRenderer = aColumn.getHeaderRenderer(
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground()
Color aForeground = aComponent.getForeground()
Border border = (Border)UIManager.getDefau
Insets insets = border.getBorderInsets(tab
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null
Dimension dim = new Dimension( metrics.stringWidth("999")
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii
lbl.setFont(aFont);
lbl.setBackground(aBackgro
lbl.setForeground(aForegro
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// create and position GUI components; register event handlers
class ExampleButton extends JFrame{
// Declare your JButton to allow some interaction
private JButton yourFileJButton;
private void createUserInterface()
{
// get content pane for attaching GUI components
Container contentPane = getContentPane();
// enable explicit positioning of GUI components
contentPane.setLayout( null );
// set up yourFileJButton
yourFileJButton = new JButton();
yourFileJButton.setBounds(
yourFileJButton.setText( "your button" );
contentPane.add( yourFileJButton );
yourFileJButton.addActionL
new ActionListener() // anonymous inner class
{
// event handler called when yourFileJButton is clicked
public void actionPerformed( ActionEvent event )
{
//yourFileJButtonActionPer
}
} // end anonymous inner class
); // end call to addActionListener
} // end method createUserInterface
}
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A
Dimension dimScpViewport = getPreferredScrollableView
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot
else
dimScpViewport.width = getColumnModel().getTotalC
setPreferredScrollableView
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel(
_model.setEditMode(row, convertColumnIndexToModel(
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent
_model.setDisplayMode(_edi
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven
_model.setDisplayMode(_edi
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals
else {
_popupMenu.setTargetCells(
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x
_popupMenu.setVisible(true
}
}
}
super.processMouseEvent(ev
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun
setBackground(sc.backgroun
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli
"double-click to edit.");
}
return this;
}
}
}
/* // Then you could use a method for the button
* // You said you already knew how to do this
* // But I placed an example here anyway (commented out)
*
*
private void openFileJButtonActionPerfo
{
// Method action to try here
try
{
// Something
// change state of JButton if you want
yourFileJButton.setEnabled
;
}
catch ( IOException exception )
{
JOptionPane.showMessageDia
"Sorry there is problem with something",
"Blah Blah Blah something isn't right",JOptionPane.INFORMA
}
// end open file
// reset JButton to initial states
resetUserInput();
} // end method yourFileJButtonActionPerfo
ASKER
Yep, you are right, it compiled without any problem. But when I run, I can not see any button anywhere. That was my problem and that is why I could not figure it out. Do you think that the cause is not using "Layout", that is really wierd. Heeelp !!!
Ah I C now what you REALLY need. Didn't quite UNDERSTAND the scope of what you wanted just thought you wanted to see if the JButton COULD be added period.
Ok.. here's the deal.
What you have to do is to provide a TableCellRenderer implementation if you want to display buttons in the JTable. The TableCellRenderer interface contains only one method, getTableCellRendererCompon ent(...), which returns a java.awt.Component that knows how to draw the contents of a specific cell- this is required so that you can SEE the button!
I'll post some code in a fe minutes that demonstrates this (with YOUR CODE).
Ok.. here's the deal.
What you have to do is to provide a TableCellRenderer implementation if you want to display buttons in the JTable. The TableCellRenderer interface contains only one method, getTableCellRendererCompon
I'll post some code in a fe minutes that demonstrates this (with YOUR CODE).
Before we get into renderers try this!
========================== ========== ========== ========== ========== ========== ========== =
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v ersion");
if (vers.compareTo("1.3") < 0) {
System.out.println("Please use Java 1.3 or above.");
//System.exit(1);
}
try {
UIManager.setLookAndFeel(" javax.swin g.plaf.met al.MetalLo okAndFeel" );
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne w WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add (sp.getScr ollPane()) ;
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f orName("ja va.lang.Ob ject" ), _renderer );
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread Sheet() Can't modify renderer");
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr ue);
setSelectionMode(ListSelec tionModel. SINGLE_INT ERVAL_SELE CTION);
getSelectionModel().addLis tSelection Listener( new ListSelectionListener() {
public void valueChanged(ListSelection Event ev) {
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo l.length];
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c onvertColu mnIndexToM odel(selCo l[c])];
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn (0);
TableCellRenderer aRenderer = getTableHeader().getDefaul tRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn (0);
aRenderer = aColumn.getHeaderRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend ererCompon ent(this,
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground() ;
Color aForeground = aComponent.getForeground() ;
Border border = (Border)UIManager.getDefau lts().get( "TableHead er.cellBor der");
Insets insets = border.getBorderInsets(tab leHeader);
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null );
Dimension dim = new Dimension( metrics.stringWidth("999") +insets.ri ght+insets .left,
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii +1), SwingConstants.CENTER);
lbl.setFont(aFont);
lbl.setBackground(aBackgro und);
lbl.setForeground(aForegro und);
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// create and position GUI components; register event handlers
class YourButton extends JPanel {
public YourButton() {
JButton aButton = new JButton("Button");
aButton.getAccessibleConte xt().
setAccessibleName("Button" );
String desc = "Here's your button button";
aButton.getAccessibleConte xt().
setAccessibleDescription(d esc);
add(aButton);
}
void buttonInterface(){
JFrame frame = new JFrame(
"YourButton");
frame.getContentPane().
add(new YourButton(),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A UTO_RESIZE _OFF);
Dimension dimScpViewport = getPreferredScrollableView portSize() ;
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot alColumnWi dth()/_num Col;
else
dimScpViewport.width = getColumnModel().getTotalC olumnWidth ();
setPreferredScrollableView portSize(d imScpViewp ort);
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel( column);
_model.setEditMode(row, convertColumnIndexToModel( column));
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven t ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve nt ev) {
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE LEASED) && (modifiers==InputEvent.BUT TON3_MASK) ) {
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals e);
else {
_popupMenu.setTargetCells( _selection );
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x +ev.getX() +1, p.y+ev.getY()+1);
_popupMenu.setVisible(true );
}
}
}
super.processMouseEvent(ev );
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi ngConstant s.CENTER);
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon ent (JTable table, Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun d);
setBackground(sc.backgroun d);
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic k to change the cell's colors.");
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli ck to select a cell, " +
"double-click to edit.");
}
return this;
}
}
}
/* // Then you could use a method for the button
* // You said you already knew how to do this
* // But I placed an example here anyway (commented out)
*
*
private void openFileJButtonActionPerfo rmed( ActionEvent event )
{
// Method action to try here
try
{
// Something
// change state of JButton if you want
yourFileJButton.setEnabled ( false );
;
}
catch ( IOException exception )
{
JOptionPane.showMessageDia log(null,
"Sorry there is problem with something",
"Blah Blah Blah something isn't right",JOptionPane.INFORMA TION_MESSA GE);
}
// end open file
// reset JButton to initial states
resetUserInput();
} // end method yourFileJButtonActionPerfo rmed*/
==========================
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v
if (vers.compareTo("1.3") < 0) {
System.out.println("Please
//System.exit(1);
}
try {
UIManager.setLookAndFeel("
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr
setSelectionMode(ListSelec
getSelectionModel().addLis
public void valueChanged(ListSelection
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn
TableCellRenderer aRenderer = getTableHeader().getDefaul
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn
aRenderer = aColumn.getHeaderRenderer(
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground()
Color aForeground = aComponent.getForeground()
Border border = (Border)UIManager.getDefau
Insets insets = border.getBorderInsets(tab
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null
Dimension dim = new Dimension( metrics.stringWidth("999")
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii
lbl.setFont(aFont);
lbl.setBackground(aBackgro
lbl.setForeground(aForegro
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// create and position GUI components; register event handlers
class YourButton extends JPanel {
public YourButton() {
JButton aButton = new JButton("Button");
aButton.getAccessibleConte
setAccessibleName("Button"
String desc = "Here's your button button";
aButton.getAccessibleConte
setAccessibleDescription(d
add(aButton);
}
void buttonInterface(){
JFrame frame = new JFrame(
"YourButton");
frame.getContentPane().
add(new YourButton(),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A
Dimension dimScpViewport = getPreferredScrollableView
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot
else
dimScpViewport.width = getColumnModel().getTotalC
setPreferredScrollableView
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel(
_model.setEditMode(row, convertColumnIndexToModel(
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent
_model.setDisplayMode(_edi
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven
_model.setDisplayMode(_edi
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals
else {
_popupMenu.setTargetCells(
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x
_popupMenu.setVisible(true
}
}
}
super.processMouseEvent(ev
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun
setBackground(sc.backgroun
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli
"double-click to edit.");
}
return this;
}
}
}
/* // Then you could use a method for the button
* // You said you already knew how to do this
* // But I placed an example here anyway (commented out)
*
*
private void openFileJButtonActionPerfo
{
// Method action to try here
try
{
// Something
// change state of JButton if you want
yourFileJButton.setEnabled
;
}
catch ( IOException exception )
{
JOptionPane.showMessageDia
"Sorry there is problem with something",
"Blah Blah Blah something isn't right",JOptionPane.INFORMA
}
// end open file
// reset JButton to initial states
resetUserInput();
} // end method yourFileJButtonActionPerfo
ASKER
I still can not see any button on the code, It runs sucessfully. I appreciate your effort and help but please give one more try, we are almost there.
Here ya go, buttons from renderering class and a cell editor also in case u need it :>)
========================== ========== ========== ========== ========== ========== ========== ========
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v ersion");
if (vers.compareTo("1.3") < 0) {
System.out.println("Please use Java 1.3 or above.");
//System.exit(1);
}
try {
UIManager.setLookAndFeel(" javax.swin g.plaf.met al.MetalLo okAndFeel" );
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne w WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add (sp.getScr ollPane()) ;
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f orName("ja va.lang.Ob ject" ), _renderer );
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread Sheet() Can't modify renderer");
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr ue);
setSelectionMode(ListSelec tionModel. SINGLE_INT ERVAL_SELE CTION);
getSelectionModel().addLis tSelection Listener( new ListSelectionListener() {
public void valueChanged(ListSelection Event ev) {
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo l.length];
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c onvertColu mnIndexToM odel(selCo l[c])];
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn (0);
TableCellRenderer aRenderer = getTableHeader().getDefaul tRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn (0);
aRenderer = aColumn.getHeaderRenderer( );
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend ererCompon ent(this,
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground() ;
Color aForeground = aComponent.getForeground() ;
Border border = (Border)UIManager.getDefau lts().get( "TableHead er.cellBor der");
Insets insets = border.getBorderInsets(tab leHeader);
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null );
Dimension dim = new Dimension( metrics.stringWidth("999") +insets.ri ght+insets .left,
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii +1), SwingConstants.CENTER);
lbl.setFont(aFont);
lbl.setBackground(aBackgro und);
lbl.setForeground(aForegro und);
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// create and position GUI components; register event handlers
JTable table = new JTable( 6,4 )
{
public TableCellRenderer getCellRenderer(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn (column);
TableCellRenderer renderer = tableColumn.getCellRendere r();
if (renderer == null) {
Class c = getColumnClass(column);
if( c.equals(Object.class) )
{
Object o = getValueAt(row,column);
if( o != null )
c = getValueAt(row,column).get Class();
}
renderer = getDefaultRenderer(c);
}
return renderer;
}
public TableCellEditor getCellEditor(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn (column);
TableCellEditor editor = tableColumn.getCellEditor( );
if (editor == null) {
Class c = getColumnClass(column);
if( c.equals(Object.class) )
{
Object o = getValueAt(row,column);
if( o != null )
c = getValueAt(row,column).get Class();
}
editor = getDefaultEditor(c);
}
return editor;
}
};
// Buttons
table.setValueAt( new JButton("Button"), 0, 0 );
table.setValueAt( new JButton("Button"), 0, 1 );
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A UTO_RESIZE _OFF);
Dimension dimScpViewport = getPreferredScrollableView portSize() ;
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot alColumnWi dth()/_num Col;
else
dimScpViewport.width = getColumnModel().getTotalC olumnWidth ();
setPreferredScrollableView portSize(d imScpViewp ort);
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel( column);
_model.setEditMode(row, convertColumnIndexToModel( column));
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven t ev) {
_model.setDisplayMode(_edi tedModelRo w, _editedModelCol);
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve nt ev) {
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE LEASED) && (modifiers==InputEvent.BUT TON3_MASK) ) {
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals e);
else {
_popupMenu.setTargetCells( _selection );
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x +ev.getX() +1, p.y+ev.getY()+1);
_popupMenu.setVisible(true );
}
}
}
super.processMouseEvent(ev );
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi ngConstant s.CENTER);
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon ent (JTable table, Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun d);
setBackground(sc.backgroun d);
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic k to change the cell's colors.");
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli ck to select a cell, " +
"double-click to edit.");
}
return this;
}
}
}
==========================
package tmanfe.spreadsheet;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;
public class SpreadSheet extends JTable {
/**
* Set this field to true and recompile
* to get debug traces
*/
public static final boolean DEBUG = true;
private JScrollPane _scp;
private CellMenu _popupMenu;
private SpreadSheetModel _model;
private int _numRow;
private int _numCol;
private int _editedModelRow;
private int _editedModelCol;
/*
* GUI components used to tailored
* the SpreadSheet.
*/
private CellRenderer _renderer;
private Font _cellFont;
//private FontMetrics _metrics;
// Cells selected.
private Object [] _selection;
/**
* Start the spreadsheet into a JFrame.
* @param String[] The options passed on the command
* line. Not used.
*/
public static void main(String[] args) {
String vers = System.getProperty("java.v
if (vers.compareTo("1.3") < 0) {
System.out.println("Please
//System.exit(1);
}
try {
UIManager.setLookAndFeel("
} catch(Exception ex) {
System.out.println("Can't set look and feel MetalLookAndFeel");
System.exit(2);
}
JFrame frame = new JFrame("A Simple Spreadsheet");
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(ne
public void windowClosing(WindowEvent e) { System.exit(0); }
});
SpreadSheet sp = new SpreadSheet(40, 40);
/**
SheetCell[][] cells = new SheetCell[3][2];
cells[0][0] = new SheetCell(0 , 0, "1", null);
cells[1][0] = new SheetCell(0 , 1, "2", null);
cells[2][0] = new SheetCell(0 , 2, "3", null);
cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
SpreadSheet sp = new SpreadSheet(cells);
**/
frame.getContentPane().add
frame.pack();
frame.setVisible(true);
}
/**
* Build SpreadSheet of numCol columns and numRow rows.
*
* @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
* It must be a two dimensional rectangular array. If null, the cells are
* automatically created.
* @param numRow The number of rows
* @param numCol The number of columns
*
*/
private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {
super();
SheetCell foo[][];
if (cells!=null)
foo = cells;
else {
foo = new SheetCell[numRow][numCol];
for (int ii=0; ii<numRow; ii++) {
for (int jj=0; jj<numCol; jj++)
foo[ii][jj] = new SheetCell(ii, jj);
}
}
_numRow = numRow;
_numCol = numCol;
_cellFont = new Font("Times", Font.PLAIN, 20);
// Create the JScrollPane that includes the Table
_scp = new JScrollPane(this);
// Create the rendeder for the cells
_renderer = new CellRenderer();
try {
setDefaultRenderer(Class.f
} catch (ClassNotFoundException ex) {
if (DEBUG) System.out.println("Spread
}
_model = new SpreadSheetModel(foo, this);
setModel(_model);
/*
* Tune the selection mode
*/
// Allows row and collumn selections to exit at the same time
setCellSelectionEnabled(tr
setSelectionMode(ListSelec
getSelectionModel().addLis
public void valueChanged(ListSelection
int selRow[] = getSelectedRows();
int selCol[] = getSelectedColumns();
_selection = new Object[selRow.length*selCo
int indice = 0;
for (int r=0; r<selRow.length; r++) {
for (int c=0; c<selCol.length; c++) {
_selection[indice] =_model.cells[selRow[r]][c
indice++;
}
}
}
});
// Create a row-header to display row numbers.
// This row-header is made of labels whose Borders,
// Foregrounds, Backgrounds, and Fonts must be
// the one used for the table column headers.
// Also ensure that the row-header labels and the table
// rows have the same height.
TableColumn aColumn = getColumnModel().getColumn
TableCellRenderer aRenderer = getTableHeader().getDefaul
if (aRenderer==null) {
System.out.println(" Aouch !");
aColumn = getColumnModel().getColumn
aRenderer = aColumn.getHeaderRenderer(
if (aRenderer==null) {
System.out.println(" Aouch Aouch !");
System.exit(3);
}
}
Component aComponent = aRenderer.getTableCellRend
aColumn.getHeaderValue(),
false, false, -1, 0);
Font aFont = aComponent.getFont();
Color aBackground = aComponent.getBackground()
Color aForeground = aComponent.getForeground()
Border border = (Border)UIManager.getDefau
Insets insets = border.getBorderInsets(tab
FontMetrics metrics = getFontMetrics(_cellFont);
rowHeight = insets.bottom + metrics.getHeight() + insets.top;
/*
* Creating a panel to be used as the row header.
*
* Since I'm not using any LayoutManager,
* a call to setPreferredSize().
*/
JPanel pnl = new JPanel((LayoutManager)null
Dimension dim = new Dimension( metrics.stringWidth("999")
rowHeight*_numRow);
pnl.setPreferredSize(dim);
// Adding the row header labels
dim.height = rowHeight;
for (int ii=0; ii<_numRow; ii++) {
JLabel lbl = new JLabel(Integer.toString(ii
lbl.setFont(aFont);
lbl.setBackground(aBackgro
lbl.setForeground(aForegro
lbl.setBorder(border);
lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
pnl.add(lbl);
}
JViewport vp = new JViewport();
dim.height = rowHeight*_numRow;
vp.setViewSize(dim);
vp.setView(pnl);
_scp.setRowHeader(vp);
// create and position GUI components; register event handlers
JTable table = new JTable( 6,4 )
{
public TableCellRenderer getCellRenderer(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn
TableCellRenderer renderer = tableColumn.getCellRendere
if (renderer == null) {
Class c = getColumnClass(column);
if( c.equals(Object.class) )
{
Object o = getValueAt(row,column);
if( o != null )
c = getValueAt(row,column).get
}
renderer = getDefaultRenderer(c);
}
return renderer;
}
public TableCellEditor getCellEditor(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn
TableCellEditor editor = tableColumn.getCellEditor(
if (editor == null) {
Class c = getColumnClass(column);
if( c.equals(Object.class) )
{
Object o = getValueAt(row,column);
if( o != null )
c = getValueAt(row,column).get
}
editor = getDefaultEditor(c);
}
return editor;
}
};
// Buttons
table.setValueAt( new JButton("Button"), 0, 0 );
table.setValueAt( new JButton("Button"), 0, 1 );
// Set resize policy and make sure
// the table's size is tailored
// as soon as it gets drawn.
setAutoResizeMode(JTable.A
Dimension dimScpViewport = getPreferredScrollableView
if (_numRow>30) dimScpViewport.height = 30*rowHeight;
else dimScpViewport.height = _numRow*rowHeight;
if (_numCol>15)
dimScpViewport.width = 15*getColumnModel().getTot
else
dimScpViewport.width = getColumnModel().getTotalC
setPreferredScrollableView
resizeAndRepaint();
}
/**
* Build a numRow by numColumn SpreadSheet included
* in a JScrollPane. The associated model and the cells
* are automatically created.
*
* @param numRow The number of row in the spreadsheet
* @param numColumn The number of column in the spreadsheet
*/
public SpreadSheet(int numRow, int numColumn) {
this(null, numRow, numColumn);
}
/**
* Build a SpreadSheet included in a JScrollPane
* from the cells given as argument.
*
* @param cells[numRow][numColumn] A two dimensional rectangular
* array of cells to be used when
* creating the spreadsheet.
*/
public SpreadSheet(SheetCell cells[][]) {
this(cells, cells.length, cells[0].length);
}
/**
* Invoked when a cell edition starts.
* This method overrides and calls that of its super class.
*
* @param int The row to be edited
* @param int The column to be edited
* @param EventObject The firing event
* @return boolean false if for any reason the cell cannot be edited.
*/
public boolean editCellAt( int row, int column, EventObject ev) {
if (_editedModelRow != -1)
_model.setDisplayMode(_edi
_editedModelRow = row;
_editedModelCol = convertColumnIndexToModel(
_model.setEditMode(row, convertColumnIndexToModel(
return super.editCellAt(row, column, ev);
}
/**
* Invoked by the cell editor when a cell edition stops.
* This method override and calls that of its super class.
*
*/
public void editingStopped(ChangeEvent
_model.setDisplayMode(_edi
super.editingStopped(ev);
}
/**
* Invoked by the cell editor when a cell edition is cancelled.
* This method override and calls that of its super class.
*
*/
public void editingCanceled(ChangeEven
_model.setDisplayMode(_edi
super.editingCanceled(ev);
}
protected JScrollPane getScrollPane() { return _scp; }
public void processMouseEvent(MouseEve
int type = ev.getID();
int modifiers = ev.getModifiers();
if ( (type==MouseEvent.MOUSE_RE
if (_selection!=null) {
if (_popupMenu==null) _popupMenu = new CellMenu(this);
if (_popupMenu.isVisible())
_popupMenu.setVisible(fals
else {
_popupMenu.setTargetCells(
Point p = getLocationOnScreen();
_popupMenu.setLocation(p.x
_popupMenu.setVisible(true
}
}
}
super.processMouseEvent(ev
}
protected void release() { _model = null; }
public void setVisible(boolean flag) { _scp.setVisible(flag); }
/*
* This class is used to customize the cells rendering.
*/
public class CellRenderer extends JLabel implements TableCellRenderer {
private LineBorder _selectBorder;
private EmptyBorder _emptyBorder;
private Dimension _dim;
public CellRenderer() {
super();
_emptyBorder = new EmptyBorder(1, 2, 1, 2);
_selectBorder = new LineBorder(Color.red);
setOpaque(true);
setHorizontalAlignment(Swi
_dim = new Dimension();
_dim.height = 22;
_dim.width = 100;
setSize(_dim);
};
/**
*
* Method defining the renderer to be used
* when drawing the cells.
*
*/
public Component getTableCellRendererCompon
boolean isSelected,
boolean hasFocus,
int row, int column) {
SheetCell sc = (SheetCell)value;
setFont(_cellFont);
setText(sc.toString());
setForeground(sc.foregroun
setBackground(sc.backgroun
if (isSelected) {
setBorder(_selectBorder);
setToolTipText("Right-clic
} else {
setBorder(_emptyBorder);
setToolTipText("Single-Cli
"double-click to edit.");
}
return this;
}
}
}
ASKER
Great effort, I ran the code and still no button, did you run the code before you posted?
When I say a button, I mean a normal button, where you press and it does something. My purpose is to add buttons to this application like "Open", "Save", "New", "Quit".
Thanks again billions, I know that it will come, please one more try.
Cheers
When I say a button, I mean a normal button, where you press and it does something. My purpose is to add buttons to this application like "Open", "Save", "New", "Quit".
Thanks again billions, I know that it will come, please one more try.
Cheers
????? YES, I ran the last three post codes.
I understand the buttons and what you want - I need to know if you ran the LAST code sent.
And IF the buttons SHOW, once I know they show the hooks can be written (even you say you understand the button behavior structure-so no worries there right)
We just need to SHOW the buttons?
Do want the buttons in CELL?
A panel or a frame??
What do you need oh GREAT one LOL.
I understand the buttons and what you want - I need to know if you ran the LAST code sent.
And IF the buttons SHOW, once I know they show the hooks can be written (even you say you understand the button behavior structure-so no worries there right)
We just need to SHOW the buttons?
Do want the buttons in CELL?
A panel or a frame??
What do you need oh GREAT one LOL.
ASKER
I need just the buttons, ofcourse not on the cells, it can be on the panel or on the frame.
Yees, we just need to show the buttons. It might be above all the cells or below all the cells.
Yees, we just need to show the buttons. It might be above all the cells or below all the cells.
I need to know if you ran the LAST code sent - I would be REALLY suprised if THAT didn't work for you as I can see the buttons clearly on my compiler.
ASKER
That is really strange, please provide me a screenshot how the buttons are shown, I did run it but can not see any buttons.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Well...???
ASKER
Well, it still does not work. I tried the code on my friend's machine, it also does not work there.
But I do appreciate all your help, effort and patience.
I give you already 500 points, for me you deserved more than that but 500 is the maximum.
Whenever you come to Belgium, let me know, I will offer you Belgian bier :-)
But I do appreciate all your help, effort and patience.
I give you already 500 points, for me you deserved more than that but 500 is the maximum.
Whenever you come to Belgium, let me know, I will offer you Belgian bier :-)
Belgium??? DUDE, I stayed in St Truden for a YEAR.
Uesed to go to Hasselt to party all the time - also to Borgloon
Hoe ist et met yer? Hoe gat ut?
WOW!!! You're awesome!
So sorry I could not help you - TRIED my BEST - if you get it fixed PLEASE lemme know what you did.
Uesed to go to Hasselt to party all the time - also to Borgloon
Hoe ist et met yer? Hoe gat ut?
WOW!!! You're awesome!
So sorry I could not help you - TRIED my BEST - if you get it fixed PLEASE lemme know what you did.
checkout here..
http://www.jroller.com/page/dhall/20050825
/**
* This simple application creates a GUI for a spreadsheet application.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Spreadsheet implements ActionListener {
CellEditor editor;
JButton recomputeButton;
public static Border cellNormalBorder;
public static Border cellSelectedBorder;
public static Dimension cellPreferredSize = new Dimension(76, 12);
public static final int ROWS = 25;
public static final int COLUMNS = 10;
public static final String[] COLUMN_LETTER = {
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
/**
* Create a spreadsheet.
*/
public Spreadsheet() {
// Create and set up the window.
JFrame mainFrame = new JFrame("Spreadsheet in Java");
mainFrame.setDefaultCloseO
// Create and set up the above panel. This panel contains the
// cell editor, and the recomputation button.
JPanel abovePanel = new JPanel();
abovePanel.setLayout(new BoxLayout(abovePanel, BoxLayout.LINE_AXIS));
editor = new CellEditor();
recomputeButton = new JButton("Recompute");
recomputeButton.addActionL
abovePanel.add(editor);
abovePanel.add(Box.createH
abovePanel.add(recomputeBu
// Create and set up the panel containing the cells. The
// topmost row contains column labels, and the leftmost column
// contain row labels.
JPanel cellsPanel = new JPanel(new GridLayout(ROWS+1, COLUMNS+1));
// Make the first row.
cellsPanel.add(newHeader("
for (int col = 1; col <= COLUMNS; col++)
cellsPanel.add(newHeader(C
// Make the other rows.
for (int row = 1; row <= ROWS; row++) {
cellsPanel.add(newHeader(I
for (int col = 1; col <= COLUMNS; col++)
cellsPanel.add(new Cell(col, row, editor));
}
// Add the panels to the main window.
mainFrame.getContentPane()
mainFrame.getContentPane()
// Display the window.
mainFrame.pack();
mainFrame.setVisible(true)
}
/**
* Create a row or column header.
*/
private JComponent newHeader(String text) {
JLabel header = new JLabel(text, SwingConstants.CENTER);
header.setBorder(cellNorma
return header;
}
/**
* This is called when the user clicks on button "Recompute".
*/
public void actionPerformed(ActionEven
// currently forces the editor to write back its current cell.
editor.validate();
}
/**
* Create the GUI and show it. For thread safety, this method
* should be invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Make sure we have nice window decorations.
JFrame.setDefaultLookAndFe
// Initialise cellNormalBorder and cellSelectedBorder.
Border thinline = BorderFactory.createLineBo
Border thinspace = BorderFactory.createEmptyB
cellNormalBorder = BorderFactory.createCompou
thinspace);
cellSelectedBorder = BorderFactory.createMatteB
Color.black);
// Create an instance of Spreadsheet
Spreadsheet ss = new Spreadsheet();
}
/**
* This is where the application starts.
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread: creating
// and showing this application's GUI.
javax.swing.SwingUtilities
public void run() {
createAndShowGUI();
}
});
}
}
R.K