Ctrl+V on a JTable

What method is called when I press Ctrl+V after selecting a row on a JTable? I tried using the copy() method which works on a text area/field but it doesn't work on the table. Ctrl+V works, but calling the
copy() method doesn't.

I'm not sure if this is what you want, but the ctrl+v action is the paste action. Are you trying to override the paste with the copy action?
JTable already has the cut, copy, paste and a lot more ready for use. Below is what happens when a key action is executed on a JTable.
"When the table component has the focus and a key (or combination of keys) is pressed, JTable's processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) method is eventually called. That method starts by executing boolean retVal = super.processKeyBinding (ks, e, condition, pressed); (which is found in JComponent). The method checks to see if ks is located in the component's input map (that is, a set of mappings from Keystroke objects to Action names). If found, the resulting Action name is checked against the component's Action map (that is, a set of mappings from Action names to Action objects) to see if that map contains an Action object that associates with the Action name. If so, SwingUtilities' notifyAction(Action action, KeyStroke ks, KeyEvent event, Object sender, int modifiers) method is called to create an ActionEvent object and call the Action's actionPerformed(ActionEvent e) method. Assuming that the actionPerformed(ActionEvent e) method is called, retVal contains a value that causes processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) to exit. Otherwise, that method automatically starts an editor for the focused cell"
-- Exploring Swing's Table Component
-- http://www.informit.com/isapi/product_id~%7BCC10A6C8-9E4A-4FC4-B158-5C8BC41A879E%7D/element_id~%7B236A3815-39EF-4EF9-B2B3-553B3734E763%7D/st~%7B94C03A97-1188-4875-8A06-17743BA224B7%7D/content/articlex.asp
Hope this helps

Similar Messages

  • Ctrl PgUp / CtrlPgDown in JTables vs JTabbedPanes

    Hi there, another wee JTable problem.
    I want Ctrl PageUp and Ctrl PageDown to move between JTabbedPanes. This normally works, except when the focus is currently in a JTable. I want it to also work if the focus is in a JTable.
    I have tried to stop the JTable from handling the keys by setting the inputmap to "none" but this has no effect (you can see my code for this below).
    Here is a test program that shows the bad behaviourimport java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class TestTable extends JTable {
         public TestTable(Object[][] data, Object[] headings) {
              super(data, headings);
              setFocusTraversalPolicyProvider(true);
              // Turn off Ctrl PgUp and Ctrl PgDown handling so tab navigation works.
              InputMap inputs = getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              KeyStroke ctrlPgUpKey = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_DOWN_MASK);
              inputs.put(ctrlPgUpKey, "None");
              KeyStroke ctrlPgDownKey = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_DOWN_MASK);
              inputs.put(ctrlPgDownKey, "None");
         public boolean isCellEditable(int row, int column) {
              return false;
         public static void main(String[] args) {
              JFrame frame = new JFrame("Test table");
              JTabbedPane pane = new JTabbedPane();
              frame.add(pane);
              JPanel panel = new JPanel();
              JTextField field = new JTextField("Key Ctrl PgDown or Ctrl PgUp");
              panel.add(field);
              pane.add("test1", panel);
              pane.add("test2", new JScrollPane(new TestTable(new String[][] {{"hello", "me"}}, new String[]{"H1", "H2"})));
              pane.add("test3", new JPanel());
              frame.setBounds(100, 100, 300, 300);
              frame.setVisible(true);
    }Thanks,
    Tim

    i had a similiar problem, had some UIs that had a Tabbed pane and
    ScrollBars, and some tabs had JTables in them, anyhow, I just wanted
    Control-Page_up/Down to work for the JTabbedPane all the the time so
    I did this in my windows look and feel applications and all was well, just posting so maybe this will help someone down the road
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    UIDefaults uiDefaults = UIManager.getDefaults();
    // ginny wants Control-Page-Up and Control-Page-Down to work for tabbed
    // panes, which it does by default, however, it also works for JTable
    // and JScrollPane, and those components grab the keystroke 1st if they are
    // all in the same screen, so disabling it for JTable and JScrollPane
    // see WindowsLookAndFeel.java
    uiDefaults.remove("ScrollPane.ancestorInputMap");
    uiDefaults.put("ScrollPane.ancestorInputMap",
    new UIDefaults.LazyInputMap(new Object[] {
    "RIGHT", "unitScrollRight",
    "KP_RIGHT", "unitScrollRight",
    "DOWN", "unitScrollDown",
    "KP_DOWN", "unitScrollDown",
    "LEFT", "unitScrollLeft",
    "KP_LEFT", "unitScrollLeft",
    "UP", "unitScrollUp",
    "KP_UP", "unitScrollUp",
    "PAGE_UP", "scrollUp",
    "PAGE_DOWN", "scrollDown",
    "ctrl PAGE_UP", "None", //"scrollLeft",
    "ctrl PAGE_DOWN", "None",//"scrollRight",
    "ctrl HOME", "scrollHome",
    "ctrl END", "scrollEnd"
    uiDefaults.remove("Table.ancestorInputMap");
    uiDefaults.put("Table.ancestorInputMap",
    new UIDefaults.LazyInputMap(new Object[] {
    "ctrl C", "copy",
    "ctrl V", "paste",
    "ctrl X", "cut",
    "COPY", "copy",
    "PASTE", "paste",
    "CUT", "cut",
    "RIGHT", "selectNextColumn",
    "KP_RIGHT", "selectNextColumn",
    "LEFT", "selectPreviousColumn",
    "KP_LEFT", "selectPreviousColumn",
    "DOWN", "selectNextRow",
    "KP_DOWN", "selectNextRow",
    "UP", "selectPreviousRow",
    "KP_UP", "selectPreviousRow",
    "shift RIGHT", "selectNextColumnExtendSelection",
    "shift KP_RIGHT", "selectNextColumnExtendSelection",
    "shift LEFT", "selectPreviousColumnExtendSelection",
    "shift KP_LEFT", "selectPreviousColumnExtendSelection",
    "shift DOWN", "selectNextRowExtendSelection",
    "shift KP_DOWN", "selectNextRowExtendSelection",
    "shift UP", "selectPreviousRowExtendSelection",
    "shift KP_UP", "selectPreviousRowExtendSelection",
    "PAGE_UP", "scrollUpChangeSelection",
    "PAGE_DOWN", "scrollDownChangeSelection",
    "HOME", "selectFirstColumn",
    "END", "selectLastColumn",
    "shift PAGE_UP", "scrollUpExtendSelection",
    "shift PAGE_DOWN", "scrollDownExtendSelection",
    "shift HOME", "selectFirstColumnExtendSelection",
    "shift END", "selectLastColumnExtendSelection",
    "ctrl PAGE_UP", "None", //"scrollLeftChangeSelection",
    "ctrl PAGE_DOWN", "None", //"scrollRightChangeSelection",
    "ctrl HOME", "selectFirstRow",
    "ctrl END", "selectLastRow",
    "ctrl shift PAGE_UP", "scrollRightExtendSelection",
    "ctrl shift PAGE_DOWN", "scrollLeftExtendSelection",
    "ctrl shift HOME", "selectFirstRowExtendSelection",
    "ctrl shift END", "selectLastRowExtendSelection",
    "TAB", "selectNextColumnCell",
    "shift TAB", "selectPreviousColumnCell",
    "ENTER", "selectNextRowCell",
    "shift ENTER", "selectPreviousRowCell",
    "ctrl A", "selectAll",
    "ESCAPE", "cancel",
    "F2", "startEditing"
    }));

  • How to override Ctrl-Click behavior in Java L&F

    On the Mac, Ctrl-Click is the popup trigger. While Java L&F designers were obviously aware of this (it is warned about in the Java Look and Feel Design Guidelines, 2nd ed, page 106). However, just two pages later (page 108), they then generically specifify that Ctrl-Click is used in lists and tables to toggle the selection.
    The implementation of the Java L&F does not appear to consider the Mac's use of Ctrl-Click and still toggles selection. If there is an additional mouse listener that shows a menu in response to the popup trigger, it will ALSO open the menu on Ctrl-Click.
    What is the best way to overide the Ctrl-Click behavior in JTable etc. to NOT do the toggle selection? Note that this is a mouse event and not a key event, so it can't be turned off or changed by the getActionMap() mechanism.
    Also, does anyone know what the "Command" modifier on the Mac (Command-Click is supposed to toggle selection on Macs) shows up as in the InputEvent (isMetaDown(), isAltGraphDown()...)?

    Try extending the JList and override the processMouseEvent(MouseEvent evt) method and show your popup menu when the user clicks the mouse while holding the CTRL key down. The code below demonstrates the same.
    import java.awt.BorderLayout;
    import java.awt.event.MouseEvent;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.ListModel;
    import javax.swing.WindowConstants;
    public class Temp extends JFrame {
         public Temp() {
              super("Temp");
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              String [] items = {"One", "Two", "Three", "Four", "Five"};
              JList list = new MyList(items);
              JScrollPane scroller = new JScrollPane(list);
              getContentPane().add(scroller, BorderLayout.CENTER);
              pack();
              setVisible(true);
         class MyList extends JList {
              public MyList() {
                   super();
              public MyList(Object[] listData) {
                   super(listData);
              public MyList(Vector listData) {
                   super(listData);
              public MyList(ListModel dataModel) {
                   super(dataModel);
              protected void processMouseEvent(MouseEvent evt) {
                   System.out.println(evt.isPopupTrigger());
                   int onmask = MouseEvent.CTRL_DOWN_MASK | MouseEvent.BUTTON1_DOWN_MASK;
                   if(evt.getModifiersEx() == onmask) {
                        JOptionPane.showMessageDialog(this, "Control + click");
                   else {
                        super.processMouseEvent(evt);
         public static void main(String[] args) {
              new Temp();
    }Hope this helps
    Sai Pullabhotla

  • Dragging multiple rows in JTable - MUST use CTRL, or not?

    Hello all!
    I'm writing an app that needs to be able to drag multiple rows from a JTable. I have seen that I can do this by selecting multiple rows with the LEFT mouse button, while holding down the CTRL key, and then dragging (again, with the left mouse button).
    The problem is, since I'm holding down the CTRL key, this comes across as a DnDConstants.ACTION_COPY.
    I find that if I do multiple selection, then drag with the RIGHT mouse button (no CTRL key held down), then I get a DnDConstants.ACTION_MOVE, as I want.
    My question: Is there any simple way to enable dragging multiple JTable rows, using the LEFT mouse button, but WITHOUT holding down the CTRL key?
    I have been tasked with "making it act like Windows", which doesn't undo a multiple-selection when one clicks on an existing selected row until one lets go of the left mouse button; whereas JTables appear to change the selection to the clicked-upon row immediately, even if it is part of the existing selection.
    Any ways around this anyone knows, short of modifying the JTable or BasicTableUI itself?
    - Tim

    By the way, I just tested this assumption of mine, and found I was wrong if you're using default JTable drag and drop.
    However, I'm using my own implementation. I notice in a simple program without any drag and drop, I get the behavior I mentioned above, so I'm guessing this IS default JTable behavior, which is then modified by the built-in drag and drop support.
    So the trick will be, how to do what built-in drag and drop is doing, without using built-in drag and drop. :-)
    - Tim

  • Navigate JTable using Ctrl and arrow combination

    By default, one way to navigate cells in a JTable is by using the arrow keys. I need to change this so that the user must hold down the Ctrl key and then navigate with the arrows. The arrow keys alone will not have any cell navigation functionality... they will only be used for editing cells that contain a JTextField (or some variant).
    Can anyone help me with this? BTW...I am using jdk 1.4.1_03

    To answer my own question:
    Using the InputMap and ActionMap of the JTable, the keybindings can be removed or added, so for moving one column to the right by holding down CTRL and pressing the right arrow, it is as simple as:
    InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    // KeyEvent.VK_RIGHT is the right arrow key, and 2 is the CTRL key mask
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 2), "selectNextColumn");Here are some links that were of help:
    http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/doc-files/Key-Index.html
    http://javaalmanac.com/egs/javax.swing/ListKeyBinds.html?l=rel
    http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html

  • Handling behaviour of Ctrl - End of JTable

    I use JTable to show the data. Since i have a huge list of data, we load data lazily, Initially the data is loaded and shown that fits the screen and then upon scroll down we load the required data . In the current scenario, when the user presses Ctrl - End, it only selects the last loaded record [Only data that is loaded so far/ last record seen on the screen], rather what i want to achieve is, handle the Ctrl - End and then load all the data and then select the last (really last) record.
    Thanks,
    Sarat.

    ryaliscs wrote:
    I use JTable to show the data. Since i have a huge list of data, we load data lazily,I always consider this approach to viewing a 'huge list of data' as being flawed. It seems silly to me to get the user to scroll through hundreds or thousands of lines to find a particular line. It is normally better to only show the lines that match some search criteria.
    As for the rest of your requirement . Since we have no view of your code, only you know enough about your design and code to stand a chance of suggesting the changes necessary.

  • Ctrl+tab is not working in editing mode

    I have JcheckBox and JTable in my JPanel. When user clicks or presses F2 to edit any cell value of the JTable a comboBox will appear with possible values. (This comboBox is coming from table CellEditor). When user presses ctrl+tab from the table focus should transfer to JComboBox all time. It is working only when the user presses ctrl+tab from the table cell which is not in editing mode. If the user presses ctrl+tab from the table cell which is in editing mode (i.e. focus is on the ComboBox of the cellEditor) it does not work. Please help me to find the solution.
    I give a sample code here for your reference.
    public class Frame1 extends JFrame {
    public Frame1()
    super();
    this.setLayout( null );
    this.setSize( new Dimension(400, 300) );
    JTextField ch = new JTextField();
    ch.setVisible(true);
    ch.setBounds(10, 10, 10, 10);
    this.add(ch, null);
    DefaultTableModel tmodel = new DefaultTableModel(3, 1);
    tmodel.setValueAt("0 0 1",0,0);
    tmodel.setValueAt("1 0 1",1,0);
    tmodel.setValueAt("2 0 1",2,0);
    JTable custLayersTable = new JTable(tmodel);
    custLayersTable.getColumnModel().getColumn(0).
    setCellEditor(new ComboEditor());
    custLayersTable.setBounds(new Rectangle(40, 40, 280, 145));
    custLayersTable.setSurrendersFocusOnKeystroke(true);
    this.add(custLayersTable, null);
    public static void main(String[] args)
    Frame1 a = new Frame1();
    a.setVisible(true);
    final class ComboEditor extends AbstractCellEditor
    implements TableCellEditor
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    Vector<String> layerValSet = new Vector<String>();
    for(int i=0; i<3; i++)
    layerValSet.add(row+" "+column+" "+i);
    mComboModel = new DefaultComboBoxModel(layerValSet);
    mComboModel.setSelectedItem(value);
    mEditorComp = new JComboBox(mComboModel);
    return mEditorComp;
    public Object getCellEditorValue()
    return mEditorComp.getSelectedItem();
    private DefaultComboBoxModel mComboModel;
    private JComboBox mEditorComp;
    }

    Thanks a lot for your reply.
    Since the textField is in a different class i could not use the transferFocus API directly. I tried the following code in the keyreleased event of Combo Box but it was not working.
    KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(
    e.getComponent().getParent());
    I also tried the following code in stopCellEditing and is not working.
    KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
    Is there any other way to achieve this?

  • JTable and clipboard...

    Hi all!
    I'm trying to copy data from JTable to system clipboard. Here's my code that is
    supposed to do that except it doesn't work. Nothing happens. The system is
    Windows, rigth click invokes menu with only one position - COPY, which is served
    by a appopriate ActionListener. I want to copy entire table (all data):
    private class NotEditableTable extends JTable
    NotEditableTable(Object[][] data, Object[] columnNames)
    super(data, columnNames);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    setCellSelectionEnabled(true);
    getTableHeader().setReorderingAllowed(false);
    NotEditableTableEngine nete = new NotEditableTableEngine();
    this.addMouseListener(nete);
    public boolean isCellEditable(int row, int column)
    return false;
    private class NotEditableTableEngine extends MouseAdapter implements ActionListener
    public void mouseReleased(MouseEvent e)
    if (e.isPopupTrigger())
    JPopupMenu menu = new JPopupMenu();
    JMenuItem menuitem = new JMenuItem(Lang.TABLE_COPY, new ImageIcon("res/Copy16.gif"));
    menuitem.addActionListener(this);
    menu.add(menuitem);
    menu.show(NotEditableTable.this, e.getX(), e.getY());
    public void actionPerformed(ActionEvent e)
    TransferHandler th = new TransferHandler(null);
    NotEditableTable.this.setTransferHandler(th);
    Clipboard clip = NotEditableTable.this.getToolkit().getSystemClipboard();
    th.exportToClipboard(NotEditableTable.this, clip, TransferHandler.COPY);
    }

    I also tried the code above with a simple JTextField, both with text selected and not.Did my sample code use the TransferHandler??? The simple way to do it for a JTextField would be
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection testData = new StringSelection( textField.getText );
    //StringSelection testData = new StringSelection( textField.getSelectedText );
    c.setContents(testData, testData);
    As for the table I said that the Ctrl-C KeyStroke will invoke the default Action to copy selected data from the JTable to the Clipboard. This can be tested manually by simply using Ctrl-C. If you want to invoke it in your program then you need to get the corresponding Action from the JTable and invoke the ActionPerformed method of the Action. You can try using the
    getActionForKeyStroke(...) method of JComponent to get the Action.

  • How to add a JMenubar and a JTable in a JFrame in a single application

    Hi all,
    I require an urgent help from you.I am a beginer in programming Swing.I want to add a menu,combobox,and a table in a single application.I did coding as below:
    package com.BSS;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class newssa extends JFrame
         public JMenuBar menuBar;
         public JToolBar toolBar;
         public JFrame frame;
         private JLabel jLabel1;
         private JLabel jLabel2;
         private JLabel jLabel3;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel6;
         private JComboBox jComboBox1;
         private JComboBox jComboBox2;
         private JComboBox jComboBox3;
         private JComboBox jComboBox4;
         private JComboBox jComboBox5;
         private JComboBox jComboBox6;
         private JTable jTable1;
         private JScrollPane jScrollPane1;
         private JPanel contentPane;
         public newssa()
              super();
              initializeComponent();
              this.setVisible(true);
         private void initializeComponent()
              jLabel1 = new JLabel();
              jLabel2 = new JLabel();
              jLabel3 = new JLabel();
              jLabel4 = new JLabel();
              jLabel5 = new JLabel();
              jLabel6 = new JLabel();
              jComboBox1 = new JComboBox();
              jComboBox2 = new JComboBox();
              jComboBox3 = new JComboBox();
              jComboBox4 = new JComboBox();
              jComboBox5 = new JComboBox();
              jComboBox6 = new JComboBox();
              frame=new JFrame();
              //Included here
              JMenuBar menuBar = new JMenuBar();
              JMenu general = new JMenu("General");
         menuBar.add(general);
         JMenu actions =new JMenu("Actions");
         menuBar.add(actions);
         JMenu view=new JMenu("View");
         menuBar.add(view);
         JMenu Timescale=new JMenu("TimeScale");
         menuBar.add(Timescale);
         Timescale.add("Today CTRL+D");
         Timescale.add("Current Week CTRL+W");
         Timescale.add("Current Month CTRL+M");
         Timescale.add("Current Quarter CTRL+Q");
         Timescale.add("Current Year CTRL+Y");
         Timescale.add("Custom TimeScale CTRL+U");
         JMenu start=new JMenu("Start");
         menuBar.add(start);
         JMenu options=new JMenu("Options");
         menuBar.add(options);
         JMenu help=new JMenu("Help");
         menuBar.add(help);
         JFrame.setDefaultLookAndFeelDecorated(true);
         frame.setJMenuBar(menuBar);
         frame.pack();
         frame.setVisible(true);
         toolBar = new JToolBar("Formatting");
         toolBar.addSeparator();
              //Before this included new
              String columnNames[] = { "ColorStatus", "Flash", "Service Order","Configuration","Configuration Description"};
              // Create some data
              String dataValues[][] =
                   { "blue", "flash", "ORT001" },
                   { "AVCONF", "av configuration with warrenty"}
              // Create a new table instance
              //jTable1 = new JTable( dataValues, columnNames );
              jTable1 = new JTable(dataValues,columnNames);
              jScrollPane1 = new JScrollPane(jTable1);
              contentPane = (JPanel)this.getContentPane();
              //scrollPane = new JScrollPane( table );
              //topPanel.add( scrollPane, BorderLayout.CENTER );
              // jLabel1
              jLabel1.setText("Service Centers");
              // jLabel2
              jLabel2.setText("Service Areas");
              // jLabel4
              jLabel3.setText("Skills");
              jLabel4.setText("Availablity Types");
              // jLabel5
              jLabel5.setText("From Date");
              // jLabel6
              jLabel6.setText("To");
              // jComboBox1
              jComboBox1.addItem("Coimbatore");
              jComboBox1.addItem("Chennai");
              jComboBox1.addItem("Mumbai");
              jComboBox1.addItem("New Delhi");
              jComboBox1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox1_actionPerformed(e);
              // jComboBox2
              jComboBox2.addItem("North Zone");
              jComboBox2.addItem("South Zone");
              jComboBox2.addItem("Central Zone");
              jComboBox2.addItem("Eastern Zone");
              jComboBox2.addItem("Western Zone");
              jComboBox2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox2_actionPerformed(e);
              // jComboBox3
              jComboBox3.addItem("Microsoft Components");
              jComboBox3.addItem("Java Technologies");
              jComboBox3.addItem("ERP");
              jComboBox3.addItem("Others");
              jComboBox3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox3_actionPerformed(e);
              // jComboBox4
              jComboBox4.addItem("One");
              jComboBox4.addItem("Two");
              jComboBox4.addItem("Three");
              jComboBox4.addItem("Four");
              jComboBox4.addItem("Five");
              jComboBox4.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox4_actionPerformed(e);
              // jComboBox5
              jComboBox5.addItem("12/12/2004");
              jComboBox5.addItem("13/12/2004");
              jComboBox5.addItem("14/12/2004");
              jComboBox5.setEditable(true);
              jComboBox5.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox5_actionPerformed(e);
              // jComboBox6
              jComboBox6.addItem("12/11/2004");
              jComboBox6.addItem("13/11/2004");
              jComboBox6.addItem("14/11/2004");
              jComboBox6.setEditable(true);
              jComboBox6.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox6_actionPerformed(e);
              // jTable1
              jTable1.setModel(new DefaultTableModel(4, 4));
              // jScrollPane1
              jScrollPane1.setViewportView(jTable1);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 2,29,84,18);
              addComponent(contentPane, jLabel2, 201,33,76,18);
              addComponent(contentPane, jLabel3, 384,32,59,18);
              addComponent(contentPane, jLabel4, 2,77,85,18);
              addComponent(contentPane, jLabel5, 197,79,84,18);
              addComponent(contentPane, jLabel6, 384,80,60,18);
              addComponent(contentPane, jComboBox1, 85,32,100,22);
              addComponent(contentPane, jComboBox2, 276,32,100,22);
              addComponent(contentPane, jComboBox3, 419,30,100,22);
              addComponent(contentPane, jComboBox4, 88,76,100,22);
              addComponent(contentPane, jComboBox5, 276,79,100,22);
              addComponent(contentPane, jComboBox6, 421,78,100,22);
              addComponent(contentPane, jScrollPane1, 33,158,504,170);
              // newssa
              this.setTitle("SSA Service Scheduler");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(560, 485));
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jComboBox1_actionPerformed(ActionEvent e)
              int index = jComboBox1.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("Area Coimbatore Selected "); break;
                   case 1: System.out.println("Area Chennai selected"); break;
                   case 2: System.out.println("Mumbai being selected"); break;
                   case 3: System.out.println("New Delhi being selected"); break;
         private void jComboBox2_actionPerformed(ActionEvent e)
              int index = jComboBox2.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("North Zone Selcted "); break;
                   case 1: System.out.println("South Zone being selected"); break;
                   case 2: System.out.println("Central Zone being selected"); break;
                   case 3: System.out.println("Eastern Zone being selected"); break;
                   case 4: System.out.println("Western Zone being selected"); break;
         private void jComboBox3_actionPerformed(ActionEvent e)
              int index = jComboBox3.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("Microsoft Components being selected"); break;
                   case 1: System.out.println("Java Technologies being selected"); break;
                   case 2: System.out.println("ERP Tehnologies being selected"); break;
                   case 3: System.out.println("Other's selected"); break;
         private void jComboBox4_actionPerformed(ActionEvent e)
              int index = jComboBox4.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("One selected"); break;
                   case 1: System.out.println("Two selected"); break;
                   case 2: System.out.println("Three selected"); break;
                   case 3: System.out.println("Four selected"); break;
                   case 4: System.out.println("Five selected"); break;
         private void jComboBox5_actionPerformed(ActionEvent e)
              int index = jComboBox5.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("12/12/2004 being selected"); break;
                   case 1: System.out.println("13/12/2004 being selected"); break;
                   case 2: System.out.println("14/12/2004 being selected"); break;
         private void jComboBox6_actionPerformed(ActionEvent e)
              int index = jComboBox6.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("12/11/2004 being selected"); break;
                   case 1: System.out.println("13/11/2004 being selected"); break;
                   case 2: System.out.println("14/11/2004 being selected"); break;
         public static void main(String[] args)
              newssa ssa=new newssa();
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              //JFrame frame = new JFrame("SSA Service Scheduler");
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.setJMenuBar(ssa.menuBar);
    //frame.getContentPane( ).add(ssa.toolBar, BorderLayout.NORTH);
    //frame.getContentPane( ).add(ssa.pane, BorderLayout.CENTER);
    //frame.pack( );
    //frame.setVisible(true);
              try
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
    But as a O/P ,I am getting menu in a seperate windos and the rest of the combobox and jtable in a seperate window.Kindly help me to solve the application.
    VERY URGENT PLEASE..
    Thanks in advance
    with kind regds
    Satheesh.K

    But did u mean this as the next problem,Which I will come across..Yes, the second setVisible(true) seemed to be producing a smaller frame behind the main frame.
    And your JMenuBar is declared twice, but not sure if this will affect the code - haven't read it all.

  • L&F mapping JTable

    The look and feel values chosen for the JTable under windows do not feel right to me (albeit that I cannot find many examples of tables under windows).
    I am trying to provide some workarounds that follow what most people expect to happen but am a little unclear on what should happen on some key presses for the JTable in windows look and feel
    Space handling
    From one of the MS windows books it suggests that the space key is a selection key, thus when you press space a row in a table should be selected (and when you press again it should deselect the row?)
    The JList has functionality for the space key
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.
    Enter handling
    The enter key press is supposed to activate the default button
    or commit a text field under edit.
    F2 puts a field under edit
    q2) Should the enter key put an editable cell under edit (same mouse action as single or double click to edit)?
    q3) if not should the first enter key stop cell editing and a second press activate the default button, with only a single enter to activate default button if a cell is not under edit
    Escape handling
    The escape key will cancel editing of a cell that is under edit.
    q4) should the event not be passed on when editing has been cancelled so that dialogs with a canel button can be dismissed
    or
    q5) should the first escape cancel editing while the second escape will action the escape action of the window.
    Any links to "highly regarded" useability/look and feel sites would be helpful - sun does not appear to provide much on this subject
    I've read both their l&f and advanced l&f books and they just scratch the surface of look and feel without much realworld appliance to real gui issues.
    Might be useful to others: Some of the code that I was trying to create goes like....
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Event;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyEvent;
    import java.math.BigDecimal;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.CellEditor;
    import javax.swing.InputMap;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.JViewport;
    import javax.swing.KeyStroke;
    import javax.swing.ListSelectionModel;
    import javax.swing.RootPaneContainer;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.border.Border;
    import javax.swing.border.LineBorder;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    /** Provides utility methods for the JTable and JCSortableTable classes
    * @author  */
    public final class JTableUtil
          * Constructor for JCTableUtil.
         private JTableUtil()
              super();
         /** will resize the last column of a table to fill the gap
          * if the width of the columns is narrower than the width of the
          * table
          * @param table to act upon
         static void resizeLastColumn(final JTable table)
              TableColumn lastColumn = getLastVisibleColumn(table);
              if (lastColumn != null)
                   int gap = getLastColumnGap(table);
                   if (gap > 0)
                        int newLastColumnWidth = gap + lastColumn.getWidth();
                        lastColumn.setWidth(newLastColumnWidth);
                        lastColumn.setPreferredWidth(newLastColumnWidth);
                        redrawTable(table);
          * Determines if there is a gap between the last column in a table
          * and the border of the table.
          * Works if the table is drawn on the page or is in the
          * viewport of a scroll pane.
          * @param table to act upon
          * @return the gap in pixels between last column and table edge.
         static int getLastColumnGap(final JTable table)
              int widthTable = getTableWidth(table);
              int lastVisColIndex = getLastVisibleColumnIndex(table);
              TableColumnModel columnModel = table.getColumnModel();
              int widthColumns = columnModel.getTotalColumnWidth();
              final TableColumn lastColumn = columnModel.getColumn(lastVisColIndex);
              // gap is number of pixels from right hand edge of last column
              // to right hand edge of the table
              int gap = widthTable - widthColumns;
              return gap;
          * Determines the width of a table returning the table width if
          * table is painted onto a panel, but if the table is painted
          * into a scroll pane then it is the scroll pane viewport width that is returned
          * This is to capture that the width of the table may be less than the
          * width of the viewport - ie if there is a gap after the last column in a table.
          * @param table to act upon
          * @return the width of the table in pixels
         static int getTableWidth(final JTable table)
              int widthTable = table.getWidth();
              Object tableParent = table.getParent();
              JViewport tableViewPort = null;
              if (tableParent instanceof JViewport)
                   tableViewPort = (JViewport) tableParent;
                   widthTable = tableViewPort.getWidth();
              return widthTable;
         /** Cause the table to redraw wether table is painted on a panel
          * or in a scroll pane
          * @param table to act upon
         static void redrawTable(final JTable table)
              Component tableRegion = table;
              Component tableParent = table.getParent();
              if (tableParent instanceof JViewport)
                   tableRegion = tableParent;
              tableRegion.invalidate();
              tableRegion.validate();
         /** Determines the last (right most) column in a table with a width
          * greater than 0
          * @param table to act upon
          * @return index (0 based) of the last visible column.
         static int getLastVisibleColumnIndex(JTable table)
              TableColumnModel columnModel = table.getColumnModel();
              boolean found = false;
              int columnIndex = columnModel.getColumnCount();
              while (!found && columnIndex > 0)
                   columnIndex--;
                   if (columnModel.getColumn(columnIndex).getWidth() != 0)
                        found = true;
              return columnIndex;
         /** Determines the last (right most) column in a table with a width
          * greater than 0
          * @param table to act upon
          * @return TableColumn - the last visible column.
         static TableColumn getLastVisibleColumn(JTable table)
              TableColumnModel columnModel = table.getColumnModel();
              return columnModel.getColumn(getLastVisibleColumnIndex(table));
          * Add the currency symbol to a JCTable/JCListTable column header
          * e.g. 'Salary' becomes 'Salary (�)'
         public static void addCurrencySymbol(JTable table, Object columnKey)
              //@todo - update to work with JTable
              TableColumnModel columnModel = table.getTableHeader().getColumnModel();
              int columnIndex = columnModel.getColumnIndex(columnKey);
              TableColumn column = columnModel.getColumn(columnIndex);
              Object object = column.getHeaderValue();
              if (object instanceof JLabel)
                   JLabel columnLabel = (JLabel) object;
                   SlacCurrency.getInstance().addCurrencySymbol(columnLabel);
              else
                   // @todo log here ???
              // is above correct - need to get the JLabel rendered from the table
              // in the scroll pane?          
         /** Provides a sum of a column of BigDecimals
          * @param tableModel model containing column that you wish to sum
          * @param column the column that you wish to be summed, must contain numeric values and not strings
         public static BigDecimal calculateTotalForColumn(final TableModel tableModel, final int column)
              int numRows = tableModel.getRowCount();
              BigDecimal total = new BigDecimal("0");
              for (int row = 0; row < numRows; row++)
                   Object value = tableModel.getValueAt(row, column);
                   if (value instanceof BigDecimal)
                        BigDecimal decimalValue = (BigDecimal) value;
                        total = total.add(decimalValue);
                   else
                        //Logger.logGeneralFailure("", ErrorCodes.GUI_ERROR, this);
              return total;
          * Provides the swing setting JTable.AUTO_RESIZE_OFF.
          * <p>
          * In this situation if the width of the columns is smaller than the width
          * of the table then there will be a gap after the last column.
          * <p>
          * This method will add a ComponentListener to the table and or
          * scroll pane viewport so that there is no gap after the last column.
          * @param table to act upon
         public static void configureAutoResizeOff(final JTable table)
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              Component tableParent = table.getParent();
              JViewport tableViewPort = null;
              ComponentAdapter gapFiller = new ComponentAdapter()
                   public void componentResized(ComponentEvent e)
                        super.componentResized(e);
                        JTableUtil.resizeLastColumn(table);
              table.addComponentListener(gapFiller);
              if (tableParent instanceof JViewport)
                   tableViewPort = (JViewport) tableParent;
                   tableViewPort.addComponentListener(gapFiller);
         /** Method provides fixes to provide standard handling for keyboard and mouse usage
          * <ul>
          *    <li> spacebar - selection handling of rows that have focus emphasis see fixSpacebarHandling()
          *    <li> initial focus handling - table should give visual feedback when gaining focus
          *    <li>
          * </ul>
          * @param table - the table to add standards handling to
         public static void setupKeyboardMouseHandling(JTable table)
              fixTableGainsFocusOnFirstEntry(table);
              fixSpacebarHandling(table);
              fixCtrlSpacebarHandling(table);
              fixShiftSpacebarHandling(table);
              fixCtrlUpDownHandling(table);
              fixFocusHighlight();
              fixEscEnter(table);
         /** Add fixes to the look and feel handling for a JTable
          * Enter on a table will do different things depending on the mode of the table
          * <p>
          * if a cell is being edited then
          * Enter will do what normally happens to a field under edit - ie stop the editing and commit
          * Escape will cancel the editing
          * <p>
          * if a cell is not under edit then
          * Enter will activate the default button
          * Escape will activate the default cancel button (see FrameUtil.addEscapeKeyAction())
         static void fixEscEnter(final JTable table)
              final RootPaneContainer root = (RootPaneContainer)SwingUtilities.windowForComponent(table);
              final String escapeKey = "escapeAction";
              Action escapeAction = new AbstractAction(escapeKey)
                   public void actionPerformed(ActionEvent actionEvent)
                        if(table.isEditing())
                             CellEditor editor = table.getCellEditor(table.getEditingRow(), table.getEditingColumn());
                             editor.cancelCellEditing();
                        else
                             Window parentWindow = SwingUtilities.windowForComponent(table);
                             Action windowEscapeAction = FrameUtil.getEscapeKeyAction(root);
                             windowEscapeAction.actionPerformed(actionEvent);
              final String enterKey = "enterAction";
              Action enterAction = new AbstractAction(enterKey)
                   public void actionPerformed(ActionEvent actionEvent)
                        if(table.isEditing())
                             CellEditor editor = table.getCellEditor(table.getEditingRow(), table.getEditingColumn());
                             editor.stopCellEditing();
                        else
                             root.getRootPane().getDefaultButton().doClick();
              InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              table.getActionMap().put(escapeKey, escapeAction);
              table.getActionMap().put(enterKey, enterAction);
              inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), escapeKey);          
              inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enterKey);          
         static void fixFocusHighlight()
              Border focusCellHighlightBorder = new DashedLineBorder(Color.BLACK);
              UIManager.put("Table.focusCellHighlightBorder", focusCellHighlightBorder);
         /** If you do not setup a table to have a row selected then there is a bug where for example
          * you use an accelerator key to put focus in the table and you get no visual feedback that
          * the table has focus - ie no focus emphasis - dashed box
          * @param table - the table to fix
         static void fixTableGainsFocusOnFirstEntry(JTable table)
              // for first time tabbing to table make sure that first cell has focus
              // don't seem to need this fix under windows XP
              table.getSelectionModel().removeSelectionInterval(0, 0);
         /** fix spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * spacebar - select the current row without deselecting any others
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixSpacebarHandling(JTable table)
              KeyStroke ksSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true);
              final String ACTION_SPACE = "SPACE";
              Action spaceAction = new AbstractAction(ACTION_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        selectModel.addSelectionInterval(currentRowIndex, currentRowIndex);
              table.getInputMap().put(ksSpace, ACTION_SPACE);
              table.getActionMap().put(ACTION_SPACE, spaceAction);
         /** fix ctrl + spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * ctrl + spacebar - toggle selection on the current row without deselecting any others
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixCtrlSpacebarHandling(JTable table)
              KeyStroke ksCtrlSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.CTRL_MASK, true);
              final String ACTION_CTRL_SPACE = "CTRLSPACE";
              Action ctrlSpaceAction = new AbstractAction(ACTION_CTRL_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        boolean isCurrentRowSelected = selectModel.isSelectedIndex(currentRowIndex);
                        if (isCurrentRowSelected)
                             selectModel.removeSelectionInterval(currentRowIndex, currentRowIndex);
                        else
                             selectModel.addSelectionInterval(currentRowIndex, currentRowIndex);
              table.getInputMap().put(ksCtrlSpace, ACTION_CTRL_SPACE);
              table.getActionMap().put(ACTION_CTRL_SPACE, ctrlSpaceAction);
         /** fix shift + spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * shift + spacebar - extend the selection from the anchor to the lead index.
          * this might still be a bit funny in java 1.4.2 and code may need to be changed slightly
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixShiftSpacebarHandling(JTable table)
              KeyStroke ksShiftSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.SHIFT_MASK, true);
              final String ACTION_SHIFT_SPACE = "SHIFTSPACE";
              Action shiftSpaceAction = new AbstractAction(ACTION_SHIFT_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        int startRowIndex = selectModel.getLeadSelectionIndex();
                        selectModel.setSelectionInterval(startRowIndex, currentRowIndex);
              table.getInputMap().put(ksShiftSpace, ACTION_SHIFT_SPACE);
              table.getActionMap().put(ACTION_SHIFT_SPACE, shiftSpaceAction);
         /** fix ctrl + down or up handling - move focus emphasis up or down accordingly
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixCtrlUpDownHandling(JTable table)
              final String ACTION_UP = "CTRLUP";
              KeyStroke ksCtrlUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.CTRL_MASK, true);
              KeyStroke ksCtrlDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.CTRL_MASK, true);
              Action ctrlUpAction = new CtrlUpDownAction(ACTION_UP, true);
              final String ACTION_DOWN = "CTRLDOWN";
              Action ctrlDownAction = new CtrlUpDownAction(ACTION_DOWN, false);
              table.getInputMap().put(ksCtrlUp, ACTION_UP);
              table.getActionMap().put(ACTION_UP, ctrlUpAction);
              table.getInputMap().put(ksCtrlDown, ACTION_DOWN);
              table.getActionMap().put(ACTION_DOWN, ctrlDownAction);
    * Action for moving focus emphasis up or down
    class CtrlUpDownAction extends AbstractAction
         private boolean m_isUp = true;
         /** Ctor controlling direction of focus emphasis
          * @param name of the action
          * @param isUp - true if dirction of action is up, else false
         public CtrlUpDownAction(String name, boolean isUp)
              super(name);
              m_isUp = isUp;
         /** Moves the focus emphasis
          * @param actionEvent - see javax.swing.AbstractAction class for details
         public void actionPerformed(ActionEvent actionEvent)
              JTable table = (JTable) actionEvent.getSource();
              ListSelectionModel selectModel = table.getSelectionModel();
              int nextRowIndex =
                   getNextRowIndex(table.getRowCount(), selectModel.getAnchorSelectionIndex());
              if (selectModel.isSelectedIndex(nextRowIndex))
                   selectModel.addSelectionInterval(nextRowIndex, nextRowIndex);
              else
                   selectModel.removeSelectionInterval(nextRowIndex, nextRowIndex);
         /** Gets the index of the next row depending on direction up or down
          * @param rowCount - number of rows in the table
          * @param currentRowIndex - index of the row that has focus emphasis
          * @return the index of the next row
         private int getNextRowIndex(int rowCount, int currentRowIndex)
              int nextRowIndex = -1;
              if (m_isUp && currentRowIndex > 0)
                   // emphasis moving up one row
                   nextRowIndex = currentRowIndex - 1;
              else if (!m_isUp && currentRowIndex < (rowCount - 1))
                   // emphasis moving down one row
                   nextRowIndex = currentRowIndex + 1;
              return nextRowIndex;
    /** Draws a dashed line (well more of a dotted line)
    * Used for eg drawing focus emphasis rectangle
    * Class draws a rectangle of chosen colour overlaid with a dashed white line.
    class DashedLineBorder extends LineBorder
         private BasicStroke m_lineStroke = new BasicStroke();
         private BasicStroke m_dashStroke =
              new BasicStroke(
                   m_lineStroke.getLineWidth(),
                   BasicStroke.CAP_BUTT,//m_lineStroke.getEndCap(),
                   m_lineStroke.getLineJoin(),
                   m_lineStroke.getMiterLimit(),
                   new float[] { 1,1,1 },
                   0);
          * Constructor for DashedLineBorder.
          * @param color
         public DashedLineBorder(Color color)
              super(color);
          * Constructor for DashedLineBorder.
          * @param color
          * @param thickness
         public DashedLineBorder(Color color, int thickness)
              super(color, thickness);
          * Constructor for DashedLineBorder.
          * @param color
          * @param thickness
          * @param roundedCorners
         public DashedLineBorder(Color color, int thickness, boolean roundedCorners)
              super(color, thickness, roundedCorners);
         /** Similar to LineBorder's method but draws a line in the chosen colour
          * before drawing a white dashed line on top of it
          * @see javax.swing.border.Border#paintBorder(Component, Graphics, int, int, int, int)
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
              Color oldColor = g.getColor();
              int i;
              Graphics2D g2 = (Graphics2D) g;
              g2.setStroke(m_lineStroke);
              g.setColor(lineColor);
              drawRect(g, x, y, width, height);
              g2.setStroke(m_dashStroke);
              g.setColor(Color.WHITE);
              drawRect(g, x, y, width, height);
              g.setColor(oldColor);
          * @see javax.swing.border.Border#paintBorder(Component, Graphics, int, int, int, int)
         private void drawRect(Graphics g, int x, int y, int width, int height)
              // extracted from Java LineBorder.paintBorder
              int i;
              /// PENDING(klobad) How/should do we support Roundtangles?
              for (i = 0; i < thickness; i++)
                   if (!roundedCorners)
                        g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1);
                   else
                        g.drawRoundRect(
                             x + i,
                             y + i,
                             width - i - i - 1,
                             height - i - i - 1,
                             thickness,
                             thickness);
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.image.ImageProducer;
    import java.io.IOException;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;
    import javax.swing.RootPaneContainer;
    * Provides static utility methods for JFrames.
    public final class FrameUtil {
        * No instances allowed. Just use the static methods.
       private FrameUtil() {
          super();
        * Sets the button that is "activated" when the escape key is used.
        * A bit like
        * SwingUtilities.getRootPane(this).setDefaultButton(myButton);
        * @param jFrame The JFrame or JDialog for which the escape key button should be set.
        * @param button The button which should be clicked automatically when the escape key is pressed.
       public static void setEscapeKeyButton(final RootPaneContainer jFrame, final JButton button) {
          addEscapeKeyAction(jFrame, new AbstractAction() {
             public void actionPerformed(final ActionEvent evt) {
                button.doClick();
        * Adds an action to the jframe's  action map that is triggered by the Escape key.
        * (If you just want to simulate a button click when the escape key is pressed then
        * use setEscapeKeyButton.)
        * A bit like
        * SwingUtilities.getRootPane(this).setDefaultButton(myButton);
        * @param jFrame The JFrame or JDialog for which the escape key action should be set.
        * @param action The action that is executred when the escape key us pressed,
       public static void addEscapeKeyAction(final RootPaneContainer jFrame, final Action action) {
          String actionKey = "escapeAction";
          KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
          // using getRootPane rather than getContentPane, content pane doesn't work in all
          // scenarios
          InputMap inputMap = (jFrame.getRootPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          inputMap.put(escape, actionKey);
          ActionMap actionMap = (jFrame.getRootPane()).getActionMap();
          actionMap.put(actionKey, action);
        * Finds the escape action for the given frame or dialog if one was added
        * @param jFrame The JFrame or JDialog for which the escape key action should be set.
       public static Action getEscapeKeyAction(final RootPaneContainer jFrame)
          InputMap inputMap = (jFrame.getRootPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
          ActionMap actionMap = (jFrame.getRootPane()).getActionMap();
          Object actionKey = inputMap.get(escapeKeyStroke);
          Action escapeAction = null;
          if(actionKey != null)
             escapeAction = actionMap.get(actionKey);
          return escapeAction;

    From one of the MS windows books.....Going by the books, eh?
    Well, apparently MS doesn't do so with Excel... Pressing space will simply trigger an edit!
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.A bug, no... a feature, maybe. Anyway, JTable provides most of the features needed for creating a table -- it's far from perfect..... adding support for CTRL+SPACE and SHIFT+SPACE is not all that hard to do.
    q2) Should the enter key put an editable cell under edit and
    q3) if not should the first enter key stop cell editing and a second press activate the default buttonIMHO, a good answer to your question can be found by running MS Excel and see how it's done.
    The escape key will cancel editing of a cell that is under edit.and q4, q5
    It should, as in Excel. But then, in Lotus 1-2-3, first escape will clear the edit buffer (unless it's empty) and the second escape will cancel editing. Who'is more programmatically correct (I don't know)?
    ;o)
    V.V.

  • Tab and back-tab out of a JTable

    Hi There,
    I have been working for some time on improving the default behaviour of the tab key within editable JTables. It largely works as required now, but I'm stuck on getting back-tab to leave the table if on row 0, col 0. I register tab and back-tab action in the table's ActionMap that looks like this:     
         class TabAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   if (getRowCount() > 0) {
                        int row = getSelectedRow();
                        int column = getSelectedColumn();
                        if (row < 0 || column < 0) {
                             row = 0;
                             column = 0;
                        do {
                             if (++column >= getColumnCount()) {
                                  row++;
                                  column = 0;
                        } while (row < getRowCount() && ! isCellTabbable(row, column));
                        if (row < getRowCount()) {
                             changeSelection(row, column, false, false);
                        } else {
                             clearSelection();
                             transferFocus();
                   } else {
                        transferFocus();
         class BackTabAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   if (getRowCount() > 0) {
                        int row = getSelectedRow();
                        int column = getSelectedColumn();
                        if (row < 0 || column < 0) {
                             row = getRowCount() - 1;
                             column = getColumnCount() - 1;
                        do {
                             if (--column < 0) {
                                  row--;
                                  column = getColumnCount() - 1;
                        } while (row >= 0 && ! isCellTabbable(row, column));
                        if (row >= 0) {
                             changeSelection(row, column, false, false);
                        } else {
                             clearSelection();
                             transferFocusBackward();
                             KeyboardFocusManager fm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                                // fm.upFocusCycle(BTTTable_Editable.this);                         
                             // fm.focusPreviousComponent(BTTTable_Editable.this);
                   } else {     
                        // transferFocusBackward();
                        // KeyboardFocusManager fm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                           // fm.upFocusCycle(BTTTable_Editable.this);                         
                        // fm.focusPreviousComponent(BTTTable_Editable.this);
         }transferFocus() to go to the next screen component works fine - as long as I callsetFocusTraversalPolicyProvider(true); when I create the JTable.
    But the backward traversal just doesn't work - instead it does nothing the first time you press back-tab on row 0 col 0, then if you press it again, focus goes onto the last row/col of the table.
    As an alternative, I thought maybe I could call the Ctrl-back-tab action, but I can't find that registered in the action map - can anyone tell me how ctrl-back-tab is called and whether I can call that code directly?
    Any ideas?
    Thanks,
    Tim

    Where's the rest of your code? What good does posting
    the Actions do if we can't execute your code and see
    how you've installed the Actions on the table? Who
    knows where the mistake is. It may be in the posted
    code or it may be in some other code.Well I assume the Action is registered okay because back-tab within the table works fine, and in fact using a debugger I can see that the focus request code (transferFocusBackward) is being called at the right time. I followed it into that code and it appears that it is picking up the tableCellEditor as the "previous" component which is "why" it isn't working right - not that that helps me to fix it.
    Anyway, just to confirm, here is a complete standalone testcase:import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.ActionEvent;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    * <br>
    * <br>
    * Created on 14/11/2005 by Tim Ryan
    public class TabTable extends JTable implements FocusListener {
         protected KeyStroke TAB = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
         protected KeyStroke BACK_TAB = KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
                   InputEvent.SHIFT_DOWN_MASK);
         protected KeyStroke LEFT_ARROW = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
         protected KeyStroke RIGHT_ARROW = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
         public TabTable(Object[][] rowData, Object[] columnNames) {
              super(rowData, columnNames);
              initialise();
         public TabTable() {
              super();
              initialise();
         private void initialise() {
              addFocusListener(this);
              InputMap inMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              ActionMap actionMap = getActionMap();
              inMap.put(LEFT_ARROW, "None");
              inMap.put(RIGHT_ARROW, "None");
              actionMap.put(inMap.get(TAB), new TabAction());
              actionMap.put(inMap.get(BACK_TAB), new BackTabAction());
              setCellSelectionEnabled(true);
              putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              setFocusTraversalPolicyProvider(true);
         public void focusGained(FocusEvent e) {
              if (getRowCount() > 0 && getSelectedRow() < 0) {
                   editCellAt(0, 0);
                   getEditorComponent().requestFocusInWindow();
         public void focusLost(FocusEvent e) {
         public void changeSelection(int row, int column, boolean toggle, boolean extend) {
              super.changeSelection(row, column, toggle, false);
              if (editCellAt(row, column)) {
                   getEditorComponent().requestFocusInWindow();
          * This class handles the back-tab operation on the table.
          * It repeatedly steps the selection backwards until the focus
          * ends up on a cell that is allowable (see <code>isCellTabbable()</code>).
          * If already at the end of the table then focus is transferred out
          * to the previous component on the screen.
         class BackTabAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   if (getRowCount() > 0) {
                        int row = getSelectedRow();
                        int column = getSelectedColumn();
                        if (row < 0 || column < 0) {
                             row = getRowCount() - 1;
                             column = getColumnCount() - 1;
                        do {
                             if (--column < 0) {
                                  row--;
                                  column = getColumnCount() - 1;
                        } while (row >= 0 && ! isCellTabbable(row, column));
                        if (row >= 0) {
                             changeSelection(row, column, false, false);
                        } else {
                             clearSelection();
                             // transferFocusBackward();
                             KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
                   } else {
                        // transferFocusBackward();
                        KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
          * This class handles the tab operation on the table.
          * It repeatedly steps the selection forwards until the focus ends
          * up on a cell that is allowable (see <code>isCellTabbable()</code>).
          * If already at the end of the table then focus is transferred out
          * to the next component on the screen.
         class TabAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   if (getRowCount() > 0) {
                        int row = getSelectedRow();
                        int column = getSelectedColumn();
                        if (row < 0 || column < 0) {
                             row = 0;
                             column = 0;
                        do {
                             if (++column >= getColumnCount()) {
                                  row++;
                                  column = 0;
                        } while (row < getRowCount() && ! isCellTabbable(row, column));
                        if (row < getRowCount()) {
                             changeSelection(row, column, false, false);
                        } else {
                             clearSelection();
                             transferFocus();
                   } else {
                        transferFocus();
          * Some cells can be tabbed to, but are not actually editable.
          * @param row
          * @param column
          * @return
         private boolean isCellTabbable(int row, int column) {
              return (column % 2 == 0);
         public boolean isCellEditable(int row, int column) {
              return (column == 1 || column == 3);
          * @param args
         public static void main(String[] args) {
              JFrame frame = new JFrame("Tables test");
              frame.setName("TablesTest");
              frame.setSize(600, 400);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel panelMain = new JPanel(new GridBagLayout());
              frame.add(panelMain);
              Object[][] tableData = new Object[2][6];
              Object[] columnHeadings = new Object[] {"H0", "H1", "H2", "H3", "H4", "H5"};
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.anchor = GridBagConstraints.NORTH;
              gbc.insets = new Insets(10, 10, 10, 10);
              JTextField field1 = new JTextField("left", 8);
              field1.setName("left");
              panelMain.add(field1, gbc);
              Dimension tableSize = new Dimension(300, 300);
              BTTTable table3 = new BTTTable_Editable(tableData, columnHeadings);
              table3.setName("Editable");
              JScrollPane scroll3 = new JScrollPane(table3);
              scroll3.setPreferredSize(tableSize);
              panelMain.add(scroll3, gbc);
              JTextField field2 = new JTextField("right", 8);
              field2.setName("right");
              gbc.gridwidth = GridBagConstraints.REMAINDER;
              panelMain.add(field2, gbc);
              frame.setVisible(true);
    }I thought it might be the focusGained() code, but commenting that out makes no difference.
    And here is the code I would use to go to the
    previous component:
    KeyboardFocusManager.getCurrentKeyboardFocusManager().
    focusPreviousComponent();I tried that too, as you can see from my original post. It gives the same answer.
    So the big question is why does the FocusManager think that the "previous" field to the table is an editor component within the table?
    Regards,
    Tim

  • JTable has two mouselistener?

    Hi,
    I have a JTable where one column is rendered by JCombobox and other column by JCheckbox. want to have this kind of functionality:
    I clicks several rows while ctrl is pressed (basic functionality) but when I click already selected row it becomes deselected (that is not what I want). So I wrote a mouse adapter to take care of this
    MouseAdapter mouse = new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            int ctrlPressed = e.getModifiers()&InputEvent.CTRL_MASK;
            int clickedRow = table.rowAtPoint(e.getPoint());
            //no row
            if( clickedRow == -1 )
                return;
            // ctrl pressed and row clicked so select it
            if (e.getClickCount() == 1 && ctrlPressed == 2 )
                System.out.println("Was already selected "+table.isRowSelected( clickedRow ));
                if( !table.isRowSelected( clickedRow ) )
                    table.addRowSelectionInterval( clickedRow, clickedRow );
                    System.out.println("Row "+clickedRow+" selected");
            if (e.getClickCount() == 2 && ctrlPressed == 2 )
                if( table.isRowSelected( clickedRow ) )
                    System.out.println("Clicked row deselected");
                    table.removeRowSelectionInterval( clickedRow, clickedRow );
    };I add that to my table but when I click deselected row holding ctrl "Was already selected true" is printed. So some other mouselistener noticed before my listener that clicking and selected the row :o
    I tried to remove all mouselisteners with these lines and results was not what I was hoping for :)
    MouseListener[] listenerit = (MouseListener[])(table.getListeners(MouseListener.class));
    System.out.println(listenerit.length+" mouselisteners");
    for(int uu = 0; uu < listenerit.length; uu++)
        System.out.println("This will be removed "+listenerit[uu]);
        table.removeMouseListener(listenerit[uu]);
    System.out.println("There should be nothing: "+table.getMouseListeners());What Im doing wrong?

    So, did my first suggestion work?
    Is there some way to handle mouseclicking with those custom renders? Sure, there is always something you can do but you'll have to tell me more about what happens to the combo or check box when you do what you did with the mouse --e.g., did it go into an edit mode (if so, you should really make the cell editable on two mouse clicks).  Without more info, all I can suggest is for you to look into the JTable's editCellAt method, check to see if editing is being triggered by a mouse event, if so, do something about it there.  Let me emphasize again that I'm suggesting something that I know would work but is considered unconventional or even inappropriate by some experts.
    ;o)
    V.V.

  • Cell L&F of JTable

    hi ,
    I have a JTable contructed from DeaultTableModel and
    i have created a TableCellEditor which has a custom DefaultCellRenderer as its argument and
    added to the table
    THE PROBLEM is :
    When i edit in the table cell , the editable area of the cell becomes smaller compared to the area without a TableCellEditor, how can i change it ?
    and i want to change the border of the celll which is selected and its color
    Any Help ? Please.
    thanks.

    From one of the MS windows books.....Going by the books, eh?
    Well, apparently MS doesn't do so with Excel... Pressing space will simply trigger an edit!
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.A bug, no... a feature, maybe. Anyway, JTable provides most of the features needed for creating a table -- it's far from perfect..... adding support for CTRL+SPACE and SHIFT+SPACE is not all that hard to do.
    q2) Should the enter key put an editable cell under edit and
    q3) if not should the first enter key stop cell editing and a second press activate the default buttonIMHO, a good answer to your question can be found by running MS Excel and see how it's done.
    The escape key will cancel editing of a cell that is under edit.and q4, q5
    It should, as in Excel. But then, in Lotus 1-2-3, first escape will clear the edit buffer (unless it's empty) and the second escape will cancel editing. Who'is more programmatically correct (I don't know)?
    ;o)
    V.V.

  • Jtable and ctrl_down_mask

    hi,
    hope someone will give me some pointers to the following problem that i have.
    i have a jtable that has 2 editable string columns.
    i have a <keypress event> that handles <ctrl_down> and <space> keys when pressed simultaneously.
    What i found was that when i tab into any of the columns initinially (field is selected when in focus), the <ctrl><space> event is picked up.
    But, if i were to do some edit in the column and then press <ctrl><space>, the event does not get picked up.
    Why ???
    Thanks for any help
    Tony

    Well first you should extend JTextField to support
    the functionality that you require. Its easier to
    test a simply text field then it is an editor in a
    table. Once this components works you would then
    create a new editor for the table using this
    component. See the DefaultCellEditor API. Then you
    would add this editor to the table.
    did this already ... know how it works on a JTextField.
    I would use KeyBindings to handle the Ctrl+Space
    KeyStroke. Read the Swing tutorial on [url
    http://java.sun.com/docs/books/tutorial/uiswing/misc/k
    eybinding.html]How to Use Key Bindings for moreinformation.
    Would i be right to say that Keybinding for jtable can be used together with a DefaultCellEditor ?
    Thanks for your info ... will read that article :)

  • Implementing Copy and Paste on JTable cells.

    Hi to all,
    Can anybody suggest as how to impose copy and paste with Ctrl-C and Ctrl-V by using keys on JTable cells.
    Thanks in advance.
    khiz_eng

    First, add a key listener to the table itself (most likely in the constructor for your table), like so:
      addKeyListener(new KeyListener()
        public void keyTyped(KeyEvent e) {}
        public void keyReleased(KeyEvent e) {}
        public void keyPressed(KeyEvent e)
          tableKeyPressed(e);
      });Next, add the code for the "tableKeyPressed" method. Here's a skeleton you can use as a starting point (obviously, the exact code to copy and paste will depend on the nature of the data you are trying to transfer).
      protected void tableKeyPressed(KeyEvent e)
        // Get selected cols and rows:
        int[] selectedRows = getSelectedRows();
        int[] selectedCols = getSelectedColumns();
        // A "copy" is signified by either ctrl+c, meta+c, or the "copy" button on a Sun keyboard.
        // Unfortunately, Java does not abstract this for us, so we have to test each of these conditions:
        if ((e.getKeyCode() == KeyEvent.VK_COPY) ||
            ((e.getKeyCode() == KeyEvent.VK_C) && e.isControlDown()) ||
            ((e.getKeyCode() == KeyEvent.VK_C) && e.isMetaDown()))
          // Grab the cell(s) that are currently selected by using the selectedRows
          // and selectedCols arrays from above.  Then copy this data to the clipboard.
        // A "paste" is signified by either ctrl+v, meta+v, or the "paste" button on a Sun keyboard.
        // Again, Java does not abstract this for us, so each condition must be tested:
        else if ((e.getKeyCode() == KeyEvent.VK_PASTE) ||
             ((e.getKeyCode() == KeyEvent.VK_V) && e.isControlDown()) ||
             ((e.getKeyCode() == KeyEvent.VK_V) && e.isMetaDown()))
          // Make sure there is valid data in the clipboard.
          // If so, paste it into the selected cell(s).
      }(By the way, this code assumes that you are running on a Sun machine with a Sun keyboard. If you are only targeting windows boxes, then the only key press you really need to worry about is CTRL+C. There's no harm in leaving the other keys in, though.
    Hope that helps,
    Steve

Maybe you are looking for

  • ACNS 5.5 / Troubleshooting bad quality VIDEO (MMS-over-http)

    Hello community, For an unexplanable reason I have to deal with an ACNS problem which is not my domain at all ! ACNS 5.5.15 is on a WAE-512-K9 working with CDM. Please can someone advice me on how to start the basic troubleshooting steps on the follo

  • Impossible to use a Vault on any disk

    Hello all! I'm very deprived of hope to solve this kind of problem. 24 hrs ago, Aperture begun to show error message when I'm trying to update the Vault. Ok, It wasn't the first time. So, I've deleted the Vault for recreate a new one. But, with my su

  • Video wont play its all jumbeld letters and figures!

    so when i go to watch webcasts they dont play. its a page of letters and figures that dont make sense. then i tried to do the audio and it was the same. but youtube works so im confused someone please help me!

  • How to lock all transactions documents?

    hi experts, for example, once I have done all reports in January, I don't want anybody to add, change or delete any marketing documents includ A/R, A/P, production order, inventory transfer....in January. is there any fast way to lock a period of SAP

  • Mojarra JSF 2.1.x servlet requirement or dependency

    Can anyone tell me how to reconcile this information? http://javaserverfaces.java.net/nonav/rlnotes/2.1.0/releasenotes.html says that JSF (Mojarra) 2.1 series depends on a servlet 3.0 container. But http://download.java.net/maven/2/com/sun/faces/jsf-