JInternalFrame  , Jtable && XML

Hi all ,
I am trying to Build a GUI program that gets the data from the XML file and then put it into the Jtable . The jtable is in the Jinternalframe .
When I try to add one Jinternalframe that containing the Jtable , it works fine .
But when I try to put the other Jinternalframe that containing another Jtable .
It fails . I can compile the program but can't run it .
It is the error code :
Exception in thread "main" java.lang.NullPointerException
at tablemodel.getColumnName(tablemodel.java:92)
at TableMap.getColumnName(TableMap.java:38)
at javax.swing.JTable.addColumn(JTable.java:1841)
at javax.swing.JTable.createDefaultColumnsFromModel(JTable.java:927)
at javax.swing.JTable.tableChanged(JTable.java:2842)
at javax.swing.JTable.setModel(JTable.java:2710)
at javax.swing.JTable.<init>(JTable.java:357)
at javax.swing.JTable.<init>(JTable.java:297)
at jin_frame.<init>(jin_frame.java:15)
at button.<init>(button.java:41)
at button.main(button.java:115)
Can somebody help ??

Could you show the code that you used to do this? I am trying to do the same thing. Thank you.

Similar Messages

  • Having trouble with JInternalFrame

    I posted about this and was advised that self-contained runnable code is a better way of illustrating the problem.
    I've written up an app which replicates the class structure and makes the same calls as a real app but is compilable and runnable.
    The problem is in the last 3 lines of MyJInternalFrame class, (which I have commented out).
    I want to trap an event in my JTable which is displayed in an instance of MyJInternalFrame and then display some data taken from the table in another JInternalFrame but this class structure won't allow it.
    I'm pretty sure that I am being dumb, but I hope someone can help point me in the right direction!
    Regards
    Paul
    package selfcontained;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    @author Paul Wilkin - to replicate problem.
    public class MyOuterFrame extends JFrame implements ActionListener {
    JButton myButton;
    JPanel myPanel;
    public MyOuterFrame(){
    super("Problem Demo");
    myPanel = new JPanel();
    myButton = new JButton("Press Me");
    myButton.addActionListener(this);
    myPanel.add(myButton);
    this.getContentPane().add(myPanel);
    this.setSize(100,100);
    this.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    myJInternalFrame myIF = new myJInternalFrame();
    myIF.setVisible(true);
    myPanel.add(myIF);
    this.setSize(550,550);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    createAndShowGUI();
    private static void createAndShowGUI(){
    try{
    //String PLAFName = UIManager.getSystemLookAndFeelClassName();
    // UIManager.setLookAndFeel(PLAFName);
    MyOuterFrame frame = new MyOuterFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    } catch (Exception e){
    System.out.println("Exception caught" + e);
    class myJInternalFrame extends JInternalFrame{
    JTable myJTable;
    public myJInternalFrame(){
    this.setSize(100,100);
    String [] headings = {"Column 1","Column 2"};
    Object [][] data = {{"Entry 1a","Entry 2a"},{"Entry 1b","Entry 2b"}};
    myJTable = new JTable(data,headings);
    myJTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    this.getContentPane().add(new JScrollPane(myJTable),"Center");
    ListSelectionModel myLSM = myJTable.getSelectionModel();
    myLSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent le) {
    int[] rows = myJTable.getSelectedRows();
    // myJInternalFrame newIF = new myJInternalFrame();
    // newIF.getContentPane().add(new JLabel(rows.toString()));
    // myPanel.add(newIF);
    }

    posted about this and was advised that self-contained runnable code is a better way of illustrating the problem. It also helps if you post readable code. I'm sure you don't write your code left aligned so don't expect us to read it unformatted.
    class myJInternalFrame extends JInternalFrame
        JTable myJTable;
        JLabel label;
        public myJInternalFrame()
            this.setSize(100,100);
            String [] headings = {"Column 1","Column 2"};
            Object [][] data = {{"Entry 1a","Entry 2a"},{"Entry 1b","Entry 2b"}};
            myJTable = new JTable(data,headings);
            myJTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            this.getContentPane().add(new JScrollPane(myJTable),"Center");
            label = new JLabel(" ");
            add(label, BorderLayout.SOUTH);
            ListSelectionModel myLSM = myJTable.getSelectionModel();
            myLSM.addListSelectionListener(new ListSelectionListener()
                public void valueChanged(ListSelectionEvent le)
                    if (! le.getValueIsAdjusting())
                        label.setText("Selected: " + myJTable.getSelectedRow());
    }I really don't understand your question. You say you want to display data from the table yet I don't see any code that attempts to reference the table. So I just threw together a quick demo that may provide some ideas.

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

  • JTable, JScrollPane, and JinternalFrame problems.

    I have this internal frame in my application that has a scrollpane and table in it. Some how it won't let me selelct anything in the table. Also it scrolls really weird. There's a lot of chopping going on. Here's my code for the internal frame:
    public class BCDEObjectWindow extends javax.swing.JInternalFrame{
        private Vector bcdeObjects = new Vector();
        private DefaultTableModel tModel;
        public BCDEObjectWindow(JavaDrawApp p) {
            initComponents();
            this.setMaximizable(false);
            this.setClosable(false);
            this.setIconifiable(true);
            this.setDoubleBuffered(true);
            objectTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
            listScrollPane.setColumnHeaderView(new ObjectWindowHeader());
            pack();
            this.setVisible(true);
            parent = p;
            getAllBCDEFigures();
            setPopupMenu();
            tModel = (DefaultTableModel) objectTable.getModel();
            objectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        public void getAllBCDEFigures() {
            bcdeObjects.removeAllElements();
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
        public void addBCDEFigure(BCDEFigure b) {
            bcdeObjects.add(b);
            tModel.addRow(new Object[]{b.BCDEName, "incomplete"});
        public void changeLabelName(BCDEFigure b) {
            if (bcdeObjects.contains(b)) {
                int index = bcdeObjects.indexOf(b);
                tModel.removeRow(index);
                tModel.insertRow(index, new Object[]{b.BCDEName, "incomplete"});
        public void removeBCDEFigure(BCDEFigure b) {
            int index = 0;
            if (bcdeObjects.contains(b)) {
                index = bcdeObjects.indexOf(b);
                bcdeObjects.remove(b);
                tModel.removeRow(index);
        public void removeAllBCDEFigures(){
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
            bcdeObjects.removeAllElements();
        /** 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.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            listScrollPane = new javax.swing.JScrollPane();
            objectTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setBackground(new java.awt.Color(255, 255, 255));
            setIconifiable(true);
            setTitle("BCDE Objects");
            listScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            listScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            listScrollPane.setPreferredSize(new java.awt.Dimension(250, 150));
            objectTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Name", "Status"
                boolean[] canEdit = new boolean [] {
                    true, false
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
            objectTable.setColumnSelectionAllowed(true);
            listScrollPane.setViewportView(objectTable);
            jPanel1.add(listScrollPane);
            getContentPane().add(jPanel1);
            pack();
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane listScrollPane;
        private javax.swing.JTable objectTable;
        // End of variables declaration
    }and this is how i create the object in my JFrame:
    bcdeOW = new BCDEObjectWindow(this);
            bcdeOW.setLocation(400, 0);
            if (getDesktop() instanceof JDesktopPane) {
                ((JDesktopPane)getDesktop()).setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                ((JDesktopPane)getDesktop()).add(bcdeOW, JLayeredPane.PALETTE_LAYER);
            } else
                getDesktop().add(bcdeOW);Any help would be great. Thanks a lot.

    Rajb1 wrote:
    to get the table name to appear
    create a scollpane and put the table in the scrollpane and then add the the scollpane to the component:
    //declare
    scrollpane x;
    //body code
    scrollpane x - new scrollpane();
    table y = new table();
    getContentPane().add(x(y));What language is this in, the lambda calculus -- add(x(y))!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • Populating JTable from an XML file

    I am in search of some knowledge. I have been having difficulty implementing JTable with an XML file. I am trying to take my basic XML file and populate the cells of my JTable with this information in such a way that
    <entry FN="Robert" LN="Smith" STREET="2215 Bromley Park Drive" CITY="Winston-Salem" STATE="North Carolina" ZIP="27103" PHONE="919-434-4278"/>
    Is parsed correctly where FN will be in row 0, column firstName etc. . .
    Anyone have some advice?
    thank you!

    I am in search of some knowledge. I have been having difficulty implementing JTable with an XML file. I am trying to take my basic XML file and populate the cells of my JTable with this information in such a way that
    <entry FN="Robert" LN="Smith" STREET="2215 Bromley Park Drive" CITY="Winston-Salem" STATE="North Carolina" ZIP="27103" PHONE="919-434-4278"/>
    Is parsed correctly where FN will be in row 0, column firstName etc. . .
    Anyone have some advice?
    thank you!

  • JTable in JInternalFrame

    Hi,
    I am having a problem with editing cells in a JTable. I have initially created a table using a custom table model in a JFrame. Everything works as expected.
    Now that I have modified it so that the JFrame becomes a JInternalFrame inside my Desktop I have lost the ability to edit cells.
    I can still select individual cells, however no caret displays and no input from the keyboard is accepted.
    I don't understand why the ability to edit cells is lost whenever the table is in a JInternalFrame.
    Could someone explain or suggest why this would be happening.
    Thanks.

    Hi,
    Thanks for the quick reply.
    I tried them both but it didn't work and Yes everything is set to use a JDesktopPane.
    below is some of the code if that helps
    //This is the AbstractTableModel
    class MatrixTableModel extends AbstractTableModel
      private double[][] data = { {0.0} };
      public int getColumnCount()
        return data.length;
      public int getRowCount()
       return data.length;
       public Object getValueAt(int row, int col)
        return new Double(data[row][col]);     
       public boolean isCellEditable(int row, int col)
         return true;     
       public void setValueAt(Object value, int row, int col)
        double doubleVal;
        try
         doubleVal = new Double(value.toString()).doubleValue();       
         data[row][col] = Math.floor(doubleVal*1000 + .5) /1000;
         fireTableCellUpdated(row,col);
         fireTableCellUpdated(col,row);
        catch (NumberFormatException e)
          JOptionPane.showMessageDialog(null,"Input matrix can only contain real values");
       public void changeData(double A[][])
        data = A;
        mtm.fireTableStructureChanged();
    //The TableColumnModel I use
    TableColumnModel cm = new DefaultTableColumnModel()
    public void addColumn(TableColumn tc)
      tc.setMinWidth(50);
      tc.setMaxWidth(100);    
      seqEditor = new JTextField();     
      seqEditor.setMargin(new Insets(0,0,0,0));
      seqEditor.setHorizontalAlignment(SwingConstants.CENTER);
      seqCellEditor = new DefaultCellEditor(seqEditor);
      seqCellEditor.setClickCountToStart(1);
      tc.setCellEditor(seqCellEditor);
      super.addColumn(tc);
    //each are added as follows
        Matrix = new JTable(mtm);
        Matrix.setColumnModel(cm); The cells look as if they are selected - i.e. the rectangle outline is black when selected.
    I placed a message in the setValueAt method and i know that it is called whenever i select away from a selectd cell.
    Any ideas,
    Thanks

  • JTable wont refresh in JInternalFrame

    hello people
    my JTable wont refresh when iam using the form as an JInternalFrame, but if i use it as JFrame then the table will refresh, here is a bit of my code
    public void getTable()
              Statement sat;
              ResultSet rs;
              try {
                   int idx = queryType.getSelectedIndex();
                   String s = columnNames[idx];
                   JOptionPane.showMessageDialog(null, "yeah "+s);
                   String query = "SELECT * FROM College_Master " +
                                       " WHERE  ("+s+") ='" + typelist.getSelectedItem()+"'";
                   sat = connection.createStatement();
                   rs = sat.executeQuery(query);
                   displayResultSet(rs);
                   sat.close();
              catch(SQLException sqlex) {
                   sqlex.printStackTrace();
         public void displayResultSet (ResultSet rs)
                   throws SQLException
                   boolean moreRecords = rs.next();
                   if(! moreRecords){
                        JOptionPane.showMessageDialog(this, "No record to display. Please query again.");
                        setTitle("No records to dispaly");
                        return;
                   Vector columnHeads = new Vector();
                   Vector rows = new Vector();
                   try {
                        ResultSetMetaData rsmd = rs.getMetaData();
                        for(int i = 1;i<=rsmd.getColumnCount();i++)
                        columnHeads.addElement(rsmd.getColumnName(i));
                   do {
                             ctr2++;
                             rows.addElement (getNextRow(rs, rsmd));
                             JOptionPane.showMessageDialog(null, "here"+ctr2);
                        } while (rs.next());
                        table = new JTable(rows, columnHeads);
                        JScrollPane scroller = new JScrollPane(table);
                        scroller.setBounds(10,40,660,250);
                        c.add(scroller);//c is a panel
                        validate();
                   catch(SQLException sqlex) {
                        sqlex.printStackTrace();
         public Vector getNextRow (ResultSet rs, ResultSetMetaData rsmd)
                             throws SQLException
                   Vector currentRow = new Vector();
                   for (int i=1;i<=rsmd.getColumnCount();i++)
                   switch(rsmd.getColumnType(i)) {
                        case Types.VARCHAR:
                             currentRow.addElement (rs.getString(i));
                             break;
                        case Types.INTEGER:
                             currentRow.addElement(new Long(rs.getLong(i)));
                             break;
                        default:
                             System.out.println("Type was: " + rsmd.getColumnTypeName(i));
                   return currentRow;
              }whats wrong?
    asrar

    hello people
    my JTable wont refresh when iam using the form as an JInternalFrame, but if i use it as JFrame then the table will refresh, here is a bit of my code
    public void getTable()
              Statement sat;
              ResultSet rs;
              try {
                   int idx = queryType.getSelectedIndex();
                   String s = columnNames[idx];
                   JOptionPane.showMessageDialog(null, "yeah "+s);
                   String query = "SELECT * FROM College_Master " +
                                       " WHERE  ("+s+") ='" + typelist.getSelectedItem()+"'";
                   sat = connection.createStatement();
                   rs = sat.executeQuery(query);
                   displayResultSet(rs);
                   sat.close();
              catch(SQLException sqlex) {
                   sqlex.printStackTrace();
         public void displayResultSet (ResultSet rs)
                   throws SQLException
                   boolean moreRecords = rs.next();
                   if(! moreRecords){
                        JOptionPane.showMessageDialog(this, "No record to display. Please query again.");
                        setTitle("No records to dispaly");
                        return;
                   Vector columnHeads = new Vector();
                   Vector rows = new Vector();
                   try {
                        ResultSetMetaData rsmd = rs.getMetaData();
                        for(int i = 1;i<=rsmd.getColumnCount();i++)
                        columnHeads.addElement(rsmd.getColumnName(i));
                   do {
                             ctr2++;
                             rows.addElement (getNextRow(rs, rsmd));
                             JOptionPane.showMessageDialog(null, "here"+ctr2);
                        } while (rs.next());
                        table = new JTable(rows, columnHeads);
                        JScrollPane scroller = new JScrollPane(table);
                        scroller.setBounds(10,40,660,250);
                        c.add(scroller);//c is a panel
                        validate();
                   catch(SQLException sqlex) {
                        sqlex.printStackTrace();
         public Vector getNextRow (ResultSet rs, ResultSetMetaData rsmd)
                             throws SQLException
                   Vector currentRow = new Vector();
                   for (int i=1;i<=rsmd.getColumnCount();i++)
                   switch(rsmd.getColumnType(i)) {
                        case Types.VARCHAR:
                             currentRow.addElement (rs.getString(i));
                             break;
                        case Types.INTEGER:
                             currentRow.addElement(new Long(rs.getLong(i)));
                             break;
                        default:
                             System.out.println("Type was: " + rsmd.getColumnTypeName(i));
                   return currentRow;
              }whats wrong?
    asrar

  • Save jtable in xml

    hi,
    i have an application that create multiple jtable, and i want when the user click to save, the jtable will be save in a xml file.
    i know that's possible but i dont know how to do that.
    someone have an example or a good tutorial to teach how to do that????
    i will be very gratefull to any kind of help.

    Have u tried something like:
    For row major xml document:
    String xml = "";
    for(int i = 0; i < jt.getRowCount(); i++)
             xml+= "<row number = '" + i + "'>\n";
             for(int j = 0; j < jt.getColCount(); j++)
                      xml+= "       <col number = '" + j + "'>" + jt.getValueAt(i,j) + "</col>";
              xml += "</row>
    //Then save xml to file.For column major XML document just swap the two loops round.
    Hope this helps

  • Pass a xml file into a JTable

    I'm new to java and xml, I need to pass a xml file into a JTable.
    thanks

    That error about the package not existing probably means that your classpath is wrong. Is JDOM in a Jar file? If so, add it to the classpath on the command line:
    javac -classpath C:\JDOMPath\JDOM.jar;C:\MyClasses DescendantDemo.java(put whatever directories and jar files you need in the classpath).

  • 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

  • How to edit databases from JTable?

    Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable.
    I have the installer of an application which I made with Java SE called FuelStation.exe
    My class files are ready for sharing along with its source files.
    I have placed it in this location in my website:
    http://www.apachevista.com/alphaprojects/runfiles/
    It is complete with full details about databases, proposed mysql embed, and so on. Please see the file and notify me at [email protected]
    Here is my sample code:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
    // JDBC driver, database URL, username and password
    ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
    final String JDBC_DRIVER = bundle.getString("Driver");
    final String DATABASE_URL = bundle.getString("URL");
    final String USERNAME = bundle.getString("User");
    final String PASSWORD = bundle.getString("Password");
    // default query retrieves all data from authors table
    //static final String DEFAULT_QUERY = "SELECT authors.lastName, authors.firstName, titles.title, titles.editionNumber FROM titles INNER JOIN (authorISBN INNER JOIN authors ON authorISBN.authorID=authors.authorID) ON titles.isbn=authorISBN.isbn";
    final String DEFAULT_QUERY = bundle.getString("Query");
    private ResultSetTableModel tableModel;
    private JTextArea queryArea;
    static final int xOffset = 0, yOffset = 200;
    private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
    // create ResultSetTableModel and GUI
    public DisplayQueryResults() {  
    super("Sales of the Day",
    true, //resizable
    true, //closable
    true, //maximizable
    false);//iconifiable
    //...Create the GUI and put it in the window...
    //Set the window's location.
    setLocation(xOffset, yOffset);
    // create ResultSetTableModel and display database table
    try {
    // create TableModel for results of query SELECT * FROM authors
    tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
    USERNAME, PASSWORD, DEFAULT_QUERY);
    // set up JTextArea in which user types queries
    queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
    queryArea.setWrapStyleWord(true);
    queryArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(queryArea,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    // set up JButton for submitting queries
    JButton submitButton = new JButton("Submit Query");
    // create Box to manage placement of queryArea and
    // submitButton in GUI
    Box box = Box.createHorizontalBox();
    box.add(scrollPane);
    box.add(submitButton);
    // create JTable delegate for tableModel
    JTable resultTable = new JTable(tableModel);
    resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
    resultTable.setRowSelectionAllowed(true);
    resultTable.getModel().addTableModelListener(this); // step 3
    // place GUI components on content pane
    add(box, BorderLayout.NORTH);
    add(new JScrollPane(resultTable), BorderLayout.CENTER);
    // create event listener for submitButton
    submitButton.addActionListener(
    new ActionListener()
    // pass query to table model
    public void actionPerformed(ActionEvent event)
    // perform a new query
    try
    tableModel.setQuery(queryArea.getText());
    } // end try
    catch ( SQLException sqlException)
    JOptionPane.showMessageDialog(null,
    sqlException.getMessage(), "Database error",
    JOptionPane.ERROR_MESSAGE);
    // try to recover from invalid user query
    // by executing default query
    try {
    tableModel.setQuery(DEFAULT_QUERY);
    queryArea.setText(DEFAULT_QUERY);
    } // end try
    catch (SQLException sqlException2) {
    JOptionPane.showMessageDialog(null,
    sqlException2.getMessage(), "Database error",
    JOptionPane.ERROR_MESSAGE);
    // ensure database connection is closed
    tableModel.disconnectFromDatabase();
    System.exit(1); // terminate application
    } // end inner catch
    } // end outer catch
    } // end actionPerformed
    } // end ActionListener inner class
    ); // end call to addActionListener
    //...Then set the window size or call pack...
         setSize(750,300);
    setVisible(true); // display window
    } // end try
    catch (ClassNotFoundException classNotFound) {
    JOptionPane.showMessageDialog(null,
    "MySQL driver not found", "Driver not found",
    JOptionPane.ERROR_MESSAGE);
    System.exit(1); // terminate application
    } // end catch
    catch (SQLException sqlException) {
    JOptionPane.showMessageDialog(null, sqlException.getMessage(),
    "Database error", JOptionPane.ERROR_MESSAGE);
    // ensure database connection is closed
    tableModel.disconnectFromDatabase();
    System.exit(1); // terminate application
    } // end catch
    // dispose of window when user quits application (this overrides
    // the default of HIDE_ON_CLOSE)
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    // ensure database connection is closed when user quits application
    addInternalFrameListener(
    new InternalFrameAdapter() {
    // disconnect from database and exit when window has closed
    public void windowClosed(WindowEvent event) {
    tableModel.disconnectFromDatabase();
    System.exit(0);
    } // end method windowClosed
    } // end WindowAdapter inner class
    ); // end call to addWindowListener
    } // end DisplayQueryResults constructor
    public void tableChanged(TableModelEvent e) { // step 4
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object tableModel = model.getValueAt(row, column);
    // Do something with the data...
    System.out.println(tableModel);
    System.out.println("data");
    // execute application
    public static void main(String args[]) {
    new DisplayQueryResults();
    } // end main
    } // end class DisplayQueryResults
    My question is in lines 177-187:
    public void tableChanged(TableModelEvent e) { // step 4
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object tableModel = model.getValueAt(row, column);
    // Do something with the data...
    System.out.println(tableModel);
    System.out.println("data");
    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?
    If this is Flash, Things can be done easily, but this is Java, and I dont know much about this language. I admit that I am new to this -intirely new.
    PS:
    When you have solved the problem, please notify me with the code that's changed
    and please share it to others if you like so.
    Best Wishes: Oliver Bob Lagumen
    Email: [email protected]
    website: www.apachevista.com
    Oliver Bob Lagumen
    Edited by: Oliverbob on Jan 24, 2008 9:03 PM

    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?What does happen when you click on the cells?
    Does the ResultSetTableModel report the cells as editable? If not you will never get to edit their contents, and so the table's model won't change, and so the table model listener will never get invoked.
    When you post code here use the code tags. Basically you put {code} at the start of your code and again at the end. That way the code will be readable.
    Try to post minimal examples with which others can reproduce your problem. In this case "minimal" would involve removing or drastically simplifying a lot of the GUI stuff which is just noise. But "reproduce" would involve including the ResultSetTableModel.
    When you have solved the problem, please notify me with the code that's changedAvoid this.
    What you say here is quite possibly not what you mean. But, in any event, while there might be plenty of interest in helping with specific problems there will likely be none in writing your code. Your problem remains yours. But your solution and your code - prompted by whatever help you might recieve - will also be yours.

  • JPopupMenu with JInternalFrame, popup menu doesn't work

    hi, i have this problem, as shown in the sample code at the end of this post.. basically, i have a table, and i added a JPopupMenu onto the table.. the popup menu works well when running the table class, though, when i call the table class in a JInternalFrame environment, the popup menu won't work.. anyone know why?
    ///Basic sample table code, when run this alone, the popup menu will work
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableBasic extends JPanel
         private JTable table;
         public TableBasic()
              String[] columnNames = { "Date", "String", "Integer", "Boolean" };
              Object[][] data =
                   {  { new Date(), "A", new Integer(1), Boolean.TRUE },
                        { new Date(), "B", new Integer(2), Boolean.FALSE },
                        { new Date(), "C", new Integer(9), Boolean.TRUE },
                        { new Date(), "D", new Integer(4), Boolean.FALSE}
              table = new JTable(data, columnNames)
                   //Returning the Class of each column will allow different
                   //renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
         public void createPopupMenu()
              JMenuItem menuItem;
              //Create the popup menu.
              JPopupMenu popup = new JPopupMenu();
              menuItem = new JMenuItem("A popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              menuItem = new JMenuItem("Another popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              //Add listener to the text area so the popup menu can come up.
              MouseListener popupListener = new PopupListener(popup);
              table.addMouseListener(popupListener);
         public static void main(String[] args)
              JFrame frame = new JFrame();
              TableBasic table = new TableBasic();
              table.createPopupMenu();
              frame.setContentPane(table);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              //frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         class PopupListener extends MouseAdapter
              JPopupMenu popup;
              PopupListener(JPopupMenu popupMenu)
                   popup = popupMenu;
              public void mousePressed(MouseEvent e)
                   maybeShowPopup(e);
              public void mouseReleased(MouseEvent e)
                   maybeShowPopup(e);
              private void maybeShowPopup(MouseEvent e)
                   if (e.isPopupTrigger())
                        popup.show(e.getComponent(), e.getX(), e.getY());
    ///when integrate the previous table into here, popup menu won't work
    import java.awt.*;
    import javax.swing.*;
    public class InternalFrameBasic
         extends JFrame
         //implements ActionListener
         private JDesktopPane desktop;
         private JInternalFrame menuWindow;
         public static final int desktopWidth = 800;
         public static final int desktopHeight = 700;
         public InternalFrameBasic(String title)
              super(title);
              //Set up the GUI.
              desktop = new JDesktopPane();
              desktop.putClientProperty("JDesktopPane.dragMode", "outline");
              //Because we use pack, it's not enough to call setSize.
              //We must set the desktop's preferred size.
              desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
              setContentPane(desktop);
              createMenuWindow();
              desktop.add(menuWindow); //DON'T FORGET THIS!!!
              Dimension displaySize = menuWindow.getSize();
              menuWindow.setSize(desktopWidth, displaySize.height);
         private void createMenuWindow()
              menuWindow =
                             new JInternalFrame("Event Watcher", true, //resizable
                                                                                                   true, //closable
                                                                                                   false, //not maximizable
                                                                                                   true); //iconifiable
              menuWindow.setContentPane(new TableBasic());
              menuWindow.pack();
              menuWindow.setVisible(true);
          * Create the GUI and show it.  For thread safety,
          * this method should be invoked from the
          * event-dispatching thread.
         private static void createAndShowGUI()
              //Make sure we have nice window decorations.
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new InternalFrameBasic("Example Internal Frame");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args)
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        createAndShowGUI();
    }

    table.createPopupMenu();The above line should not be in the main method. It should be in the constructor class of TableBasic.
    You never execute that method in your InternalFrameBasic class to the mouse listener never gets added to the table.

  • How to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • Java Logging, problem recreating Thrown record from XML

    Ok, so I've got all these log files that are using the default java.util.logging.XMLFormatter so all the output is in XML. I'm writing a parser that reads the XML file and recreates LogRecord objects for each of the record entries. Everything works great until I come up to a logged exception. The entire stack trace information is stored in the XML file, but there doesnt seem to be any way to create new StackTraceElement objects. I can create a new Exception object and give it a message, and I could even set the stack trace if I could just generate some StackTraceElement objects. There are no public constructors for StackTraceElement and the class is final so I can't simply subclass it with my own. Basically I would like to be able to recreate the thrown Object so I can call record.setThrown(thrown); but so far it doesn't look like that is possible.
    I guess the other way to go is to just make my own data objects to represent the log record and the thrown exception, but I would really like to avoid that and just use the classes already available. Has anyone ever tried this before? I can't have been the only one.

    I'd like to recreate a LogRecord object simply because that is what is used to create the XML file and I guess I'm just trying to be consistent :)
    Here is the overall process:
    1. User selects which XML file to open
    2. Parse the log file generating LogRecord objects for each entry.
    3. Display a JTable to the user with rows for each LogRecord, columns for Logging Level, time, message etc.
    4. If the user double clicks on a row, open a dialog with more detailed info about the LogRecord, including a stack trace if it was included.
    Now see, I want to just be able to grab the Throwable object off the LogRecord in step 4 and call getStackTrace() to get an array of StackTraceElements so I can print those into a JTextArea to display to the user. However, if I gotta be able to set the damn stack trace elements of the Throwable object first. :(

Maybe you are looking for

  • Error while looking up bean from Eclipse plugin

    Hi all,    I am developing an Eclipse plugin which calls session bean deployed in some j2ee engine. But I am facing a problem while I try to look up the bean. It gives me an error saying <i>"com.sap.engine.services.jndi.persistent.UnsatisfiedReferenc

  • How to see inserted rows using load csv data

    Hey all... I am using apex 3.1 and I want to know how can I see non failed rows when I insert data from an CSV file. the failed rows that I can see are the the ones that shows in the next case: Uploading data that already exists and having a primary

  • Leap Year and Schema & Rules on Time Management

    Hello, On Time management, do you know how to configure on Schema & Rules if the year is a leap year? Thanks, julien Edited by: Julien on May 6, 2009 6:33 PM

  • Is 10.4.8 safe now?

    Is 10.4.8 safe now? I'm on 10.4.7 and was going to update a few weeks back, but did not as there appeared (on forums) to be lots of issues with 10.4.8. Is it safe and sorted now? anyone give feedback of an okay update or should I hold out for another

  • What J2EE engine for SAP NetWeaver 7.0 (2004s) Trial Version - Full Java Ed

    Hi experts, I am installing SAP NetWeaver 7.0 (2004s) Trial Version - Full Java Edition. For that 1.what J2EE engine sholud be installed? 2.where is it available? 3.give Installation procedure for this. They have given it as trial version will it exp