JMenuItem accelerator on JTable

Hi,
I have a popup menu on a JTable. I have this code (executed at JTable show time):
m_oPopupMenu = new JPopupMenu();
JMenuItem oMenuItem = new JMenuItem("upd row");
oMenuItem.addActionListener(new RowMouseAdapter.UpdateRowEvent());
oMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,
ActionEvent.CTRL_MASK));
oMenuItem.setMnemonic(KeyEvent.VK_M);
m_oPopupMenu.add(oMenuItem);
I also have a MouseAdapter which correcly show the pop-up menu and items. But accelerator-key doesn't works.
Any idea?
TIA
Roberto Colmegna

here is the code (it works correctly right mouse click, but it doesn't works
with CTRL+O when cursor is over jTable1).
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class JFrame extends javax.swing.JFrame {
  boolean m_bMove = false;
  /** Creates new form JFrame */
  public JFrame () {
    initComponents ();
  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
  private void initComponents() {
    jTable1 = new javax.swing.JTable();
    myInitJTable1();
    getContentPane().setLayout(null);
    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        exitForm(evt);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {
        {null, null, null, null},
        {null, null, null, null},
        {null, null, null, null},
        {null, null, null, null}
      new String [] {
        "Title 1", "Title 2", "Title 3", "Title 4"
    getContentPane().add(jTable1);
    jTable1.setBounds(30, 90, 300, 64);
    pack();
  void myInitJTable1() {
      oPopupMenu = new JPopupMenu();
      JMenuItem oMenuItem = new JMenuItem("item");      
      oMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed (ActionEvent actionEvent) {
          System.out.println("--------XXXXXXXXXXXXXXX-------");
      oMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
        InputEvent.CTRL_MASK));
      oMenuItem.setMnemonic(KeyEvent.VK_O);
      oPopupMenu.add(oMenuItem);
      jTable1.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
          if(e.getButton () != e.BUTTON3) // right mouse button
            return;
          oPopupMenu.show(e.getComponent(), e.getX(), e.getY());
  /** Exit the Application */
  private void exitForm (java.awt.event.WindowEvent evt) {
    System.exit (0);
   * @param args the command line arguments
  public static void main (String args[]) {
    new JFrame ().show ();
  // Variables declaration - do not modify
  private javax.swing.JTable jTable1;
  // End of variables declaration
  private JPopupMenu oPopupMenu;
}TIA
Roberto Colmegna

Similar Messages

  • How to set JMenu/JMenuItem.accelerator property in Inspector

    How do you set an accelerator key through the accelerator
    property in the inspector for a JMenu or JMenuItem object? The
    list box contains one item, "<none>". Does one have to create
    some special keyboard shotcut objects that then will be added to
    the list?
    Where can one find documentation for the Swing classes, as far
    as I can see it's not included?
    Thanks.
    Finn Ellebaek Nielsen
    ChangeGroup ApS
    null

    I know how to do it in the code but it must be possible to do it
    from the Inspector since the property is listed there?
    Thanks.
    Finn
    JDeveloper Team (guest) wrote:
    : Finn,
    : I would check the Swing documentation available from the
    Javasoft
    : website for more information on these controls.
    : -L
    : Finn Ellebaek Nielsen (guest) wrote:
    : : How do you set an accelerator key through the accelerator
    : : property in the inspector for a JMenu or JMenuItem object?
    The
    : : list box contains one item, "<none>". Does one have to
    create
    : : some special keyboard shotcut objects that then will be
    added
    : to
    : : the list?
    : : Where can one find documentation for the Swing classes, as
    far
    : : as I can see it's not included?
    : : Thanks.
    : : Finn Ellebaek Nielsen
    : : ChangeGroup ApS
    null

  • JTextPane key bindings override JMenuItem accelerators

    hi all,
    I have a JTextPane subclass, sitting on a JPanel, sitting on a JFrame which has a JMenu attached. One of my menu commands has an accelerator PgDn... I am trying to disable the PgDn default behaviour in the JTextPane so that the keystroke then "falls through" and activates the menu item...
    NOTHING WORKS! Using Keymap and InputMap, have tried "remove", have tried setting the action to "none", etc... it is simple enough to stop PgDn default behaviour in JTextPane, and if I looked into it I could probably explicitly put the action of the menu item in the action map of the JTextPane... but I want to cancel the key binding so that the system looks elsewhere and finds the JMenuItem accelerator...! is this too much to ask??
    I am a big user of hotkeys in apps and I want to understand more about all this stuff... how come there are no fewer than 4 generations of InputMap associated with a single JTextPane, for example?
    Thanks
    Mike

    Hi,
    Thanks for this... very useful clue... In fact JTextPane itself does handle the PgDn key binding, causing the insertion point to move to the end of the multiline text.
    But I followed your suggestion, finding that it is, perhaps unsurprisingly, the vertical Jscrollbar which (otherwise) handles PgDn, causing a scroll down... and a little experimenting finds that this scrollbar is created not on the fly, but once for each JScrollPane...
    So I also remove the vertical JScrollBar's key binding for "PgDn" (listing the bindings before and after removal) and... it STILL refuses to work!
    So I thought: aha, maybe by some anomaly you have a PgDn binding in the horizontal scrollbar... turns out it seems to share the same input map (actually the parent of the JScrollBar's getInputMap()) as the vertical scrollbar... so no, this doesn't work either!
    I also checked out scrollpane's viewport... 0 keys in getInputMap() and the latter does not have parent...
    Your suggestion looks like a very promising avenue... somewhere there is something trapping this key, but what? NB when a JButton, for example, is placed on the JPanel, and focus is on the button, PgDn activates the JMenuItem accelerator as expected, so it's obviously sthg to do with the complexity of having a JScrollPane combination
    Anything else you can suggest? I really don't want to have to explicitly put an action in the JTextPane... I like to understand, and I like elegant solutions...
    Thanks,
    Mike

  • JTable overrides the accelerator on JMenuItem

    I have a JFrame which has a JMenu. Some of the menu items have accelerators associated with them. And the JFrame has a JTable. The accelerators are working only when the focus is not in the JTable. But they are not working when the focus is in JTable. For example, when I selected a row in the table and press the accelerator key, it is not working. Can somebody provide me the solution for it?

    Here is the code:
    public class SwingEventPropagationTest {
         private static final int shortcutKeyAsciiValue = 65; //A
         public static void main(String[] args) {
              final JFrame frame = new JFrame();
              JMenuBar menuBar = new JMenuBar();
              JMenu menu = new JMenu("Edit");
              JMenuItem menuItem = new JMenuItem("Test");
              KeyStroke ctrlAKeyStroke = KeyStroke.getKeyStroke(shortcutKeyAsciiValue, InputEvent.CTRL_MASK);
              menuItem.setAccelerator(ctrlAKeyStroke);
              menuItem.addActionListener(new SelectAllAction());
              menu.add(menuItem);
              menuBar.add(menu);
              frame.setJMenuBar(menuBar);
              final JTable table = new JTable(new NumericTableModel());
              //Remove Keybindings from table
              table.getInputMap().put(ctrlAKeyStroke, "doNothing");
              table.getActionMap().put("doNothing", new DoNothingAction());
              JScrollPane scrollpane = new JScrollPane(table);
              JPanel panel = new JPanel();
              panel.add(new JButton("test"));
              panel.add(scrollpane);
              frame.getContentPane().add(panel);
              frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              frame.setSize(500,500);
              frame.setVisible(true);
         private static class NumericTableModel extends AbstractTableModel{
              public int getColumnCount() { return 2; }
              public int getRowCount() { return 10;}
              public Object getValueAt(int row, int col) {
                   int value = (row*2) + (col+1);
                   return value;
         private static class SelectAllAction extends AbstractAction{
              public void actionPerformed(ActionEvent e) {
                   //This should be shown when Shortcut Key is pressed
                   JOptionPane.showMessageDialog(null, "Worked");
         private static class DoNothingAction extends AbstractAction{
              public void actionPerformed(ActionEvent e) {
                   //do nothing
    }

  • JMenuItem whit Accelerator but without text

    helo
    I want to make JMenuItem whit accelerator but i don`t want text of accelerator on button! Help i dont know how to do that.
    I have my own MyJMenuItem I try to redefine paintComponent() method but this did not help.
    thanks

    You mean on an icon only menu item, or an invisible menu item? You could do control-key combinations with keybindings...
    http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html

  • JMenuItem's hotkey (accelerator) alignment

    Hi guys,
    How to force all JMenuItem's hotkeys (that are menu items accelerators) be aligned to the right equally for all hotkeys?
    I am about JMenuItem.setAccelerator(...) - how to force ALL THE hotkeys for a menu to be aligned equally to the right?
    Thanks in advance.

    [http://docstore.mik.ua/orelly/java-ent/jfc/ch03_08.htm]
    [http://onjava.com/pub/a/onjava/excerpt/swing_14/index3.html]

  • Accelerator keys for a JFrame containing JTextPane

    Hi, I have written a text editing window which extends JTextPane, and is embedded in a JFrame with a menubar. I have attached accelerator key shortcuts to each JMenuItem. However, none of them work, because my extension of JTextPane implements KeyListener, and thus controls keyboard input. How do I get the accelerator keys to still work? In general they are all Ctrl-key combinations with no meaningful function in the JTextPane.

    The only way I have found around this problem is to make your JFrame a KeyListener, and add it as a KeyListener of your JTextPane. In the keyPressed method of your JFrame call the processKeyEvent method. That will route the key to the menu. I have used this for a JTable and JTree under my JFrame, but not a JTextPane. It should work the same.
    I have heard rumors that this will be fixed in 1.4. Pretty lame that it is so difficult to do.

  • Accelerator text font problem

    When I set an accelerator key for a menu item,
    the name of that key is displayed beside the
    menu item. For example:
    fileExitItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_X, ActionEvent.ALT_MASK));
    The above code will display "Alt-X" next to the
    label in the file exit menu item. Now, if I
    wanted to change the font for the menu item I
    could enter something like:
    private class MyMenuItem extends JMenuItem
    {   public MyMenuItem(String label, ImageIcon icon)
    {   super(label, icon);
    setFont(new Font("Dialog", Font.BOLD, 16));
    And then define all my menu items to descend from the
    above class. The problem is that this does not change
    the font used to display the accelerator key. How do
    you change that??
    My thanks to anyone willing to help out.

    <snip>
    >
    And then define all my menu items to descend from the
    above class. Don't do that. See below.
    The problem is that this does not change
    the font used to display the accelerator key. How
    do you change that??Such changes should be done via the UIManager. If you compile and run the code below, you will see that the UIManager has keys such as Menu.font and Menu.acceleratorFont which you can use to do exactly what you want to do with no need to create a bunch of widget subclasses.
    ==============
    public class UILister extends JPanel {
         public static void main(String[] args) {
             try {
             JFrame f = new JFrame("UI Properties");
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             Set defaults = UIManager.getLookAndFeelDefaults().entrySet();
             TreeSet ts = new TreeSet(new Comparator() {
                 public int compare(Object a, Object b) {
                     Map.Entry ea = (Map.Entry)a;
                     Map.Entry eb = (Map.Entry)b;
                     return ((String)ea.getKey()).compareTo(((String)eb.getKey()));
             ts.addAll(defaults);
             Object[][] kvPairs = new Object[defaults.size()][2];
             Object[] columnNames = new Object[] {"Key", "Value"};
             int row = 0;
             for (Iterator i = ts.iterator(); i.hasNext();) {
                 Object o = i.next();
                 Map.Entry entry = (Map.Entry)o;
                 kvPairs[row][0] = entry.getKey();
                 kvPairs[row][1] = entry.getValue();
                 row++;
             JTable table = new JTable(kvPairs, columnNames);
             JScrollPane sp = new JScrollPane(table);
             f.getContentPane().add(sp);
             f.pack();
             f.setVisible(true);
             } catch (Exception e) {
                 e.printStackTrace();
    }===========

  • MDI JTable Overlap Area Repaint Problem

    Hi all,
    I have a problem for my application in MDI mode.
    I open many windows (JInternalFrame contain JTable) under JDesktopPane. Some of the windows are overlapping and when they receive update in the table, it seems repaint all of the overlapping windows, not only itself. This make my application performance become poor, slow respond for drap & drop an existing window or open a new window.
    To prove this, i make a simple example for open many simple table and have a thread to update the table's value for every 200 mill second. After i open about 20 windows, the performance become poor again.
    If anyone face the same problem with me and any suggestions to solve the problem ?
    Please help !!!!!
    Following are my sources:
    public class TestMDI extends JFrame {
        private static final long serialVersionUID = 1L;
        private JPanel contentPanel;
        private JDesktopPane desktopPane;
        private JMenuBar menuBar;
        private List<TestPanel> allScreens = new ArrayList<TestPanel>();
        private List<JDialog> freeFloatDialogs = new ArrayList<JDialog>();
        private List<JInternalFrame> mdiInternalFrm = new ArrayList<JInternalFrame>();
        int x = 0;
        int y = 0;
        int index = 0;
        private static int MDI_MODE = 0;
        private static int FREE_FLOAT_MODE = 1;
        private int windowMode = MDI_MODE;
        public TestMDI() {
            init();
        public static void main(String[] args) {
            new TestMDI().show();
        public void init() {
            contentPanel = new JPanel();
            desktopPane = new JDesktopPane();
            desktopPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
            desktopPane.setFocusTraversalKeysEnabled(false);
            desktopPane.setFocusTraversalPolicyProvider(false);
            desktopPane.setBorder(null);
            desktopPane.setIgnoreRepaint(true);
            desktopPane.setPreferredSize(new Dimension(1000, 800));
            this.setSize(new Dimension(1000, 800));
            menuBar = new JMenuBar();
            JMenu menu1 = new JMenu("Test");
            JMenuItem menuItem1 = new JMenuItem("Open Lable Screen");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        final TestJLableScreen screen = new TestJLableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            JMenuItem menuItem2 = new JMenuItem("Open Table Screen");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        TestTableScreen screen = new TestTableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            menu1.add(menuItem1);
            menu1.add(menuItem2);
            this.setJMenuBar(menuBar);
            this.getJMenuBar().add(menu1);
            this.getJMenuBar().add(createSwitchMenu());
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(desktopPane);
            desktopPane.setDesktopManager(null);
        public JInternalFrame createInternalFram(final TestPanel panel) {
            final CustomeInternalFrame internalFrame = new CustomeInternalFrame(panel.getTitle(), true, true, true, true) {
                public void doDefaultCloseAction() {
                    super.doDefaultCloseAction();
                    allScreens.remove(panel);
            internalFrame.setPanel(panel);
            // internalFrame.setOpaque(false);
            internalFrame.setSize(new Dimension(1010, 445));
            internalFrame.add(panel);
            internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setFocusTraversalPolicyProvider(false);
            desktopPane.getDesktopManager();
            // internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setIgnoreRepaint(true);
            return internalFrame;
        public JDialog createJDialog(final TestPanel panel) {
            JDialog dialog = new JDialog(this, panel.getTitle());
            dialog.setSize(new Dimension(1010, 445));
            dialog.add(panel);
            dialog.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    allScreens.remove(panel);
            return dialog;
        public JMenu createSwitchMenu() {
            JMenu menu = new JMenu("Test2");
            JMenuItem menuItem1 = new JMenuItem("Switch FreeFloat");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = FREE_FLOAT_MODE;
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    remove(desktopPane);
                    desktopPane.removeAll();
    //                revalidate();
                    repaint();
                    add(contentPanel);
                    index = 0;
                    for (JDialog dialog : freeFloatDialogs) {
                        dialog.setVisible(false);
                        dialog.dispose();
                        dialog = null;
                    freeFloatDialogs.clear();
                    for (int i = 0; i < allScreens.size(); i++) {
                        JDialog dialog = createJDialog(allScreens.get(i));
                        freeFloatDialogs.add(dialog);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        dialog.setLocation(x, y);
                        dialog.setVisible(true);
            JMenuItem menuItem2 = new JMenuItem("Switch MDI");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = MDI_MODE;
                    remove(contentPanel);
                    add(desktopPane);
                    for (int i = 0; i < freeFloatDialogs.size(); i++) {
                        freeFloatDialogs.get(i).setVisible(false);
                        freeFloatDialogs.get(i).dispose();
                    freeFloatDialogs.clear();
    //                revalidate();
                    repaint();
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    index = 0;
                    for (int i = 0; i < allScreens.size(); i++) {
                        JInternalFrame frame = createInternalFram(allScreens.get(i));
                        desktopPane.add(frame);
                        mdiInternalFrm.add(frame);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        frame.setLocation(x, y);
                        frame.setVisible(true);
            menu.add(menuItem1);
            menu.add(menuItem2);
            return menu;
    public class TestTableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        JTable testTable = new JTable();
        MyTableModel tableModel1 = new MyTableModel(1);
        private boolean notRepaint = false;
        int start = 0;
        JScrollPane scrollPane = new JScrollPane();
        private Timer timmer = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(50);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        notRepaint = false;
                        TestTableScreen.this.update(index + "|" + val);
        public TestTableScreen(String title) {
            this.title = title;
            init();
            tableModel1.setTabelName(title);
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                List vals = tableModel1.getVector();
                if (vals.size() > index) {
                    vals.set(index, val[1]);
    //                 tableModel1.fireTableRowsUpdated(index, index);
                } else {
                    vals.add(val[1]);
    //                 tableModel1.fireTableRowsUpdated(vals.size() - 1, vals.size() - 1);
                tableModel1.fireTableDataChanged();
        public TableModel getTableModel() {
            return tableModel1;
        public void init() {
            testTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            testTable.setRowSelectionAllowed(true);
            this.testTable.setModel(tableModel1);
            int[] width = { 160, 80, 45, 98, 60, 88, 87, 88, 80, 70, 88, 80, 75, 87, 87, 41, 88, 82, 75, 68, 69 };
            TableColumnModel columnModel = testTable.getColumnModel();
            for (int i = 0; i < width.length; i++) {
                columnModel.getColumn(i).setPreferredWidth(width[i]);
            testTable.setRowHeight(20);
            tableModel1.fireTableDataChanged();
            this.setLayout(new BorderLayout());
            TableColumnModel columnMode2 = testTable.getColumnModel();
            int[] width2 = { 200 };
            for (int i = 0; i < width2.length; i++) {
                columnMode2.getColumn(i).setPreferredWidth(width2[i]);
            scrollPane.getViewport().add(testTable);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            this.add(scrollPane, BorderLayout.CENTER);
        class MyTableModel extends DefaultTableModel {
            public List list = new ArrayList();
            String titles[] = new String[] { "袨怓1", "袨怓2", "袨怓3", "袨怓4", "袨怓5", "袨怓6", "袨怓7", "袨怓8", "袨怓9", "袨怓10", "袨怓11",
                    "袨怓12", "袨怓13", "袨怓14", "袨怓15", "袨怓16", "袨怓17", "袨怓18", "袨怓19", "袨怓20", "袨怓21" };
            String tabelName = "";
            int type_head = 0;
            int type_data = 1;
            int type = 1;
            public MyTableModel(int type) {
                super();
                this.type = type;
                for (int i = 0; i < 50; i++) {
                    list.add(i);
            public void setTabelName(String name) {
                this.tabelName = name;
            public int getRowCount() {
                if (list != null) {
                    return list.size();
                return 0;
            public List getVector() {
                return list;
            public int getColumnCount() {
                if (type == 0) {
                    return 1;
                } else {
                    return titles.length;
            public String getColumnName(int c) {
                if (type == 0) {
                    return "head";
                } else {
                    return titles[c];
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            public Object getValueAt(int r, int c) {
                if (list.size() == 0) {
                    return null;
                switch (c) {
                default:
                    if (type == 0) {
                        return r + " " + c + "  test ";
                    } else {
                        return list.get(r) + "   " + c;
        public boolean isNotRepaint() {
            return notRepaint;
        public void setNotRepaint(boolean notRepaint) {
            this.notRepaint = notRepaint;
    public class TestPanel extends JPanel {
        protected String title = "";
        protected boolean needRepaint = false;
        protected boolean isFirstOpen = true;
        public String getTitle() {
            return title;
        public void setNeedRepaint(boolean flag) {
            this.needRepaint = flag;
        public boolean isNeedRepaint() {
            return needRepaint;
        public boolean isFirstOpen() {
            return isFirstOpen;
        public void setFirstOpen(boolean isFirstOpen) {
            this.isFirstOpen = isFirstOpen;
    public class TestJLableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        private JLabel[] allLables = new JLabel[20];
        private Timer timmer = new Timer(20, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(10);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        TestJLableScreen.this.setNeedRepaint(true);
                        TestJLableScreen.this.update(index + "|" + val);
        public TestJLableScreen(String title) {
            this.title = title;
            init();
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                allLables[index * 2 + 1].setText(val[1]);
        public void init() {
            this.setLayout(new GridLayout(10, 2));
            boolean flag = true;
            for (int i = 0; i < allLables.length; i++) {
                allLables[i] = new JLabel() {
                    // public void setText(String text) {
                    // super.setText(text);
                    // // System.out.println("  setText " + getTitle() + "   ; " + this.getName());
                    public void paint(Graphics g) {
                        super.paint(g);
                        // System.out.println("  paint " + getTitle() + "   ; " + this.getName());
                    // public void repaint() {
                    // super.repaint();
                    // System.out.println("  repaint " + getTitle() + "   ; " + this.getName());
                allLables[i].setName("" + i);
                if (i % 2 == 0) {
                    allLables[i].setText("Name " + i + "  : ");
                } else {
                    allLables[i].setOpaque(true);
                    if (flag) {
                        allLables[i].setBackground(Color.YELLOW);
                        flag = false;
                    } else {
                        allLables[i].setBackground(Color.CYAN);
                        flag = true;
                    allLables[i].setText(i * 8 + "");
            for (int i = 0; i < allLables.length; i++) {
                this.add(allLables[i]);
    public class CustomeInternalFrame extends JInternalFrame {
        protected TestPanel panel;
        public CustomeInternalFrame() {
            this("", false, false, false, false);
        public CustomeInternalFrame(String title) {
            this(title, false, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable) {
            this(title, resizable, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable) {
            this(title, resizable, closable, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) {
            this(title, resizable, closable, maximizable, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable,
                boolean iconifiable) {
            super(title, resizable, closable, maximizable, iconifiable);
        public TestPanel getPanel() {
            return panel;
        public void setPanel(TestPanel panel) {
            this.panel = panel;

    i had the same problem with buttons and it seemed that i overlayed my button with something else...
    so check that out first do you put something on that excact place???
    other problem i had was the VAJ one --> VisualAge for Java (terrible program)
    it does strange tricks even when you don't use the drawing tool...
    dunno 2 thoughts i had... check it out...
    SeJo

  • Retrieving values entered in a JTable

    Hi!
    I have made a sudoku solver as many others, but in the purpose of learning recursion, and now I am implementing GUI to that program. I have bean strugling to set up a table that shows the sudokutable, and most of all how to recieve the values entered into the table. I have looked at forums and search at google, but all the topics on this is not good enough. I just simply do not understand what they mean. Most often they just say: "Just paste this code in and it will turn out as intended". I want to know how it works.
    I have added the code below:
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.*;
    import java.awt.event.*;
    import easyIO.*;
    import java.util.*;
    import java.io.*;
    * Klassen Oblig3 som inneholder main metoden som starter programmet.
    * Dette er Utsynen for programmet.
    * @Param ru - Peker til klassen Rute.
    * @Param br - Peker til klassen Brett.
    * @Param skrivebord - En ny desktpoPane som representerer hovedvinduet..
    public class Oblig3 extends JFrame implements ActionListener {
         Rute  ru   = new Rute();
         Brett br   = new Brett(ru);
         ImageIcon icon;
         Image image;
         JDesktopPane skrivebord;
          * Konstrukt�ren Oblig3 som setter opp hovedvinduet.
          * @Param skjemrStorelse - Lagrer st�relsen p� skjermen.
         public Oblig3() {
              super("Oblig3");
              int innrykk = 400;
              Dimension skjermStorelse = Toolkit.getDefaultToolkit().getScreenSize();
              setBounds(innrykk, innrykk, skjermStorelse.width  - innrykk*3, skjermStorelse.height - innrykk*2);
              skrivebord = new JDesktopPane()
                   Image im = (new ImageIcon("bilder/panzer.gif")).getImage();
                   public void paintComponent(Graphics g){
                        g.drawImage(im,0,0,this);
              setContentPane(skrivebord);
              setJMenuBar(lagMenyList());
              skrivebord.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
         } // Slutt p� konstrukt�ren Oblig3
         * JMenuBar metoden som gir menyen til hovedvinduet.
         * @Param menyList - Peker p� et MenuBar objekt.
         * @Param meny# - Menyene p� menylisten.
         * @Param menyObjekt - Et valg p� gitt meny.
         protected JMenuBar lagMenyList() {
              JMenuBar menyList = new JMenuBar();
              // F�rste menyen
              JMenu meny1 = new JMenu("Fil");
              meny1.setMnemonic(KeyEvent.VK_F);
              menyList.add(meny1);
                   // Gruppe1 med JMenuObjekt
                   JMenuItem menyObjekt = new JMenuItem("�pne brett", new ImageIcon("bilder/folder.gif"));
                   menyObjekt.setMnemonic(KeyEvent.VK_O);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("�pne brett");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
                   menyObjekt = new JMenuItem("Spare brett", new ImageIcon("bilder/floppy.gif"));
                   menyObjekt.setMnemonic(KeyEvent.VK_S);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("Spare brett");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
                   meny1.addSeparator();
                   menyObjekt = new JMenuItem("Exit");
                   menyObjekt.setMnemonic(KeyEvent.VK_ESCAPE);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("Exit");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
              // Lage den andre menyen
              JMenu meny2 = new JMenu("Edit");
              meny1.setMnemonic(KeyEvent.VK_E);
              menyList.add(meny2);
                   // Gruppe2 med JMenObjekt
                   menyObjekt = new JMenuItem("L�s Brett");
                   menyObjekt.setMnemonic(KeyEvent.VK_L);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("L�s Brett");
                   menyObjekt.addActionListener(this);
                   meny2.add(menyObjekt);
                   menyObjekt = new JMenuItem("Lag eget brett");
                   menyObjekt.setMnemonic(KeyEvent.VK_L);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.ALT_MASK));
                   menyObjekt.setActionCommand("Lag eget brett");
                   menyObjekt.addActionListener(this);
                   meny2.add(menyObjekt);
              // Lage den tredje menyen
              JMenu meny3 = new JMenu("Hjelp");
              meny1.setMnemonic(KeyEvent.VK_H);
              menyList.add(meny3);
                   // Gruppe3 med JMenObjekt
                   menyObjekt = new JMenuItem("Version?");
                   menyObjekt.setActionCommand("Version?");
                   menyObjekt.addActionListener(this);
                   meny3.add(menyObjekt);
                   menyObjekt = new JMenuItem("www.dresas.com");
                   menyObjekt.setActionCommand("www.dresas.com?");
                   menyObjekt.addActionListener(this);
                   meny3.add(menyObjekt);
              return menyList;
         } // Slutt p� JMenuBar metoden.
         * Metode som lytter p� menyval mm.
         public void actionPerformed(ActionEvent e) {
              if(e.getActionCommand().equals("�pne brett")) {
                   lesFraFil();
              } else if (e.getActionCommand().equals("L�s Brett")) {
                   losning();
              } else if (e.getActionCommand().equals("Exit")) {
                   System.exit(0);
              } else if (e.getActionCommand().equals("Version?")) {
                   version();
              } else if (e.getActionCommand().equals("www.dresas.com")) {
                   link();
              } else if (e.getActionCommand().equals("Lag eget brett")) {
                   lagEgetBrett();
              } // Slutt p� if-else-if setning.
         * Metoden lesFraFil som ber om navn p� fil fra bruker
         * via grensesnittet.
         protected void lesFraFil() {
              final String losFraFil = JOptionPane.showInputDialog(null, "Skriv inn navn p� filen.");
              svarLesFraFil(losFraFil + ".txt");
         } // Slutt p� metoden losFraFil
         * Metoden svarLesFaFil som gir resultat p� inlesning fra fil.
         protected void svarLesFraFil(String filnavn) {
              boolean rF = br.lesBrettFraFil(filnavn);
              if(rF == true) {
                    JOptionPane.showMessageDialog(this, "Filen er lest inn");
              } else {
                    JOptionPane.showMessageDialog(this, "Filen ble ikke lest inn,\n (husk sm� og store bokstaver)");
              } // Slutt p� if-else
         } // Slutt p� metoden svarLosFraFil
         * Metoden losning som gir resultat p� l�st brett.
         protected void losning() {
              ru.provAlleSifferMegOgResten(0);
              br.skrivLosning();
         } // Slutt p� metoden losning
         protected void version() {
              JOptionPane.showMessageDialog(null, "Dette er version 0.7");
         protected void link() {
              OpenBrowser op = new OpenBrowser();
              op.displayURL("www.dresas.com");
         } // Slutt p� metoden link
         * Metoden lagEgetBrett som lar brukeren tegne sitt eget
         * brett og l�se det.
         * @Param ramme - Peker p� objektet av klassen InternRamme som
         *                setter opp det interne vinduet.
         protected void lagEgetBrett() {
              int boksBredde = 3;
              int boksHojde  = 3;
              int brettStorelse = 9;
              boolean b1 = true;
              while (b1) {
                   boksBredde = Integer.parseInt(JOptionPane.showInputDialog(null, "Skriv inn Bredde p� boksen. (2-4)"));
                   if (boksBredde > 1 && boksBredde < 5) {
                        boksHojde  = Integer.parseInt(JOptionPane.showInputDialog(null, "Skriv inn H�jde p� boksen. (3-4)"));
                        if (boksHojde > 2 && boksHojde < 5) {
                             b1 = false;
                        } else {
                             JOptionPane.showMessageDialog(null, "M� vaere mellom 3 og 4.");
                             continue;
                   } else {
                        JOptionPane.showMessageDialog(null, "M� vaere mellom 2 og 4.");
                        continue;
              brettStorelse = boksBredde * boksHojde;
              InternRamme ramme = new InternRamme(brettStorelse * 16, brettStorelse * 16);
                   Object[][] data = new Object[brettStorelse][brettStorelse];
                   for (int i = 0;i < brettStorelse;i++) {
                        for (int j = 0; j < brettStorelse;j++) {
                             data[i][j] = 0;
                   String[] columnNames = new String[brettStorelse];
                   for (int i = 0; i < brettStorelse;i++) {
                        int b = 1 + i;
                        columnNames[i] = String.valueOf(b);
                   JTable sudokuTabell = new JTable(data, columnNames);
                   sudokuTabell.setGridColor (new Color (tilfeldig(256), tilfeldig(256), tilfeldig(256)));
                   sudokuTabell.setFont(new Font ("Tahoma", Font.PLAIN, 16));
                   setVisible(true);
              ramme.add(sudokuTabell);
              ramme.setVisible(true);
              skrivebord.add(ramme);
              try {
                   ramme.setSelected(true);
              } catch (java.beans.PropertyVetoException e) {}
         } // Slutt p� klassen lagEgetBrett
         * Metode som returnerer tilfeldigt verdi st�rre en 0 og mindre
         * en maks.
         public static int tilfeldig (int maks) {
              return (int) (Math.random () * maks);
        * Metoden utsyn som tegner opp programmet p� skjermen.
        * @Param frame - Peker p� objektet Oblig3.
        private static void utsyn() {
            //Create and set up the window.
            Oblig3 frame = new Oblig3();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
        } // Slutt p� metoden utsyn.
        * Metoden main som starter programmet.
        public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    utsyn();
         } //  Slutt p� metoden main.
    } // Slutt p� klassen Oblig3.
    * Brukt av Oblig3
    class InternRamme extends JInternalFrame {
         static int tellOpneRammer = 0;
         static final int xOffset = 30, yOffset = 30;
         InternRamme(int bredde, int hojde) {
              super("Lag eget Brett #" + (++tellOpneRammer),
                     true, //resizable
                     true, //closable
                     true, //maximizable
                     true);//iconifiable
              //...Create the GUI and put it in the window...
              //...Then set the window size or call pack...
              setSize(bredde,hojde);
              //Set the window's location.
              setLocation(xOffset*tellOpneRammer, yOffset*tellOpneRammer);
    }

    Here is the method in mind, translated...
    protected void ConstructOwnBoard() {
         int boxWidth = 3;
         int boxHeight = 3;
         int BoardSize = 9;
         boolean b1 = true;
         while (b1) {
              boxWidth = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Width. (2-4)"));
              if (boxWidth > 1 && boxWidth < 5) {
                   boxHeight = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Height. (3-4)"));
                   if (boxHeight > 2 && boxHeight < 5) {
                        b1 = false;
                   } else {
                        JOptionPane.showMessageDialog(null, "Must be btween 3 og 4.");
                        continue;
              } else {
                   JOptionPane.showMessageDialog(null, "Must be between 2 og 4.");
                   continue;
         BoardSize = boxWidth * boxHeight ;
         InternalFrame frame = new InternalFrame(BoardSize * 16, BoardSize * 16);
         Object[][] data = new Object[BoardSize ][BoardSize ];
         for (int i = 0;i < BoardSize ;i++) {
              for (int j = 0; j < BoardSize ;j++) {
                   data[i][j] = 0;
         String[] columnNames = new String[BoardSize ];
         for (int i = 0; i < BoardSize ;i++) {
              int b = 1 + i;
              columnNames[i] = String.valueOf(b);
         JTable sudokuTable = new JTable(data, columnNames);
         sudokuTable.setGridColor (new Color (tilfeldig(256), tilfeldig(256), tilfeldig(256)));
         sudokuTable.setFont(new Font ("Tahoma", Font.PLAIN, 24));
         TableColumn column = null;
         for (int i = 0; i < BoardSize ; i++) {
              column = sudokuTable.getColumnModel().getColumn(i);
              column.setMinWidth(25);
              column.setMaxWidth(25);
              column.setResizable(false);
         setVisible(true);
         frame.add(sudokuTable);
         frame.setVisible(true);
         desktop.add(ramme);
         try {
              frame.setSelected(true);
         } catch (java.beans.PropertyVetoException e) {}
    } // end of class

  • 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.

  • Problem printing JTable

    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.awt.print.PrinterJob;
    import java.awt.print.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.table.*;
    class DisplayQueryResultsDOD extends JFrame implements Printable,ActionListener
    ResultSetTableModelDOD tableModel;
    JTextArea queryArea;
    JTable resultTable;
    // create ResultSetTableModel and GUI
    DisplayQueryResultsDOD()
    super( "Displaying Query Results" );
    // Cloudscape database driver class name
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // URL to connect to books database
    String url = "jdbc:odbc:MyDataSource";
    // query to select entire authors table
    String query = "SELECT * FROM person";
    // create ResultSetTableModel and display database table
         try
    // create TableModel for results of query
    // SELECT * FROM authors
              tableModel =
              new ResultSetTableModelDOD( driver, url, query );
    // set up JTextArea in which user types queries
              queryArea = new JTextArea( query, 3, 100 );
              queryArea.setWrapStyleWord( true );
              queryArea.setLineWrap( true );
              JScrollPane scrollPane = new JScrollPane( queryArea,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
    // set up JButton for submitting queries
              JButton submitButton = new JButton( "Submit Query" );
    // create Box to manage placement of queryArea and
    Box box = Box.createHorizontalBox();
              box.add( scrollPane );
              box.add( submitButton );
    // create JTable delegate for tableModel
              JTable resultTable = new JTable( tableModel );
    // place GUI components on content pane
              Container c = getContentPane();
              c.add( box, BorderLayout.NORTH );
              c.add( new JScrollPane( resultTable ),
              BorderLayout.CENTER );
    // create event listener for submitButton
              submitButton.addActionListener(
         new ActionListener()
         public void actionPerformed( ActionEvent e )
    // perform a new query
         try
              tableModel.setQuery( queryArea.getText() );
    // catch SQLExceptions that occur when
    // performing a new query
         catch ( SQLException sqlException )
              JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error",JOptionPane.ERROR_MESSAGE );
    } // end actionPerformed
    } // end ActionListener inner class
    // set window size and display window
    JMenuBar menuBar = new JMenuBar();
         JMenu filemenu= new JMenu("File");
         JMenu submenux=new JMenu("Open");
         JMenuItem np=new JMenuItem("Launch Panel");
         submenux.add(np);
         //openmenuitem.addActionListener(this);
         submenux.setActionCommand("Open");
         submenux.setMnemonic('O');
         filemenu.add(submenux);
         menuBar.add(filemenu);
         JMenuItem printItem = new JMenuItem("Print");
         printItem.setMnemonic('P');
         filemenu.add(printItem);
         JMenuItem ExitItem = new JMenuItem("Exit");
    ExitItem.setMnemonic('x');
         filemenu.add(ExitItem);
         JMenu viewmenu=new JMenu("View");
         JMenuItem repItem=new JMenuItem("Reports");
         JMenu submenu=new JMenu("sort by");
         submenu.add(new JMenuItem("Marital Status"));
    submenu.add(new JMenuItem("Rank"));
         submenu.add(new JMenuItem("Tribe"));
         submenu.add(new JMenuItem("Educational Level"));
         viewmenu.add(submenu);
         menuBar.add(viewmenu);
         setJMenuBar(menuBar);
    printItem.addActionListener(this);
         ExitItem.addActionListener
         new ActionListener()
    public void actionPerformed(ActionEvent ae)
    System.exit(0);
    setSize( 1500,900);
    // setVisible( true );
    } // end try
    // catch ClassNotFoundException thrown by
    // ResultSetTableModel if database driver not found
         catch ( ClassNotFoundException classNotFound )
         JOptionPane.showMessageDialog( null,"Cloudscape driver not found", "Driver not found",JOptionPane.ERROR_MESSAGE );
              System.exit( 1 ); // terminate application
    // catch SQLException thrown by ResultSetTableModel
    // if problems occur while setting up database
    // connection and querying database
         catch ( SQLException sqlException )
         JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 ); // terminate application
    } // end DisplayQueryResults constructor
         public void actionPerformed(ActionEvent e)
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try
    printJob.print();
    catch (Exception ex)
    ex.printStackTrace();
         public int print(Graphics g, PageFormat pf, int page) throws
    PrinterException {
    if (page > 0) { /* We have only one page, and 'page' is zero-based */
    return NO_SUCH_PAGE;
    /* User (0,0) is typically outside the imageable area, so we must
    * translate by the X and Y values in the PageFormat to avoid clipping
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    /* Now print the window and its visible contents */
    resultTable.printAll(g);
    /* tell the caller that this page is part of the printed document */
    return PAGE_EXISTS;
    // execute application
    public static void main( String args[] )
    DisplayQueryResultsDOD app = new DisplayQueryResultsDOD();
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    } // end class DisplayQueryResults
    I get an exception
    pls help

    I included this statement only to check if it would print or not, because before that I tried printing the table without setting the size. Anyway, when I tried the same code under Windows it worked fine. Talking about platform independent...:-)

  • How can I change the default process of VK_ENTER in JTable

    Now I have met a requirment to process the "enter" key event in JTable. But it is found that the JTable has a default process on the ENTER key press, and it will select the next row. Even the worse, the default process is invoked before the KeyListener I registered.
    How can I remove that?
    I have tried the follow ways: 1.remove several keys, such as "selectNextRow","selectNextRowExtendSelection", from the actionMap,
    2.invoke processKeyBinding() in the constructor of my subclass of JTable.
    But both lead to failure.
    And I can't find the default process to the VK_ENTER in the java source code. I need help on this.
    BTW, does anyone know how to eliminate the focus traversal between cells. When I press left arrow or right arrow, the focus traverses in the scope of the selected row.

    thanks
    i also found solution for my poblem:
    i have this code:
    jMenuItem jMnItEdit;
    jMnItEdit.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER, 0));
    also i had ActionListener bounded to this JMenuItem
    but Ialso had in form JTable and it always grabbed my VK_ENTER event and that menu item wasn't working at all
    but when i overrode that input map for JTable and set
    tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "none");
    everything started to work perfectly,
    thanks a lot

  • Creating a new row in a JTable

    How do i make a new row in a JTabel?

    is there a line something like: newRow(); but anyway here is the code i have so far thanx for the help:
    class UserSettings extends JFrame implements ActionListener {
      private JMenuBar menu = new JMenuBar();
      private JMenu Settings;
      private JMenuItem exit;
      private JButton sset;
      String[] columnNames = {"users","passwords"};
      Vector dat = new Vector();
      private JTable usertable;
      public UserSettings() {
        setSize(new Dimension(350, 350));
        setTitle("User Setings");
        Settings = new JMenu("Settings");
        menu.add(Settings);
        exit = new JMenuItem("Exit");
        exit.addActionListener(this);
        Settings.add(exit);
        sset = new JButton("Save settings");
        sset.addActionListener(this);
        try {
          BufferedReader userin = new BufferedReader(new FileReader("users/userp.txt"));
          String su;
          while ((su = userin.readLine()) != null) {
            String[] uspa = su.split(" ");
            dat.add(uspa);
        catch (FileNotFoundException ioe) {
          JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);
        catch (ClassCastException ioe){}
        catch (NullPointerException ioe) {}
        catch (IOException ioe) {
          JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);
        String[][] data = new String[dat.size()][];
        for(int x = 0; x < dat.size(); x++) {
          data[x] = (String[])dat.get(x);
        usertable = new JTable(data, columnNames);
        JScrollPane scrollpane = new JScrollPane(usertable);
        usertable.setPreferredScrollableViewportSize(new Dimension(50, 500));
        JPanel pane = new JPanel(new GridLayout(0, 1));
        getContentPane().add(scrollpane);
        getContentPane().add(sset, BorderLayout.SOUTH);
        setJMenuBar(menu);
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == sset) {
             int count = usertable.getRowCount();
             if (count == 1) {
             if (count == 2) {
             if (count == 3) {
          try {
               FileWriter uname = new FileWriter("users/usertest.txt");
               String sname;
               uname.write("test");
               uname.close();
          catch (IOException ioe) {
               JOptionPane.showMessageDialog(null, "Error saving you file, if error persists contact [email protected] or reenstal", "", JOptionPane.WARNING_MESSAGE);
          dispose();
        if (e.getSource() == exit) {
          int exitask = JOptionPane.showConfirmDialog(UserSettings.this, "Are you sure you want to exit? Any unsaved settinging changes will be lost!!");
          if (exitask == JOptionPane.YES_OPTION) {
            dispose();
    Thanx again

  • Inserting Pics in a JTable

    I'd like to include an ID of the person within my table.
    Using DefaultTableModel and ImageIcon, how can I insert a picture?
    Is it even possible to enter a non-textual entry into a JTable?
    Here's what I did:
    JMenuItem insertPicture;
    JTable contactTable;
    DefaultTableModel details;
    else if(ae.getSource() == insertPicture)
      // Column and row details
      int row = contactTable.getSelectedRow();
      int column = contactTable.getSelectedColumn();
      // Using a string to store the picture's location details
      String fileName;
      FileDialog location = new FileDialog(ContactDetails.this,   
                "Choose picture", FileDialog.LOAD);
      // Displaying the FileDialog
      location.show();
      // Getting the image and inserting it in the JTable
      ImageIcon image = new ImageIcon(location.getDirectory()+
      location.getFile());
      details.setValueAt(image, row, column);
    }My problem is that within the row (to which the picture should be placed), I'm getting only the String description of the image's location. How can I correct this?
    Much thanks in advance!
    Reformer!

    import java.awt.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test {
        public static void main(String[] args) throws MalformedURLException {
            DefaultTableModel model = new DefaultTableModel(new String[]{"path","image"}, 0) {
                public Class getColumnClass(int columnIndex) {
                    return columnIndex==1? Icon.class : String.class;
                public boolean isCellEditable(int rowIndex, int columnIndex){
                    return false;
            URL[] urls = {
                new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg"),
                new URL("http://today.java.net/jag/bio/JAG2001small.jpg"),
                new URL("http://blogs.sun.com/roller/resources/jag/2005_09_14_03-44-21-438_n1.small.png")
            for(int i=0; i<urls.length; ++i)
                model.addRow(new Object[]{urls.toString(), new ImageIcon(urls[i])});
    JTable table = new JTable(model);
    table.setRowHeight(240);
    JScrollPane sp = new JScrollPane(table);
    sp.setPreferredSize(new Dimension(600,450));
    final JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(sp);
    f.pack();
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    f.setLocationRelativeTo(null);
    f.setVisible(true);

Maybe you are looking for

  • Safari 6.0.2 keeps crashing on 10.7.5

    My Safari 6.0.2 keeps crashing all the time. I'm using Macbook Pro with OS 10.7.5. All softwares are up to date, cache emptied, still problem occurs. Could somebody help? Thanks! Here is the last crashreport: Process:         WebProcess [63550] Path:

  • What's wrong with Safari??

    It's always something. Right now, I can't open Safari without it 'not responding' within just two minutes. It really just started happening a few days ago, but it does this now and I 'force quit' 20 or more times a day. I just updated to 4.0.3. today

  • How do i get my phone off demo mode

    i bought my phone from orange, but when they set it up in store, they set it up in demo mode. iv been back to the shop for them to tell me that it will take 6-7 hrs to sort?? can i not do this from home?

  • Looking for forms samples

    I am using Acrobat 9 Pro with LifeCycle Designer ES 8.2. I am trying to find some somples of the PDF forms with will: Submit form data to the Access Database Populate form with the data from Access Database I have done many searches and so far could

  • CSMARS 6.0 Tune Bandwidth Utilization

    Any way to tune out 11:00PM 12:00PM bandwidth notice "red events"? These are backups over a few t1 interfaces and "false positives". I dont see a way to make the FP for a hourly time range.