Custom JSpinner Model / Editor

Hello,
This question may have been answered in the past but I could not find anything. I am trying to use a JSpinner for cycling through pages of information. I would like the display to show current page of total number of pages, i.e. 1 of 10. I would also like the user to be able to enter a number and have the spinner display that number in the same format. I am not quite sure if I need to create a custom model and editor or expand the SpinnerNumberModel. Any guidance is much appreciated.

this might be one way for the '1 of 10', for entering a number, just add a keyListener,
and modify the methods accordingly
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Testing
  JSpinner spinner;
  JTextField tf;
  final int TOTAL_PAGES = 10;
  int currentPage;
  public void buildGUI()
    tf = new JTextField(10);
    tf.setHorizontalAlignment(JTextField.RIGHT);
    tf.setEditable(false);
    tf.setBackground(Color.WHITE);
    spinner = new JSpinner();
    spinner.setUI(new MyUI());
    spinner.setEditor(tf);
    changeValue(1);
    JFrame f = new JFrame();
    f.getContentPane().add(spinner);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  public void changeValue(int amount)
    try
      int newPageNumber = currentPage+amount;
      if(newPageNumber < 1 || newPageNumber > TOTAL_PAGES)
        java.awt.Toolkit.getDefaultToolkit().beep();
        return;
      tf.setText(newPageNumber+" of "+TOTAL_PAGES);
      currentPage = newPageNumber;
    catch(Exception e){e.printStackTrace();}
  class MyUI extends javax.swing.plaf.basic.BasicSpinnerUI
    protected Component createNextButton()
      JButton btnNext = (JButton)super.createNextButton();
      btnNext.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
          changeValue(1);}});
      return btnNext;
    protected Component createPreviousButton()
      JButton btnPrevious = (JButton)super.createPreviousButton();
      btnPrevious.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
          changeValue(-1);}});
      return btnPrevious;
  public static void main(String[] args)
    SwingUtilities.invokeLater(new Runnable(){
      public void run(){
        new Testing().buildGUI();
}

Similar Messages

  • Small issue with custom table cell editor and unwanted table row selection

    I'm using a custom table cell editor to display a JTree. Thing i notice is that when i select a value in the tree pop-up, the pop-up closes (as it should) but then every table row, from the editing row to the row behind the pop-up when i selected the value becomes highlighted. I'm thinking this is a focus issue, but it thought i took care of that. To clairfy, look at this: Before . Notice how the "Straightening" tree item is roughly above the "Stock Thickness" table row? When i select Straightening, this is what happens to my table: After .
    My TreeComboBox component:
    public class TreeComboBox extends JPanel implements MouseListener {
        private JTextField itemField;
        private TreeModel treeModel;
        private ArrayList<ActionListener> actionListeners = new ArrayList<ActionListener>();
        private Object selectedItem;
         * Creates a new <code>TreeComboBox</code> instance.
         * @param treeModel the tree model to be used in the drop-down selector.
        public TreeComboBox(TreeModel treeModel) {
            this(treeModel, null);
         * Creates a new <code>TreeComboBox</code> instance.
         * @param treeModel the tree model to be used in the drop-down selector.
         * @param selectedItem tree will expand and highlight this item.
        public TreeComboBox(TreeModel treeModel, Object selectedItem) {
            this.treeModel = treeModel;
            this.selectedItem = selectedItem;
            initComponents();
         * Returns the current drop-down tree model.
         * @return the current <code>TreeModel</code> instance.
        public TreeModel getTreeModel() {
            return treeModel;
         * Sets the tree model.
         * @param treeModel a <code>TreeModel</code> instance.
        public void setTreeModel(TreeModel treeModel) {
            this.treeModel = treeModel;
         * Returns the selected item from the drop-down selector.
         * @return the selected tree object.
        public Object getSelectedItem() {
            return selectedItem;
         * Sets the selected item in the drop-down selector.
         * @param selectedItem tree will expand and highlight this item.
        public void setSelectedItem(Object selectedItem) {
            this.selectedItem = selectedItem;
            String text = selectedItem != null ? selectedItem.toString() : "";
            itemField.setText(text);
            setToolTipText(text);
         * Overridden to enable/disable all child components.
         * @param enabled flat to enable or disable this component.
        public void setEnabled(boolean enabled) {
            itemField.setEnabled(enabled);
            super.setEnabled(enabled);
        public void addActionListener(ActionListener listener) {
            actionListeners.add(listener);
        public void removeActionListener(ActionListener listener) {
            actionListeners.remove(listener);
        // MouseListener implementation
        public void mouseClicked(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
            showPopup();
        private void initComponents() {
            setLayout(new GridBagLayout());
            itemField = new JTextField();
            itemField.setEditable(false);
            itemField.setText(selectedItem != null ? selectedItem.toString() : "");
            itemField.addMouseListener(this);
            add(itemField, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        private void showPopup() {
            final TreePopup popup = new TreePopup();
            final TreeComboBox tcb = this;
            final int x = itemField.getX();
            final int y = itemField.getY() + itemField.getHeight();
            int width = itemField.getWidth() + popupButton.getWidth();
            Dimension prefSize = popup.getPreferredSize();
            prefSize.width = width;
            popup.setPreferredSize(prefSize);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    popup.show(tcb, x, y);
                    popup.requestFocusInWindow();
        private void fireActionPerformed() {
            ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "TreeComboBoxSelection");
            for (ActionListener listener : actionListeners) {
                listener.actionPerformed(e);
        private class TreePopup extends JPopupMenu {
            private JTree tree;
            private JScrollPane scrollPane;
            public TreePopup() {
                initComponents();
                initData();
            private void initData() {
                if (treeModel != null) {
                    tree.setModel(treeModel);
            private void initComponents() {
                setFocusable(true);
                setFocusCycleRoot(true);
                tree = new JTree();
                tree.setRootVisible(false);
                tree.setShowsRootHandles(true);
                tree.setFocusable(true);
                tree.setFocusCycleRoot(true);
                tree.addTreeSelectionListener(new TreeSelectionListener() {
                    public void valueChanged(TreeSelectionEvent e) {
                        tree_valueChanged(e);
                scrollPane = new JScrollPane(tree);
                add(scrollPane);
            private void tree_valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                setSelectedItem(node.getUserObject());
                fireActionPerformed();
                this.setVisible(false);
    }My TreeComboBoxTableCellEditor:
    public class TreeComboBoxTableCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
        protected TreeComboBox treeComboBox;
        protected ArrayList<CellEditorListener> cellEditorListeners = new ArrayList<CellEditorListener>();
        public TreeComboBoxTableCellEditor(TreeComboBox treeComboBox) {
            this.treeComboBox = treeComboBox;
            treeComboBox.addActionListener(this);
        public Object getCellEditorValue() {
            return treeComboBox.getSelectedItem();
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            treeComboBox.setSelectedItem(value);
            return treeComboBox;
        public void actionPerformed(ActionEvent e) {
            stopCellEditing();
    }Any thoughts?
    Edited by: MiseryMachine on Apr 3, 2008 1:21 PM
    Edited by: MiseryMachine on Apr 3, 2008 1:27 PM

    As I said, you have to have empty context elements before additional rows will be open for input.
    For instance if you want to start with 5 rows available for input do the following to your internal table that you will bind:
    data itab type standard table of sflight.
    do 5 times.
      append initial line to itab.
    enddo.
    context_node->bind_table( itab ).
    The other option if you need n number of rows is to add a button to the table toolbar for adding more rows. When this button is pressed, you add a new context element to the node - thereby creating a new empty row in the table.

  • Problem of custom table model

    Hi,
    i m leaning JTable recently, following is an experimental code which i wrote, it has a custom table model and custom tablecellrenderer, the custom tablecellrender determine the column of # of Years greater or equal than 5 should display color green, less than 5 should display color red, it works well, however, the custom table model should be smart enough to know that the # of Years column contains numbers (which should generally be right aligned and have a particular format), it also should know that the Vegetarian column contains boolean values, which can be represented by check boxes, but it didn't, i don't know why, i have implement a getColumnClass method,
    but it seems not work, have i make any mistakes? Any idea? Thanks
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.UIManager;
    import java.awt.Color;
    import java.util.Vector;
    public class CellRenderTestVector extends JFrame {
         protected JTable table;
         protected int width = 100;
         protected MyCustomTableModel model;
         public CellRenderTestVector() {
              JPanel pan0 = new JPanel(new BorderLayout());
              Container contentPane = getContentPane();
              pan0.setPreferredSize(new Dimension(500,200));
              model = new MyCustomTableModel();
              table = new JTable();
              table.setAutoCreateColumnsFromModel(false);
              table.setModel(model);
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            TableColumn column = null;
              for (int i = 0; i < model.getColumnCount(); i++) {
                   DefaultTableCellRenderer renderer = new
                     ColoredTableCellRenderer();
                   column = new TableColumn(i,
                              width, renderer, null);
                              table.addColumn(column);
              TableColumn t_column = table.getColumnModel().getColumn(2);
              System.out.println(table.getColumnModel());
              JScrollPane scrollPane = new JScrollPane(table);
              pan0.add(scrollPane, BorderLayout.CENTER);
              contentPane.add(pan0);
                public class ColoredTableCellRenderer extends DefaultTableCellRenderer {
              public void setValue(Object value) {
                   Color  m_color;
                   Color GREEN = new Color(0, 128, 0);
                   Color RED = Color.red;
                   if (value instanceof Integer) {
                        Integer m_data = (Integer)value;
                        m_color = m_data.intValue() >= 5 ? GREEN : RED;
                                           setForeground(m_color);
                               setText(m_data.toString());
                   else {
                        super.setValue(value);
         public class Columndata {
              protected String m_title;
              public Columndata(String title) {
                   m_title = title;
         public class Rowdata {
              protected String fname;
              protected String lname;
              protected String sport_type;
              protected Integer no_year;
              protected Boolean vegetarian;
              public Rowdata(String fn, String ln,
                        String sp, int ny, boolean vg) {
                   fname = fn;
                   lname = ln;
                   sport_type = sp;
                   no_year = new Integer(ny);
                   vegetarian = new Boolean(vg);
         public class MyCustomTableModel extends AbstractTableModel {
              protected final Columndata m_column[] =
                        {new Columndata("First Name"),
                         new Columndata("Last Name"),
                         new Columndata("Sport"),
                         new Columndata("# of Years"),
                         new Columndata("Vegetarian")
              protected Vector m_vector;
              public MyCustomTableModel() {
                   m_vector = new Vector();
                   setDefaultData();
              public void setDefaultData() {
                   m_vector.removeAllElements();
                   m_vector.addElement(new Rowdata("Mary", "Campione",
                                                           "Snowboarding", 5, false));
                   m_vector.addElement(new Rowdata("Alison", "Huml",
                                                           "Rowing",3,true));
                   m_vector.addElement(new Rowdata("Kathy", "Walrath",
                                                           "Knitting",2, false));
                   m_vector.addElement(new Rowdata("Sharon", "Zakhour",
                                                           "Speed reading",20,true));
                   m_vector.addElement(new Rowdata("Philip", "Milne",
                                                           "Pool",10,false));
              public int getColumnCount() {
                   return m_column.length;
              public int getRowCount() {
                   return m_vector==null ? 0 : m_vector.size();
              public String getColumnName(int col) {
                   return m_column[col].m_title;
              public Object getValueAt(int nRow, int nCol) {
                   if (nRow < 0 || nRow>=getRowCount()) return "";
                   Rowdata row = (Rowdata)m_vector.elementAt(nRow);
                   switch (nCol) {
                   case 0: return row.fname;
                   case 1: return row.lname;
                   case 2: return row.sport_type;
                   case 3: return row.no_year;
                   case 4: return row.vegetarian;
                   return "";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
         public static void createAndShowGUI() {
              try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch (Exception evt) {}
                   JFrame f = new CellRenderTestVector();
                   f.setTitle("TableTest");
                   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   f.pack();
                 f.setVisible(true);
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    You need to write your custom TableCellRenderes/Editors for each type. And don't forget to register your custom renderes via myTable.setDefaultRendere().

  • JTree selection problem when using custom renderer and editor

    Hello:
    I created a JTree with custom renderer and editor.
    The customization makes JCheckBox to be the component
    responsible for editing and rendering.
    The problem is that when I click on the node with the checkbox
    the JTree selection model does not get updated.
    Without customizations of the editor and renderer the MouseEvent would be fired and BasicTreeUI$MouseHandler.mousePressed() method would call
    the selectPathForEvent() method which would be responsible for updating
    the selection model. At the same time if I attach a mouse listener to the JTree (customized) I see the events when clicking on the nodes. It seems like the MouseEvent gets lost and somehow as a result of which the selection model does not get updated.
    Am I missing something?
    Thanks
    Alexander

    You probably forgot to call super.getTreeCellRendererComponent(...) at the beginning of your getTreeCellRendererComponent(...) method in your custom renderer.
    Or maybe in the getTreeCellEditorComponent(...) of the TreeCellEditor...

  • Why is a redirect not happening in a custom train model

    Dear All,
    I followed a post by Jobinesh here regarding supplying your custom train model in this post http://jobinesh.blogspot.com/2010/04/custom-model.html
    Now, I am extending the ProcessMenuModel and to create my navigation.
    I created a wildcard control flow to each of my page but I had set a redirect option also in each of my taskflow
    view.
    <control-flow-rule id="__22">
          <from-activity-id id="___33">*</from-activity-id>
          <control-flow-case id="__44">
            <from-outcome id="__10">employee</from-outcome>
            <to-activity-id id="__5">employee</to-activity-id>
          </control-flow-case>
          <control-flow-case id="__11">
            <from-outcome id="__13">department</from-outcome>
            <to-activity-id id="__121">department</to-activity-id>
          </control-flow-case>
          <control-flow-case id="__15">
            <from-outcome id="__16">manager</from-outcome>
            <to-activity-id id="__14">manager</to-activity-id>
          </control-flow-case>
    </control-flow-rule>
    <view id="employee">
          <page>/com/test/employee.jsff</page>
          <redirect/>
    </view>
    <view id="department">
          <page>/com/test/department.jsff</page>
          <redirect/>
    </view>
    <view id="manager">
          <page>/com/test/manager.jsff</page>
          <redirect/>
    </view>My concern is this, why is it that when I navigate in the train, it is not redirecting to another view even though I have set it explicitly?
    Thanks

    Below links may helpful for you.
    http://www.oracle.com/technetwork/developer-tools/adf/learnmore/82-programmatically-navigate-trains-396873.pdf
    http://docs.oracle.com/cd/E12839_01/web.1111/b31974/taskflows_complex.htm#CJHFBFIE
    http://jobinesh.blogspot.com/2010/04/custom-model.html

  • How can we get the value of the key field in a custom data model using governance API?

    Dear Team,
    How can we get the value of the key field in a custom data model, to be used for manipulation of the change request fields using governance API?
    Any kind of help would be sincerely appreciated.
    Thanks & Regards,
    Tushar.

    Hi Michael,
    Thanks for direction. Let me give more context on this as I'm interested to get more details..One of the issue was to read cross entity field values on UI based on user action and set other entity field behaviour...It is similar to what is being posted here.
    For ex: Reading MTART from Basic Data UIBB in MM MDG UI and set the field properties in some other custom entities say ZZETEST. This cannot be done using UI BADI as it only supports single entity at a time and not cross entity. So alternatively we found a solution where we can enhance existing PLMB feederclass cl_mdg_bs_mat_feeder_form by reading the model and the entity as needed as it it proved that it supports cross entity UI field behaviours and so business requirements.
    This is a workaround for now.
    So the question is How do we achive it using governance API for cross entity field behiaviours.?or what is the right way doing this.
    Can we do that using governance API and its' methods?
    In the Governance API doc you provided below has referring to below external model as part of gevernance API.
    The active or inactive data (before or during the derivation or the check) can be read
    with the external data model interface IF_USMD_MODEL_EXT with the method READ_CHAR_VALUE and
    the corresponding READ_MODE parameter. To avoid unnecessary flushes (derivations), the NO_FLUSH
    parameter should b
    e set to ‘X’.
    Thanks
    Praveen

  • Issue in creating a custom data model from BP

    Hi Team
    We have a requirement to create a custom data model by copying data model BP. I have successfully created new data model ZP . I have copied the UI for searching from BP. Issue is when i search a business partner  ideally it should not display any entries because i have just created the data model, But it is taking entries from BP and getting displayed. Please let me know how to map data model to search UI. I dont see option USMD_MODEL here

    Hi Imran,
    actually that is not an issue but a designed feature. I'm afraid that you need to re-think your whole project. The explanations is rather simple:
    Data model BP in MDG is a so called Re-Use Area data modell. This means that active data (records that are currently not stored in a change request) are saved in existing SAP ERP data base tables like BUT000 for the business partner master data and LFA1 or KNA1 for Vendor or Customer master data.
    If you copy data model BP to ZP you still refer to the same active area. You will always find the same active objects - no matter which data model you are actually using for the user interface. The only difference wil occur for objects being currently processed in a change request. In that case a separation between BP and ZP is possible. But this won't help to solve your issue.
    From SAP side I can only recommend not to copy BP but to find a different way of integrating your project needs into BP.
    Best regards
    Michael

  • JTable column headers not displaying using custom table model

    Hi,
    I'm attempting to use a custom table model (by extending AbstractTableModel) to display the contents of a data set in a JTable. The table is displaying the data itself correctly but there are no column headers appearing. I have overridden getColumnName of the table model to return the correct header and have tried playing with the ColumnModel for the table but have not been able to get the headers to display (at all).
    Any ideas?
    Cheers

    Class PublicationTableModel:
    public class PublicationTableModel extends AbstractTableModel
        PublicationManager pubManager;
        /** Creates a new instance of PublicationTableModel */
        public PublicationTableModel(PublicationManager pm)
            super();
            pubManager = pm;
        public int getColumnCount()
            return GUISettings.getDisplayedFieldCount();
        public int getRowCount()
            return pubManager.getPublicationCount();
        public Class getColumnClass(int columnIndex)
            Object o = getValueAt(0, columnIndex);
            if (o != null) return o.getClass();
            return (new String()).getClass();
        public String getColumnName(int columnIndex)
            System.out.println("asked for column name "+columnIndex+" --> "+GUISettings.getColumnName(columnIndex));
            return GUISettings.getColumnName(columnIndex);
        public Publication getPublicationAt(int rowIndex)
            return pubManager.getPublicationAt(rowIndex);
        public Object getValueAt(int rowIndex, int columnIndex)
            Publication pub = (Publication)pubManager.getPublicationAt(rowIndex);
            String columnName = getColumnName(columnIndex);
            if (columnName.equals("Address"))
                if (pub instanceof Address) return ((Address)pub).getAddress();
                else return null;
            else if (columnName.equals("Annotation"))
                if (pub instanceof Annotation) return ((Annotation)pub).getAnnotation();
                else return null;
            etc
           else if (columnName.equals("Title"))
                return pub.getTitle();
            else if (columnName.equals("Key"))
                return pub.getKey();
            return null;
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;
        public void setValueAt(Object vValue, int rowIndex, int colIndex)
        }Class GUISettings:
    public class GUISettings {
        private static Vector fields = new Vector();
        private static Vector classes = new Vector();
        /** Creates a new instance of GUISettings */
        public GUISettings() {
        public static void setFields(Vector f)
            fields=f;
        public static int getDisplayedFieldCount()
            return fields.size();
        public static String getColumnName(int columnIndex)
            return (String)fields.elementAt(columnIndex);
        public static Vector getFields()
            return fields;
    }GUISettings.setFields has been called before table is displayed.
    Cheers,
    garsher

  • "...in a custom Sequence Preset Editor."

    On page 1011 of the Final Cut Express User Manual, in the section "The Export QuickTime Movie Command", in the second paragraph, it suggests that there is a way to create a custom Sequence Preset. I quote:
    "You can also choose to use the existing settings of the clip or sequence you are exporting, or create customized settings in a custom Sequence Preset Editor."
    I desperately want to create a custom sequence preset. The last video I did for work I did at 1920 x 1080. The video is going on the companies site at 576 x 324. So I would rather just work in that size. But I cannot figure out how to create a sequence that size. Dose such a "Sequence Preset Editor" exist? And, where would I get one?
    Any help offered here would be most graciously welcomed.

    I don't really know what it means by that. However, in the paragraph before it it says:
    +"You can use this command to export Final Cut Express clips or sequences with their current settings or any of the sequence settings available in Final Cut Express. This command allows you to choose settings based on sequence presets in Final Cut Express"+.
    I can only assume that it means you can take the file into another program like Compressor to choose more settings instead. Or maybe it is referring to Quicktime Conversion, which gives you more options in exporting...
    Maybe someone else will know, but for now I am puzzled.

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • JButton in JTable with custom table model

    Hi!
    I want to include a JButton into a field of a JTable. I do not know why Java does not provide a standard renderer for JButton like it does for JCheckBox, JComboBox and JTextField. I found some previous postings on how to implement custom CellRenderer and CellEditor in order to be able to integrate a button into the table. In my case I am also using a custom table model and I was not able to create a clickable button with any of the resources that I have found. The most comprehensive resource that I have found is this one: http://www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm.
    It works fine (rendering and clicking) when I start it. However, as soon as I incorporate it into my code, the clicking does not work anymore (but the buttons are displayed). If I then use a DefaultTableModel instead of my custom one, rendering and clicking works again. Does anyone know how to deal with this issue? Or does anyone have a good pointer to a resource for including buttons into tables? Or does anyone have a pointer to a resource that explains how CellRenderer and CellEditor work and which methods have to be overwritten in order to trigger certain actions (like a button click)?
    thanks

    Yes, you were right, the TableModel was causing the trouble, everything else worked fine. Somehow I had this code (probably copy and pasted from a tutorial - damn copy and pasting) in my TableModel:
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 3) {
                    return false;
                } else {
                    return true;
    }A pretty stupid thing when you want to edit the 3rd column...

  • Custom table model, table sorter, and cell renderer to use hidden columns

    Hello,
    I'm having a hard time figuring out the best way to go about this. I currently have a JTable with an custom table model to make the cells immutable. Furthermore, I have a "hidden" column in the table model so that I can access the items selected from a database by their recid, and then another hidden column that keeps track of the appropriate color for a custom cell renderer.
    Subject -- Sender -- Date hidden rec id color
    Hello Pete Jan 15, 2003 2900 blue
    Basically, when a row is selected, it grabs the record id from the hidden column. This essentially allows me to have a data[][] object independent of the one that is used to display the JTable. Instinctively, this does not seem right, but I don't know how else to do it. I know that the DefaultTableModel uses a Vector even when it's constructed with an array and I've read elsewhere that it's not a good idea to do what I'm trying to do.
    The other complication is that I have a table sorter as well. So, when it sorts the objects in the table, I have it recreate the data array and then set the data array of the ImmutableTableModel when it has rearranged all of the items in the array.
    On top of this, I have a custom cell renderer as well. This checks yet another hidden field and displays the row accordingly. So, not only does the table sort need to inform the table model of a change in the data structure, but also the cell renderer.
    Is there a better way to keep the data in sync between all of these?

    To the OP, having hidden columns is just fine, I do that all the time.. Nothing says you have to display ALL the info you have..
    Now, the column appears to be sorting properly
    whenever a new row is added. However, when I attempt
    to remove the selected row, it now removes a seemingly
    random row and I am left with an unselectable blank
    line in my JTable.I have a class that uses an int[] to index the data.. The table model displays rows in order of the index, not the actual order of the data (in my case a Vector of Object[]'s).. Saves a lotta work when sorting..
    If you're using a similar indexing scheme: If you're deleting a row, you have to delete the data in the vector at the INDEX table.getSelectedRow(), not the actual data contained at
    vector.elementAt(table.getSelectedRow()). This would account for a seemingly 'random' row getting deleted, instead of the row you intend.
    Because the row is unselectable, it sounds like you have a null in your model where you should have a row of data.. When you do
    vector.removeElementAt(int), the Vector class packs itself. An array does not. If you have an array, when you delete the row you must make sure you dont have that gap.. Make a new array of
    (old array length-1), populate it, and give it back to your model.. Using Vectors makes this automatic.
    Also, you must make sure your model knows the data changed:
    model.fireTableDataChanged(); otherwise it has no idea anything happened..
    IDK if that's how you're doing it, but it sounds remarkably similar to what I went thru when I put all this together..

  • JTable: Custom Table Model (pI)

    This is a follow-up to thread http://forum.java.sun.com/thread.jspa?threadID=725162 and thread http://forum.java.sun.com/thread.jspa?threadID=725158.
    As I'm hoping to have a table of 5 columns, where the 4th and 5th columns are for integer and float data types respectively, I am creating a custom table model under the assumption that I will not know beforehand the number of rows the table will contain.
    Problems? Having not specified the cell contents of the table, since it will be pupulated by users unknown to me, I did not declare or initialize a variable similar to TableDemo's data variable of type Object (see the TableDemo tutorial http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/TableDemo.java). As such, I am unable to specify the return parameters for the getRowCount() and getValueAt(~, ~) methods.
    To overcome this, I sought to replicate the example shown in TableDemo by doing the following:
    Object[][] cell = {"", "", "", new Integer(0), new Float(0.00f)};
    public int getRowCount()
      returncell.length;
    public Object getValueAt(int row, int column)
      return cell[row][column];
    //...I got the following errors:
    pathname\CustomTableModel.java:line #: incompatible types
    found: java.lang.String
    required: java.lang.Object[]
    and the errors continue...
    So I tried
    Object[] cell = {"", "", "", new Integer(0), new Float(0.00f)};
    // ...However, I got this error:
    C:\...\CustomTableModel.java:line #:array required, but java.lang.String found
    return cell[row][column];
    .......................... ^
    I just want to set the return parameters for getRowCount() and getValueAt(~,~) in the custom table model I'm creating. How do I do this?
    Cheers!
    PS Thanks for reading this far...

    I decided to use the DefaultTableModel, after all. I was using it before, but at the time, i didn't know that certain things I wanted to accomplish, it could too.
    Anyways, here's what I have been doing: http://forum.java.sun.com/thread.jspa?threadID=725861
    Thanks nonetheless for your help. And by the way, my client is adamant that I use a LinkedList, rather than a Vector for this project. But nevertheless, thanks.

  • JTable: Custom Table Model (pII)

    As was explained in pI, I'm creating a custom table model to overcome a few pitfalls I came across using the DefaultTableModel class, such as aligning cells, and getting certain columns to return only numeric type data. However, I've come upon a few roadblocks myself.
    How do I create each of the following methods:
    insertRow(int ow, int column)
    remove row(int row)
    addRow(Object[] rowData)Assuming that I decide to allow the user to add a column to the table, how would I create the methodaddColumn(Object columnName, Object[] columnData)And also, as I'm creating a custom table model, would I need to replicate DefaultTableModel's methods that inform the listeners that a change has been made to the table?
    Thanks!

    Thanks!
    I just got this response. Anyways, I found another solution that was, interestingly, from one of your threads written in 2005.
    This is what I did:
    // Letting the JTable know what each column stores and should return by
       // overloading the getColumnClass() method
       public Class getColumnClass(int column)
            if(recordsTable.getColumnName(column) == "Ranking")
              return Integer.class;
         /* Why do I keep ketting an IllegalArgumentException here? *
           * It keeps saying it cannot format given object as a Number */            
            else if(recordsTable.getColumnName(column) == "Price (�) ")
              return Float.class;
         else
           return getValueAt(0, column).getClass();         
       }However, another problem has arisen.
    The if method for the int column (Ranking column) works okay, and is even right-aligned. The else if arguments for the Price (�) column however is returning an IllegalArgumentException. This I just cannot figure out.
    Here's the code:package Practice;
      import java.awt.BorderLayout;
      import java.awt.Frame;
      import java.awt.Menu;
      import java.awt.MenuBar;
      import java.awt.MenuItem;
      import java.awt.MenuShortcut;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      import java.awt.event.KeyEvent; // for MenuItem shortcuts
      import java.awt.event.WindowAdapter;
      import java.awt.event.WindowEvent;
      import java.awt.event.WindowListener;
      import javax.swing.JOptionPane;
      import javax.swing.JScrollPane; // JTable added to it, aiding flexibility
      import javax.swing.JTable; // The personally preferred GUI for this purpose
            // Provides a basic implementation of TableModel
      import javax.swing.table.DefaultTableModel;
              // This class uses Vector to store the rows and columns of data, though
              // programmer will be using LinkedLists
      import java.util.LinkedList;
      // User-defined classes
      import Practice.MusicDatabase;
      public class MusicBank extends Frame implements ActionListener
         MusicDatabase mDBase;
         Frame frame;
         String title = "",      // Frame's title
                file = "";           // pathname of the file to be opened
          // Declaring Menu and MenuItem variables
         Menu recordM; // ...
         // recordM
         MenuItem newRecordR_MI, deleteRecordR_MI;
         // Other irrelevant menus and sub items
        DefaultTableModel recordDetails;
        JTable recordsTable;
        LinkedList musicList;
        public MusicBank()
            musicList = new LinkedList();
            frame = new Frame(title);
            frame.setMenuBar(menuSystem());
            // Should user seek to close window externally
            frame.addWindowListener(new WindowAdapter()
                 public void windowClosing(WindowEvent we)
                     frame.dispose();
                     System.exit(0);
         recordDetails = new DefaultTableModel();
         // Creating the relevant columns
         recordDetails.addColumn("Title");
         recordDetails.addColumn("Identity");
         recordDetails.addColumn("Music Company");
         recordDetails.addColumn("Ranking");
         recordDetails.addColumn("Price (�) ");
         // Ensuring the table has at least one visible record (empty)
         recordDetails.addRow(populateRow("", "", "", 0, 0.00f));
         // Creating the table to display the data files (music record details)
         recordsTable = new JTable(recordDetails)
             // Letting the JTable know what each column stores and should return by
             // overloading the getColumnClass() method
            public Class getColumnClass(int column)
               if(recordsTable.getColumnName(column) == "Ranking")
                   return Integer.class;
                /* Why do I keep ketting an IllegalArgumentException here? *
                 * It keeps saying it cannot format given object as a Number */            
                else if(recordsTable.getColumnName(column) == "Price (�) ")
                    return Float.class;
                else
                    return getValueAt(0, column).getClass();         
      // Creating the menus
      public MenuBar menuSystem()
          MenuBar bar = new MenuBar();
          // Record menu and related items
          recordM = new Menu("Record");
          recordM.setShortcut(new MenuShortcut(KeyEvent.VK_R, false));        
          newRecordR_MI = new MenuItem("New record");
          newRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_N, false));
          deleteRecordR_MI = new MenuItem("Delete record");
          deleteRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_D, false));
           recordM.add(newRecordR_MI);
           recordM.addSeparator();
           recordM.add(deleteRecordR_MI);
            // Enabling menus with functionality
           newRecordR_MI.addActionListener(this);
           deleteRecordR_MI.addActionListener(this);
           // Adding menus and items to menu bar
           bar.add(recordM);
           return bar;        
      public void actionPerformed(ActionEvent ae)
          if(ae.getSource() == newRecordR_MI)
             newRecord();
          else if(ae.getSource() == deleteRecordR_MI)
             deleteRecord();       
      // Object that will be used, in conjunction with MusicDatabase's, to 
      // populate the JTable
      // A record in a JTable is equivalent to an element in a LinkedList
      public Object[] populateRow(String title, String name, String comp, int rank, float price)
          // First, update the LinkedList
          mDBase = new MusicDatabase(title, name, comp, rank, price);
          musicList.add(mDBase);
           // Then, update the table
           // As the parameters of Object tableDetails can only take a String or
           // object, rank and price will have to be cast as a String and later
           // parsed to their original form before use.
           String rankPT = ""+rank, pricePT = ""+price;        
           Object rowDetails[] = {title, name, comp, rankPT, pricePT};
           return rowDetails;
      public static void main(String args[])
          MusicBank app = new MusicBank();
           // Using the platform's L&F (if Win32,  Windows L&F; Mac OS, Mac OS L&F,
           // Sun, CDE/Motif L&F)
           // For more on this, refer to the WinHelp Java tutorial by F. Allimont
           try
               UIManager.getSystemLookAndFeelClassName();
           catch(Exception e)
               JOptionPane.showMessageDialog(app,
                    "Failed to create the Windows Look and Feel for this program",
                    "Look and Feel (L&F) error",
                    JOptionPane.ERROR_MESSAGE);
           app.frame.setSize(500, 500);
           app.frame.setVisible(true);
            // Placing frame in the centre of the screen on-loading
           app.frame.setLocationRelativeTo(null);
      // action methods per menu items
      // Also, why do I keep getting an ArrayIndexOutOfBoundsException
      // here? I do know what this exception is, and how it works, but just cannot
      // understand what is causing it
      public void newRecord()
          // Before adding a new record, check if previous record has complete
          // entries. If not, either display a message (JOptionPane) or disallow
          // request (simply do nothing)        
          // Proceed based on assesment
          if(queryState() == true)
              // Inform user that all entries need to be filled in before a new
              // record can be created
              JOptionPane.showMessageDialog(this, // current frame
                       "There are incomplete cells in the table."+
                       "\nPlease fill these in before proceeding",       // Message to user
                       "Incomplete entries",                                // Title
                       JOptionPane.ERROR_MESSAGE);                           // Relevant icon
          else
               // To ensure that both the linked list & the table are simultaneously
               // updated, JOptionPane's input dialogs are used to temporarily store
               // the data which is then inputted into both (linked list and JTable)
              String titleN, identityN, companyN; int rankN; float priceN;
              titleN = JOptionPane.showInputDialog(this, "Enter song title");
              identityN = JOptionPane.showInputDialog(this,                                      "Enter name of singer/band");
             companyN = JOptionPane.showInputDialog(this,                                 "Enter signed/unsigned company");
             rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
                             "Enter rank (a number)") );
            System.out.println("\n JTable rows = "+recordDetails.getRowCount());
             // Ensuring that the chosen rank is not already entered
             /* Problem lies here */
             for(int row = 1; row <= recordDetails.getRowCount(); ++row)
                 if((recordDetails.getValueAt(row, 4)).equals(""+rankN))
                     rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
                             "That number's already chosen.\nPlease enter a rank ") );
             priceN = Float.parseFloat( JOptionPane.showInputDialog(this,                                 "Finally, enter price �") );
             mDBase = new MusicDatabase(titleN, identityN, companyN, rankN, priceN);
             musicList.add(mDBase);
             recordDetails.addRow(populateRow(titleN, identityN, companyN, rankN,
         priceN));
             System.out.println("JTable rows after creation = "+
                   recordDetails.getRowCount());
         // Enabling the delete record menu item (as necessary)
         if((recordsTable.getRowCount()) > 0)
              deleteRecordR_MI.setEnabled(true);
      } // newRecord()
      public void deleteRecord()
         int selectedRow = recordsTable.getSelectedRow();
         recordDetails.removeRow(selectedRow);
          // Removing the element from the LinkedList's corresponding index
          musicList.remove(selectedRow);
          System.out.println("Existing rows = "+recordsTable.getRowCount());
           // If there are no more rows, disallow user from trying to delete rows
           if(selectedRow <= 0)
              deleteRecordR_MI.setEnabled(false);
      } // deleteRecord()
      // Method to query if all cells have changed their states (empty or not)
      public boolean queryState()
          // Obtaining number of rows
          int rows = recordDetails.getRowCount();
          int columns = recordDetails.getColumnCount();
          boolean isEmpty = false; // cell
          System.out.println("Rows = "+rows);
          System.out.println("Columns = "+columns);
          try{
              // Assessing all cells for complete entries
              // This approach is flexible, rather than hardcoding the rows available,
              // making it more reusable (assuming it will always be 5 columns)
              for (int rowIndex = 0; rowIndex<=rows; ++rowIndex)
                  if((recordDetails.getValueAt(rowIndex, 1)).equals(""))
                 isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 2)).equals(""))
               isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 3)).equals(""))
               isEmpty = true;                
                  else if((recordDetails.getValueAt(rowIndex, 4)).equals("0"))
               isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 5)).equals("0.00"))
               isEmpty = true;
          catch(Exception e)
             System.out.println(e.getMessage());
          return isEmpty;
      Now here is the code for the MusicDatabase class
    package Practice;
    class MusicDatabase
        private String songTitle, identity, musicCompany;
        private int rank;
        private float priceF;
        // Defining the constructor
        public MusicDatabase(String title, String name, String company,                                int rankingInt, float price)
           songTitle = title;
           identity = name;
           musicCompany = company;
           rank = rankingInt;
           priceF = price;
        } // constructor
       // Other methods
    } // class MusicDatabaseSorry, but am not sure if these codes are executable, as where I am (a general library), JVM is not on the machine I am using. (Remember, i don't have ready acess to the Internet, so I could not use my machine, nor the facilities that had the JVM - unavailable to me at the time).
    Thanks!
    Reformer...
    PS I do hope the code pasted was not too much. Kind regards....

  • Custom table model won't cast

    Hi, I have a JTable with a custom table model that extends AbstractTableModel. I want to take the number of a selected table row and pass it to a method of my custom model to get back the original complex object represented by the row.
    int x = mytable.getSelectedRow();
    MyTableModel model = (MyTableModel)(mytable.getModel());
    MyOwnClass orig = model.myConversionMethod(x);
    Problem: when I call mytable.getModel() then cast it to my custom model class (so I can call this conversion method) I get a ClassCastException.
    What am I doing wrong? Thanks in advance for any help/advice you can give.
    Mike

    Where is the table model created?Right after the JTable is created, I call...
    mytable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    mytable.setModel(new SortFilterModel(new MyTableModel()));

Maybe you are looking for