JProgressBar in JTable overwrites cell bounds

Problem: When the user resizes the table (during a update) so that the entire JProgressBar will no longer fit in the cell, the text of the JProgressBar will overwrite its surrounding controls.
Sample code:
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
public class Main extends JFrame {
public Main() {
super("TableModel JProgressBar Demonstration");
// create our own custom TableModel
DownloadTableModel downloadModel = new DownloadTableModel();
JTable table = new JTable(downloadModel);
// add rows to our TableModel, each row is represented as a Download object
downloadModel.addDownload(new Download("linuxmandrake.zip", 1234567));
downloadModel.addDownload(new Download("flash5.exe", 56450000));
downloadModel.addDownload(new Download("jdk1.2.2-007.zip", 20000000));
// render the columns with class JProgressBar as such
ProgressBarRenderer pbr = new ProgressBarRenderer(0, 100);
pbr.setStringPainted(true);
table.setDefaultRenderer(JProgressBar.class, pbr);
// increase the height of the rows a bit
table.setRowHeight((int) pbr.getPreferredSize().getHeight());
// create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
// add the scroll pane to this window.
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(new JButton("Spacer"), BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
public static void main(String[] args) {
Main main = new Main();
main.pack();
main.setVisible(true);
// a simple object that holds data about a particular download
// it starts a thread and increases the progress of "downloading"
// in a random manner
class Download extends Observable implements Runnable {
private Thread thisThread;
private String filename;
private int filesize;
private float progress;
public Download(String filename, int filesize) {
this.filename = filename;
this.filesize = filesize;
progress = 0.0f;
thisThread = new Thread(this);
thisThread.start();
public String getFilename() { return filename; }
public int getFilesize() { return filesize; }
public float getProgress() { return progress; }
public String toString() {
return "[" + filename + ", " + filesize + ", " + progress + "]"; }
public void run() {
Random r = new Random();
int count = 0;
while (count < filesize) {
int random = Math.abs(r.nextInt() % 100000);
count += random;
if (count > filesize) count = filesize;
progress = ((float) count / filesize) * 100;
// notify table model (and all other observers)
setChanged();
notifyObservers(this);
try { thisThread.sleep(500); } catch(InterruptedException e) { }
class DownloadTableModel extends AbstractTableModel implements Observer {
// holds the strings to be displayed in the column headers of our table
final String[] columnNames = {"Filename", "Filesize", "Progress"};
// holds the data types for all our columns
final Class[] columnClasses = {String.class, Integer.class, JProgressBar.class};
// holds our data
final Vector data = new Vector();
// adds a row
public void addDownload(Download d) {
data.addElement(d);
// the table model is interested in changes of the rows
d.addObserver(this);
fireTableRowsInserted(data.size()-1, data.size()-1);
// is called by a download object when its state changes
public void update(Observable observable, Object o) {
int index = data.indexOf(o);
if (index != -1)
fireTableRowsUpdated(index, index);
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.size();
public String getColumnName(int col) {
return columnNames[col];
public Class getColumnClass(int c) {
return columnClasses[c];
public Object getValueAt(int row, int col) {
Download download = (Download) data.elementAt(row);
if (col == 0) return download.getFilename();
else if (col == 1) return new Integer(download.getFilesize());
else if (col == 2) return new Float(download.getProgress());
else return null;
public boolean isCellEditable(int row, int col) {
return false;
// a table cell renderer that displays a JProgressBar
class ProgressBarRenderer extends JProgressBar implements TableCellRenderer {
public ProgressBarRenderer() {
super();
public ProgressBarRenderer(BoundedRangeModel newModel) {
super(newModel);
public ProgressBarRenderer(int orient) {
super(orient);
public ProgressBarRenderer(int min, int max) {
super(min, max);
public ProgressBarRenderer(int orient, int min, int max) {
super(orient, min, max);
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
setValue((int) ((Float) value).floatValue());
return this;
}

I do not have an answer for you.
However, I did skim through a solution to your problem. Since it didn't solve my problem at the time, I didn't try out the code.
In the book "Core Web Programming", Second Edition, Marty Hall and Larry Brown, Sun Microsystems Press, they do discuss making a progress bar synchronize with a file download and why you have to make it multi-threaded.
If you can head over to your bookstore, it's Chapter 15.6 and consists of about two and a half pages. Even better, the example's source code is available for free on their web site at:
http://www.corewebprogramming.com
Click on the hypertext link to Chapter 15, then scroll down and grab FileTransfer.java near the bottom of the page.
Hope this at least points you in the right direction, but I admit I wouldn't even allow the user to resize the table containing the progress bar to begin with. If I absolutely had to, I'd force the progress bar thread to reset itself each time it received a window-resizing event.

Similar Messages

  • Need help serializing an AbstractTableModel for a JTable with cell editing.

    Fun times are ahead. Here we go!
    I have a JTable that contains data I'd like to serialize out to a file to be restored and viewed later.
    So I tried saving the AbstractTableModel subclass out to a file. Whenever I do this, I get the following error message:
    java.io.NotSerializableException: javax.swing.JTable$CellEditorRemover
    Now I know for fact that serializing an AbstractTableModel that was installed in a JTable without cell editing works just fine (my old code did exactly that). As a result, I think that the code that handles events in the AbstractTableModel contains references back out to the JTable, which causes the JTable to be saved no matter what (even though I'm just interested in saving the TableModel only). It causes a bigger file than normal, but file size is not an issue. The only issue I have is that CellEditorRemover (an undocumented inner class of JTable), which is automatically installed for JTables with editable cells, is not serializable.
    This leads to the following questions:
    1. Is there a way to avoid serialization/deserialization of the CellEditorRemover inner class of JTable?
    2. Is there a way to save an AbstractTableModel without saving all of the event listeners associated with it?
    I think an answer to either of these questions would go a long way towards solving my problem. Otherwise, I'll resign myself to weeping silently in the corner of my office.
    Thanks!

    I would suggest that if you can you only save the
    data... but i would do this by using the
    externalizable interface.
    What you will need to do is have the
    writeExternal(ObjectOutputStream out) and
    readExternal(ObjectOutputStream out) methods in your
    class. These will be responsiable for saving the
    data.
    Here's an example of what you can do in these
    methods... this is just a little tidbit from a program
    i've written.public void writeExternal(ObjectOutput out) throws
    IOException {
              out.writeInt(size);
              out.writeObject(drawName);
              out.writeInt(playersLength);
    for(int i = 0; i < playersLength; i++)
    ) out.writeObject(players);
              out.writeInt(seedsLength);
    for(int i = 0; i < seedsLength; i++)
    ) out.writeObject(seeds[i]);
              out.writeInt(drawLength);
    for(int i = 0; i < drawLength; i++)
    ) out.writeObject(draw[i]);
    public void readExternal(ObjectInput in) throws
    IOException, ClassNotFoundException {
              size = in.readInt();
              drawName = (String)in.readObject();
              playersLength = in.readInt();
    for(int i = 0; i < playersLength; i++) players[i] =
    = (String)in.readObject();
              seedsLength = in.readInt();
    for(int i = 0; i < seedsLength; i++) seeds[i] =
    = (String)in.readObject();
              drawLength = in.readInt();
    for(int i = 0; i < drawLength; i++) draw[i] =
    = (String)in.readObject();
    You can now use your class as you would a Serializable
    class, but it will only save the data
    Hope this helped
    webaf409java
    I forgot to add some critical information in my original post. My apologies. :(
    I've thought about using Externalizable, but am hesitant to use it because the application would no longer be able to read in files using the old save format (ie, AbstractTableModels for JTables without CellEditorRemovers ).  I want to preserve the ability to read the old saved AbstractTableModel formats if possible. 
    Do you know of a way to revert to the default deserialization mechanism from readExternal?  This way, during deserialization, I could do a quick test on the object being read and have the ability to default to the regular deserialization mechanism if the object is of the old type or continue with the new Externalizable stuff if the object is one of the new type.  Maintaining file compatibility is key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • JTable's Cell navigation with TAB

    Dear ALL
    I have face one problem in JTable's cell navigation with TAB. The problem as describe bellow.
    I have two columns NAME and ADDRESS. Set focus on ADDRESS column's first cell. now if i am press tab key then focus controll comes on second cell which is the ADDRESS column. At the end of row controll comes on first row second column that means focus on ADDRESS column's first cell.
    Please give me some hints.
    Thanks in advance.
    Amit

    Your description doesn't make any sense (to me at least) so I don't know what your problem is or what you are asking to be changed.
    The normal tab order is Left to Right, Top to Bottom. So if the focus is at the top/left normal tabbing would be:
    Row 0, Column 0 (name 0)
    Row 0 Column 1 (address 0)
    Row 1, Column0 (name 1)
    Row 1, Column 1 (address 1)
    Row 2, Column 0 (name 2)
    Row 2, Column 1 (address 2)
    Your question seems to imply that your tab from address to addreass, which doesn't make sense.
    "Set focus on ADDRESS column's first cell. now if i am press tab key then focus controll comes on second cell which is the ADDRESS "

  • JTable - active cell not highlited when editable

    Hello,
    I'm using JDK 1.4.2_05, and I'm seeing some behavior that seems a bit strange.
    In my JTables, some cells are editable, and others are not. When the user moves the active cell around (with the arrow keys, or TAB and RETURN) the non-editable cells show up with a nice blue color. If a cell is editable, it doesn't change at all, so the user has no idea where the "cursor" (meaning the active cell) is.
    These cells don't have any special renderer or anything. My JTable has these set:
    setRowSelectionAllowed(false);
    setColumnSelectionAllowed(false);
    setCellSelectionEnabled(true);Thanks for any advice!
    --- Eric

    Okay, yeah, I overrode the default renderer, and had it check whether the cell was selected or not, setting the background color appropriately. Duh. --- Eric

  • Jtable on cell changed event

    How can i treat an Jtable on cell changed event, not on value changed

    Do you mean cell selection changed? One way is to add a ListSelectionListener to both the table's and the table's ColumnModel's ListSelectionModels. Something likeListSelectionListener lsl = new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent e) {
          System.out.println(e.getSource());
          ListSelectionModel lsm = (ListSelectionModel) e.getSource();
          if (!lsm.getValueIsAdjusting()) {
             System.out.println("Selection changed");
    table.getSelectionModel().addListSelectionListener(lsl);
    table.getColumnModel().getSelectionModel().addListSelectionListener(lsl);Note that simultaneous change of both row and column will generate two valueChanged events.
    If that's not what you wanted to know, ask a better question.
    [http://catb.org/~esr/faqs/smart-questions.html]
    db

  • HELP!!!Embedding a JTable on a ScrollPane into a JTable's cell

    I have a single column DND JTable on a DND JScrollPane that I would like to put into another's JTable's cell. I've tried creating a CellRenderer that extends the DNDJScrollPane and returns this but this doesn't work. I do have code I could post if anyone is interested in helping out.

    First copy this and compile and run and c.. then look at the code
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    public class JTableExample extends JFrame
    JTableRenderer renderer;
    MyTableModel m1, m2;
    public JTableExample()
    super();
    m1 = new MyTableModel();
    m2 = new MyTableModel();
    DefaultTableModel dtm = new DefaultTableModel()
    // make first cell uneditable
    public boolean isCellEditable(int row, int column)
    return !(column == 0);
    dtm.setDataVector(new Object[][]{{ "JTable1",  m1},
    { "JTable2",  m2}},
    new Object[]{ "Column1","Column2"});
    JTable table = new JTable(dtm);
    renderer = new JTableRenderer();
    table.getColumn("Column2").setCellRenderer(renderer);
    table.getColumn("Column2").setCellEditor(new JTableEditor());
    table.setRowHeight(80);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
    setSize( 400, 250 );
    setVisible(true);
    public static void main(String[] args) {
    JTableExample frame = new JTableExample();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    * JTable Editor
    class JTableEditor extends DefaultCellEditor
    public JTableEditor()
    super(new JCheckBox());
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column)
    return renderer;
    public Object getCellEditorValue()
    return (MyTableModel)((JTableRenderer)renderer).jtable.getModel();
    * JTable Renederer
    class JTableRenderer extends JScrollPane implements TableCellRenderer
    JTable jtable;
    public JTableRenderer()
    jtable = new JTable();
    getViewport().add(jtable);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column)
    if (isSelected)
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    jtable.setForeground(table.getSelectionForeground());
    jtable.setBackground(table.getSelectionBackground());
    else
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    jtable.setForeground(table.getForeground());
    jtable.setBackground(table.getBackground());
    jtable.setModel((AbstractTableModel)value);
    return this;
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", "Andrews",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public final Object[] longValues = {"Angela", "Andrews",
    "Teaching high school",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    public boolean isCellEditable(int row, int col) {
    if (col < 2) {
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    private void printDebugData() {
    cheers
    good luck

  • Appearing the added JTable's cell JComboBox at running the Class

    During the time of employing the JTable,arising the problem of how to appear the added JTable's cell JComboBox at loading the class..Can you aid me plz to resolve this bug...If u know answer,plz forward the resolution..

    Sorry, I don't understand the question so I'll just point you to the Swing tutorial on "How to Use Tables" which has a working example of using a combo box in a table:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

  • Indeterminate JProgressBar inside JTable cell

    I am able to put a JProgressBar inside a JTable cell, via a custom renderer to do so, however, I am unable to make the progress bar show the indeterminate animation. Any ideas? I calledbar.setIndeterminate( true ); and it doesn't seem to want to show. Is the JTable preventing it?
    (should I include more of my code?)

    Your JProgressBar is used to render the table cell only when that cell of the JTable needs to be rendered and the JProgressBar has no say in this.
    I don't know why you would want to do this but to do this I would set up timer that fired a tree model event to say that the content of the cell had changed. This would trigger the cell to be re-painted. I think, but I can't be sure, that you will not be able to use
    bar.setIndeterminate( true );
    You may have to craft your own progress bar to make this easy.

  • JProgressbar and JTable

    Hi,
    how can I add a JProgressBar in a JTable cell?
    Thanks to all!

    Create your own TableCellRenderer!
    as in:
    http://www.esus.com/docs/GetQuestionPage.jsp?uid=1216

  • JTable display cell previous/last selected/edited/clicked value/JComponent

    I have a problem with the minesweeper I made,
    The game board is a JTable containing custom gadgets in the cells,
    The first game goes without problem, but I press the JButton starting a new game,
    I randomly refill the JTable with new custom gadgets,
    My problem is that the last cell I clicked in the JTable is still in the clicked state with the previous value and I cannot click or see the new custom gadget that ought to be there ...
    The custom gadgets extends JLabel and use custom AbstractCellEditor and custom TableCellRenderer, but I think it is not related to my custom gadgets,
    I work on OSX,
    Any hint to my problem's origin?
    Any solutions?

    My code included not related classes I eliminated to use only standard java classes,
    here is is the minimal code for my mine sweeper reproducing the problem on the third launch
    any hint? :
    import java.awt.Container;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseEvent;
    import java.util.Random;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    public class MyMineSweeper
       private class JTableCellRenderer implements javax.swing.table.TableCellRenderer
          private javax.swing.table.TableCellRenderer defaultRenderer;
          public JTableCellRenderer(javax.swing.table.TableCellRenderer aRenderer)
             defaultRenderer = aRenderer;
          public java.awt.Component getTableCellRendererComponent(javax.swing.JTable aTable, Object anElement, boolean isSelected, boolean hasFocus, int aRow, int aColumn)
             if(anElement instanceof javax.swing.JComponent)
                return (javax.swing.JComponent)anElement;
             return defaultRenderer.getTableCellRendererComponent(aTable, anElement, isSelected, hasFocus, aRow, aColumn);
       private class JTableCellEditor extends javax.swing.AbstractCellEditor implements javax.swing.table.TableCellEditor
          private javax.swing.JComponent component;
          private int theClickCountToStart = 0;
          public java.awt.Component getTableCellEditorComponent(javax.swing.JTable aTable, Object anElement, boolean isSelected, int aRow, int aColumn)
             component = (javax.swing.JComponent) anElement;
             return component;
          public Object getCellEditorValue()
             return component;
          public boolean isCellEditable(java.util.EventObject anEvent)
             if(anEvent instanceof java.awt.event.MouseEvent)
                return ((java.awt.event.MouseEvent)anEvent).getClickCount() >= theClickCountToStart;
             return true;
          public int getClickCountToStart()
             return theClickCountToStart;
          public void setClickCountToStart(int aClickCountToStart)
             theClickCountToStart = aClickCountToStart;
       private class Tile extends javax.swing.JLabel
          public class JTileMouseListener implements java.awt.event.MouseListener
             public void mouseClicked(MouseEvent e)
                if(isRevealed()==false)
                   reveal();
             public void mousePressed(MouseEvent e)
             public void mouseReleased(MouseEvent e)
             public void mouseEntered(MouseEvent e)
             public void mouseExited(MouseEvent e)
            public void reveal(int aY, int anX)
               Tile tile = ((Tile)theMapModel.getValueAt(aY, anX));
               if(tile.isRevealed()==false)
                  tile.reveal();
            public void changed()
               if(theNeighbourCount==0)
                  if(theX>0)
                     if(theY>0)
                        reveal(theY-1, theX-1);
                     reveal(theY, theX-1);
                     if(theY<theMapModel.getRowCount()-1)
                        reveal(theY+1, theX-1);
                  if(theY>0)
                     reveal(theY-1, theX);
                  if(theY<theMapModel.getRowCount()-1)
                     reveal(theY+1, theX);
                  if(theX<theMapModel.getColumnCount()-1)
                     if(theY>0)
                        reveal(theY-1, theX+1);
                     reveal(theY, theX+1);
                     if(theY<theMapModel.getRowCount()-1)
                         reveal(theY+1, theX+1);
                   setBackground(java.awt.Color.WHITE);
                else if(theNeighbourCount==9)
                   setText("*");
                   setBackground(java.awt.Color.RED);
                   System.out.println("no!");
                   theMap.setEnabled(false);
                else
                   setText(String.valueOf(theNeighbourCount));
                   setBackground(java.awt.Color.WHITE);
                setBorder(javax.swing.BorderFactory.createEmptyBorder());
                if(isFinished()==true)
                   System.out.println("victory!");
                   theMap.setEnabled(false);
                theMapModel.fireTableCellUpdated(theY,theX);
          private DefaultTableModel theMapModel;
          private int theX;
          private int theY;
          private short theNeighbourCount;
          protected boolean revealed = false;
          public Tile(int aYIndex, int anXIndex, short aNeighbourCount)
             theMapModel = (DefaultTableModel)theMap.getModel();
             theX = anXIndex;
             theY = aYIndex;
             theNeighbourCount = aNeighbourCount;
             addMouseListener(new JTileMouseListener());
             setOpaque(true);
             setHorizontalAlignment(CENTER);
             setBackground(java.awt.Color.LIGHT_GRAY);
             setBorder(javax.swing.BorderFactory.createRaisedBevelBorder());
             setSize(getHeight(), getHeight());
          public void reveal()
             revealed = true;
             theRevealedTileCount +=1;
             changed();
          public boolean isRevealed()
             return revealed;
       private JFrame theFrame;
       private JTable theMap;
       private int theMapSize = 10;
       private int theTrapCount = 5;
       private int theRevealedTileCount = 0;
       private void startGame()
          Point[] traps = new Point[theTrapCount];
          Random generator = new Random();
          for(int trapIndex = 0; trapIndex<theTrapCount; trapIndex+=1)
             Point newPoint = null;
             boolean alreadyTrapped = true;
             while(alreadyTrapped==true)
                newPoint = new Point(generator.nextInt(theMapSize-1), generator.nextInt(theMapSize-1));
                alreadyTrapped = false;
                for(int existingTrapIndex= 0; existingTrapIndex<trapIndex;existingTrapIndex++)
                   if(newPoint.equals(traps[existingTrapIndex])) alreadyTrapped = true;
             traps[trapIndex] = newPoint;
          TableModel mapModel = theMap.getModel();
          for(int yIndex = 0; yIndex<theMapSize; yIndex+=1)
             for(int xIndex = 0; xIndex<theMapSize; xIndex+=1)
                short neighbours = 0;
                int x = 0;
                int y = 0;
                for(int trapIndex = 0; trapIndex<theTrapCount; trapIndex+=1)
                   x = traps[trapIndex].x - xIndex;
                   y = traps[trapIndex].y - yIndex;
                   if(x==0 && y==0)
                      trapIndex = theTrapCount;
                   else if((x==1 || x==-1) && (y==1 || y==-1))
                      neighbours += 1;
                   else if((x==0) && (y==1 || y==-1))
                      neighbours += 1;
                   else if((x==1 || x==-1) && (y==0))
                      neighbours += 1;
                if(x==0 && y==0)
                   mapModel.setValueAt(new Tile(yIndex, xIndex, (short) 9), yIndex, xIndex);
                else
                   mapModel.setValueAt(new Tile(yIndex, xIndex, neighbours), yIndex, xIndex);
          theRevealedTileCount  = 0;
          theMap.setEnabled(true);
       private boolean isFinished()
          return ((theMapSize*theMapSize)-theRevealedTileCount)==theTrapCount;
       public MyMineSweeper()
          theFrame = new javax.swing.JFrame("mine sweeper");
          JPanel cp = new JPanel();
          theMap = new JTable(new DefaultTableModel(10,10)
             public Class getColumnClass(int column)
                return getValueAt(0, column).getClass();
          theMap.setDefaultRenderer(JComponent.class, new JTableCellRenderer(theMap.getDefaultRenderer(JComponent.class)));
          JTableCellEditor editor = new JTableCellEditor();
          theMap.setDefaultEditor(JComponent.class, editor);
          editor.setClickCountToStart(0);
          theMap.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
          startGame();
          cp.add(theMap);
          Action newGameAction = new AbstractAction("new game")
             public void actionPerformed(ActionEvent e)
                startGame();
          JButton newGameTrigger = new JButton(newGameAction);
          cp.add(newGameTrigger);
          theFrame.getContentPane().add(cp);
          theFrame.pack();
          theFrame.show();
       public JFrame getFrame()
          return theFrame;
      }

  • Need urgent help on JTable and cell

    Hi,
    I've got problem in validating the cell in Table.
    If user enters data in a cell i would like to validate the data in cell and if it is wrong i would like to give a dialog and keep the cursor in the same cell. So that i can restrict the user to enter valid data.
    How do i capture the event when he is leaving the cell using tab/mouse press?
    Suppose if the cursor is in once cell from a row (the rew contains different cell renderers,) then he wish to delete the row then i would like to save the data in the model and delete it.
    I'm getting class cast exception as i have got differnt components inside row.
    Thanks

    Hi,
    Try out the following code.
    import javax.swing.*;
    import javax.swing.table.*;
    class EditingTest
         EditingTest()
              JFrame frame = new JFrame("Editing Test");
              frame.setBounds(10,10,750,550);
              JTable table = new JTable(5,5);
              TableCellEditor tableCellEditor = new CustomEditor(new JTextField());
              for(int i = 4; i > -1; --i)
                   table.getColumnModel().getColumn(i).setCellEditor(tableCellEditor);
              JScrollPane scrollpane = new JScrollPane(table);
              frame.getContentPane().add(scrollpane);
              frame.setVisible(true);
         public static void main(String [] args)
              EditingTest appln = new EditingTest();
    class CustomEditor extends DefaultCellEditor
         CustomEditor(JTextField editorComponent)
              super(editorComponent);
         public boolean stopCellEditing()
              try
                   String editingValue = (String)getCellEditorValue();
                   if(editingValue.length() != 5)
                        JOptionPane.showMessageDialog(null,"Please enter string with 5 letters.", "Alert!",JOptionPane.ERROR_MESSAGE);
                        return false;
              catch(ClassCastException exception)
                   return false;
              return super.stopCellEditing();
    }

  • JTable: scrollabel Cell

    Hi,
    I've already come up with this, but up to now I haven't received any answer.
    What do I have to do, to can I scroll a non editable cell within a JTable?
    Besides the CellRenderer, I have to implement the CellEditor. But I something is wrong, it just won't work.
    code snippet from celleditor:
    public class ScrollPaneCellEditor extends JScrollPane implements TableCellEditor, Serializable{
    JEditorPane pane;
    JScrollPane scrollpane;
    StringBuffer sb;
    /** Creates a new instance of IconTableCellRenderer */
    public ScrollPaneCellEditor() {      
    pane = new JEditorPane();
    sb = new StringBuffer(); }
    public boolean isCellEditable(java.util.EventObject anEvent) {
    return false;
    public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) {
    pane.setText(value.toString());
    super.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    JViewport vp = new JViewport();
    vp.setScrollMode(JViewport.BLIT_SCROLL_MODE);
    vp.setView(pane);
    super.setWheelScrollingEnabled(true);
    if (isSelected){           
    scrollpane.setViewport(vp);
    if(hasFocus()){
    scrollpane.setViewportView(vp);
    super.add(vp);
    return this;
    Best regards,
    Andi

    Hi bukibu79 ,
    In JTable cells are not a component
    it is a painting using graphics, when you edit a cell this time the editable cell only a component so you cann't edit two cells at a time.
    Another one is suppose you assume that cell are compoents then how can add a single component into two different cells. What actualy do on JTable is , JTable get the component form the renderer and paint this renderer component into the cell's rectangle area and move this component to some non visible area.
    If your table cell is non editable then the editor doesn't work because there are no need to get editor for JTable.

  • Problems with JTable custom cell renderers

    Hi All,
    I'm having a bit of a problem writing a custom renderer for a JTable.
    What seems to be happening is that the changes I apply in the renderer to the component are applied to ALL cells.
    All I want to do is have a different background color for certain cells....
    Ive derived from DefaultTableCellRenderer, so Im using its getTableCellRendererComponent to do most of the work.
    So, Ive got something like this:
    private class DirtyCacheRenderer extends DefaultTableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
                              boolean isSelected, boolean hasFocus, int row, int column)
          // Modifies 'this'
          super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
          // If the row/column is 'dirty' (I.e - if I want 2 color it diferently)
          if(((EditableTableModel)table.getModel()).isDirty(row,column))
            // The column is dirty. Set the color accordingly:
            super.setBackground(DIRTY_COLOR);
          return this;
      }The effect is that as soon as ONE cell gets its color set above, all of the cells do!
    Please help, its driving me mad!!!
    D

    I tried this and it worked. Tell me if it is OK for you.
    import javax.swing.table.TableCellRenderer;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.JLabel;
    public class testRenderer implements TableCellRenderer {
    JLabel cell = new JLabel();
    Color dirty = new Color(100,100,100);
    Color clear = new Color(0,0,0);
    public testRenderer() {
    cell.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table,Object value,
    boolean isSelected,boolean hasFocus, int row, int column) {
    cell.setText(value.toString());
    // The column is dirty. Set the color
    if (row == column)     {
    cell.setBackground(dirty);
    } else {
    cell.setBackground(table.getBackground());
    return cell;
    }

  • JTable custom cell objects

    howdy howdy howdy.
    is there a way of specifying cells in a jtable to have a different object in each cell.
    e.g. from the jtable tutorial
    TableColumn sportColumn = table.getColumnModel().getColumn(2);
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Chasing toddlers");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Teaching high school");
    comboBox.addItem("None");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));so that will give me a column with a combobox with those items in to choose from....
    but lets say i want a table with say 5 rows, but in the top cell of column 2 (0,1) i want a combobox with say (item1, item2, item3)
    then in the next cell (1,1) i want another combo box but with different item data in e.g. (itema, itemb, itemc)
    and even lets push it and say the next cell (2,1) i have a checkbox in.
    this is because i have a table with 2 columns
    property, value
    and the property is different and can have different value types in
    e.g.
    property | value
    font | arial, verdana, times
    color | color chooser dialog
    ultimately the second column is going to store a simple string, so perhaps rather than have a different item in each box i just have a common object that has a text field and a button that pops up an chooser or something.
    what id really like though is a editable combo box with different fields in each of my column cells.
    can anyone either help or point me in the direction of help?
    thanks

    is there a way of specifying cells in a jtable tohave a different object in each cell.
    Yes its very easy to have a different editor for each
    cell.Thanks ill look into that :)
    >
    can anyone either help or point me in the directionof help?
    You've been pointed to the Swing forum many times.I know :( but the swing forum scares me

  • JTable custom cell editor focus problem

    Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
    When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
    When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
    I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
    I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

    Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
    When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
    When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
    I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
    I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

Maybe you are looking for

  • Mail.app is COPYING instead of MOVING mail to folders (using IMAP)

    Hi there, I hope I can keep this simple, I'll go by the steps leading to my propblem: 1. I've been using POP3 mail for a long time, mainly with Outlook on PC's and now that I have made the godly switch to Apple I've been using Mail.app for a couple m

  • Trying to send photo via share/send button in iphoto

    Having problems, possible due to being a newbie, with sending a photo via the share/send button in iphoto. A message comes up "The email server didn't recognize your username/password combination". I have checked all preferences in mail and all seem

  • How do I cancel NHL gamecenter ?

    I just bought the gamecenter app just to find out that all my games are blocked out now I can't cancel it !!

  • Poor pax implementation help.

    I have a dead system due to 10.4.6 failing mysteriously. I'd like to get my system back, and as apple don't want to help users, maybe someone here can answer a few questions, which might help. Before going to work, I set SU to downaload and install t

  • Error Code 6:

    Hello people, I've got a problem with my ipad2 and as I couldn't find out how to contact Swiss or any other support via E-Mail (as it's 2 am here..), I thought, maybe someone on here is able to help me.. Here's my problem: This afternoon I was trying