Re: Using JScrollPane With JTable

>
myNamePane.setVisible(true);This is meaningless, a component becomes visible by default when you add it to a visible container
if(e.getSource().equals(newStudent))
       JFrame newFrame = new JFrame("Please select a student");
       newFrame.setContentPane(myNamePane);
       newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       newFrame.setResizable(false);
       newFrame.pack();
       newFrame.setVisible(true);
     }Which brings us to the main issue, you need to add the JScrollPane to you frame
newFrame.add(myNamePane);Read the tutorial: [Using Top-Level Containers|http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html]

Hello Rodney,
Thanks for the information and the tutorial.. I've worked with containers before but never got around to reading that one, which has clarified a few things for me.
Unfortunately however, my problem persists. I obviously can't set the content pane as the JScrollPane and add it to the Frame, so rather than setting the JScrollPane as the content pane (which I did previously), I added it to the frame as you suggested:
if(e.getSource().equals(newStudent))
     JFrame newFrame = new JFrame("Please select a student");
//     newFrame.setContentPane(myNamePane);
     newFrame.add(myNamePane);
     newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     newFrame.setResizable(false);
     newFrame.pack();
     newFrame.setVisible(true);
}But the same thing happens! All I see is a new, empty JFrame. I feel like my understanding of the JScrollPane may be flawed, but I'm really not sure :/
Edit: In fact, it is most definitely a problem either with my JTable or my JScrollPane. I used the setPreferredSize() method to check if the JScrollPane was being displayed in the JFrame, and it is. There is no JTable in the pane however.
Edit #2: The problem was, in fact, with my JTable. The ResultSet I was using was TYPE_FORWARD_ONLY, and I was trying to call studentNameSet.first(), which prevented the JTable from ever being created. Thanks for your help, Rodney. Although I do have one more question.. Do you know a better way for me to find the number of student names given that ResultSet? I can't iterate through it twice as I had done earlier, so now for testing purposes I've simply hardcoded the number in, but I'd rather have the program find the total number of entries dynamically.
Edited by: Pheer on Jul 22, 2008 10:07 AM
Edited by: Pheer on Jul 22, 2008 10:09 AM

Similar Messages

  • Plz tell me how to use JSpinner with JTable

    I have retrieve records from database but as the number of records(rows) are more than 1000 , i want to use JSpinner with JTable . plz solve my problem by giving the appropriate code for the same.

    hi
    check this links
    http://www.exampledepot.com/egs/javax.swing.table/CustRend.html
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    hope this will help you.. this explains exactly what you want.
    regards
    Aniruddha

  • Use JSpinner with JTable

    I have retrieve records from database but as the number of records(rows) are more than 1000 , i want to use JSpinner with JTable. How can i do so?

    you can start by being more clear on what your requirements are.

  • Error using JTextArea with JScrollPane

    hi,
    I am using JTextArea with JScrollpane. I am getting a problem in selecting the text in text area. I am searching for some text in the text area and selecting it if search successful. The problem is that the the scrollbar position didnt set to the correct location. So sometime the text selected is not visible in the scrolpane. Any help regarding this will be highly appreciated.
    Regards
    Danish

    What about sth like this:Rectangle r = textarea.modelToView(textarea.getSelectionStart());
    scrollpane.scrollRectToVisible(r);Just a guess, no idea whether it works.

  • JComboBox With JTable as Editor

    Hi everybody
    I'm working with JTable and having a ComboBox as first CellEditor. for that purpose i used following code
            cmbFeeType.setModel(new javax.swing.DefaultComboBoxModel(DefaultFee.FeeTypeItemList()));       
            DefaultCellEditor DCEFeeType = new DefaultCellEditor(cmbFeeType);
            DCEFeeType.setClickCountToStart(2);here DefaultFee.FeeTypeItemList is a vector returns array. This is working fine except that the ComboBox remains visible till I dobule clik on a column for editing. Then It becomes invisible and works fine.
    my JComboBox is a seperate Control on a JFrame I do not want to use
    Class FeeTypeEditor extends JComboBox implements TableCellEditoras a ComboBox editor for JTable
    Please Help Me.

    Hi
    I am giving u a sample code which simulate the error
    * TestJTable.java
    * Created on August 5, 2008, 11:05 AM
    package TestJTable;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableColumn;
    * @author  yogi
    public class TestJTable extends javax.swing.JFrame {
        /** Creates new form TestJTable */
        public TestJTable() {
            initComponents();
            DefaultCellEditor ColumnEditor = new DefaultCellEditor(jComboBox1);
            ColumnEditor.setClickCountToStart(2);
            TableColumn column = jTable1.getColumnModel().getColumn(0);
            column.setCellEditor(ColumnEditor);       
        /** 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">//GEN-BEGIN:initComponents
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            getContentPane().setLayout(null);
            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"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1);
            jScrollPane1.setBounds(10, 10, 340, 180);
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            getContentPane().add(jComboBox1);
            jComboBox1.setBounds(180, 220, 120, 20);
            pack();
        }// </editor-fold>//GEN-END:initComponents
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    TestJTable TJTable = new TestJTable();
                    TJTable.setExtendedState(MAXIMIZED_BOTH);               
                    TJTable.setVisible(true);
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration//GEN-END:variables
    }Above code is generated by Netbeans IDE 6.0
    My promblem is that when you run the code the combobox JComboBox1 remains visible till i starts to edit the Table after once started editing it disappears.
    I want to avoid this
    thanks in advance

  • Help please with Jtable

    HI
    I'm having problems
    I have a frame that has a textField, button, label.
    The button is used to diplay the Jtable which has the resultSet.
    My query is:
    String query = "SELECT personID, firstName, surname FROM Person where firstName = '" + jTxtTest.getText() + "'";
    If I enter Gita in the textField and press the button it should display the personID, firstName, surname where firtsname = Gita
    in the Jtable and also display Gita in the label.
    But it only display Gita in the Label but noting in the Jtable.
    What am i doing wrong?????
    public class Frame1 extends JFrame {
    JPanel contentPane;
    BorderLayout borderLayout1 = new BorderLayout();;
              String driver="sun.jdbc.odbc.JdbcOdbcDriver";
              String url="jdbc:odbc:myDatabase";
              String tempname = "";
              int tempcnt;
              JTabbedPane tabbedPane = new JTabbedPane();
              Object[] data = new Object[20];
              DefaultTableModel defaulttablemodel = new DefaultTableModel();
              JTable jtable = new JTable(defaulttablemodel);
    JPanel p1 = new JPanel();
    JTabbedPane jTabbedPane1 = new JTabbedPane();
    JPanel jPanel1 = new JPanel();
    JTextField jTxtTest = new JTextField();
    JButton jButton1 = new JButton();
    JLabel jLabel1 = new JLabel();
    /**Construct the frame*/
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    setup();
    contentPane = (JPanel) this.getContentPane();
    this.setSize(new Dimension(554, 532));
    this.setTitle("Frame Title");
    jPanel1.setLayout(null);
    jTxtTest.setBounds(new Rectangle(53, 20, 208, 33));
    jButton1.setText("jButton1");
    jButton1.setBounds(new Rectangle(314, 19, 130, 36));
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jButton1_actionPerformed(e);
    jLabel1.setBounds(new Rectangle(462, 23, 82, 20));
    contentPane.add(jTabbedPane1, BorderLayout.CENTER);
    jTabbedPane1.add(jPanel1, "jPanel1");
    jPanel1.add(jTxtTest, null);
    jPanel1.add(jButton1, null);
    jPanel1.add(jLabel1, null);
    void setup()
                   setupMenuBar();
                   showpane1();
                   //contentPane.add(tabbedPane, BorderLayout.CENTER);
              //------------------------------------------------------------ End setup -----------------
              //============================================================ Start setupMenuBar ========
              void setupMenuBar()
                   MenuBar menuBar = new MenuBar();
                   Menu fileMenu = new Menu("File");
                             MenuItem fileExit = new MenuItem("Exit");
                                  fileExit.addActionListener(new MenuItemHandler());
                                  fileMenu.add(fileExit);
    MenuItem filePrev = new MenuItem("Preview");
                                  filePrev.addActionListener(new MenuItemHandler());
                                  fileMenu.add(filePrev);
                             menuBar.add(fileMenu);
                   setMenuBar(menuBar);
              //------------------------------------------------------------ End setupMenuBar-----------
              //============================================================ Start showpane1 =========
              void showpane1() // REPORTS TAB WITH JTABLE
                   p1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Student Reports 1"));
    p1.setBounds(new Rectangle(28, 70, 513, 429));
    try
                             Class.forName(driver);
                             Connection connection=DriverManager.getConnection(url);
                             Statement statement = connection.createStatement();
                             String query = "SELECT personID, firstName, surname FROM Person where firstName = '" + jTxtTest.getText() + "'";
                             ResultSet rs = statement.executeQuery(query);
    if (rs == null)
    System.out.println("cannot execute query");
                             ResultSetMetaData rmeta = rs.getMetaData();
                             int numColumns=rmeta.getColumnCount();
    for(int i=1;i<=numColumns;++i)
                                  if(i<=numColumns)
                                       defaulttablemodel.addColumn(rmeta.getColumnName(i));
                             while(rs.next())
                                  for(int i=1;i<=numColumns;++i)
                                       if(i<=numColumns)
                                            tempname = rs.getString(i);
                                            tempcnt=i-1;
                                            data[tempcnt] = tempname;
                                  defaulttablemodel.addRow(data);
                   catch(Exception ex)
         p1.add(new JScrollPane(jtable));
              //------------------------------------------------------------ End showpane1 ------------
              //=========================================================== START MenuItemHandler ======
              class MenuItemHandler implements ActionListener
                   public void actionPerformed(ActionEvent ev)
                        String s=ev.getActionCommand();
                        if(s=="Exit")
                        System.exit(0);
    else if (s=="Preview")
    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton1_actionPerformed(ActionEvent e) {
    jLabel1.setText(jTxtTest.getText());
    jPanel1.add(p1);
    contentPane.repaint();
    }

    Hi,
    Seems u r new to progrmming.Well u used Jbuilder to write.U wrote good debug statments but forgot to write deubg statment or printstacktrace in excpetions.
    ok here is answer for ur problem.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class Frame1 extends JFrame {
    JPanel contentPane;
    BorderLayout borderLayout1 = new BorderLayout();;
    String driver="org.gjt.mm.mysql.Driver";
    String url="jdbc:mysql://thienpo-app.thienpo.com/jps";
    String user="";
    String pass="";
    String tempname = "";
    int tempcnt;
    boolean firstTime=false;
    JTabbedPane tabbedPane = new JTabbedPane();
    Object[] data = new Object[20];
    DefaultTableModel defaulttablemodel = new DefaultTableModel();
    JTable jtable = new JTable(defaulttablemodel);
    JPanel p1 = new JPanel();
    JTabbedPane jTabbedPane1 = new JTabbedPane();
    JPanel jPanel1 = new JPanel();
    JTextField jTxtTest = new JTextField();
    JButton jButton1 = new JButton();
    JLabel jLabel1 = new JLabel();
    /**Construct the frame*/
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    setupMenuBar();
    contentPane = (JPanel) this.getContentPane();
    this.setSize(new Dimension(554, 532));
    this.setTitle("Frame Title");
    jPanel1.setLayout(null);
    jTxtTest.setBounds(new Rectangle(53, 20, 208, 33));
    jButton1.setText("jButton1");
    jButton1.setBounds(new Rectangle(314, 19, 130, 36));
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jButton1_actionPerformed(e);
    jLabel1.setBounds(new Rectangle(462, 23, 82, 20));
    contentPane.add(jTabbedPane1, BorderLayout.CENTER);
    jTabbedPane1.add(jPanel1, "jPanel1");
    jPanel1.add(jTxtTest, null);
    jPanel1.add(jButton1, null);
    jPanel1.add(jLabel1, null);
    this.setVisible(true);
    //------------------------------------------------------------ End setup -----------------
    //============================================================ Start setupMenuBar ========
    void setupMenuBar()
    MenuBar menuBar = new MenuBar();
    Menu fileMenu = new Menu("File");
    MenuItem fileExit = new MenuItem("Exit");
    fileExit.addActionListener(new MenuItemHandler());
    fileMenu.add(fileExit);
    MenuItem filePrev = new MenuItem("Preview");
    filePrev.addActionListener(new MenuItemHandler());
    fileMenu.add(filePrev);
    menuBar.add(fileMenu);
    setMenuBar(menuBar);
    //------------------------------------------------------------ End setupMenuBar-----------
    //============================================================ Start showpane1 =========
    void showpane1() // REPORTS TAB WITH JTABLE
    p1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Student Reports 1"));
    p1.setBounds(new Rectangle(28, 70, 513, 429));
    try
    Class.forName(driver);
    Connection connection=DriverManager.getConnection(url,user,pass);
    Statement statement = connection.createStatement();
    String query = "SELECT personID, firstName, surname FROM Person where firstName = '" + jTxtTest.getText() + "'";
    System.out.println(" query"+query);
    ResultSet rs = statement.executeQuery(query);
    if (rs == null)
    System.out.println("cannot execute query");
    System.out.println(" query"+query);
    ResultSetMetaData rmeta = rs.getMetaData();
    int numColumns=rmeta.getColumnCount();
    if( !firstTime){
    for(int i=1;i<=numColumns;++i)
    if(i<=numColumns )
    defaulttablemodel.addColumn(rmeta.getColumnName(i));
    firstTime=true;
    while(rs.next())
    for(int i=1;i<=numColumns;++i)
    if(i<=numColumns)
    tempname = rs.getString(i);
    tempcnt=i-1;
    data[tempcnt] = tempname;
    defaulttablemodel.addRow(data);
    catch(Exception ex)
    System.out.println("***********************"+ex);
    p1.add(new JScrollPane(jtable));
    public static void main(String[] args){
         new Frame1();
    //------------------------------------------------------------ End showpane1 ------------
    //=========================================================== START MenuItemHandler ======
    class MenuItemHandler implements ActionListener
    public void actionPerformed(ActionEvent ev)
    String s=ev.getActionCommand();
    if(s=="Exit")
    System.exit(0);
    else if (s=="Preview")
    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton1_actionPerformed(ActionEvent e) {
    jLabel1.setText(jTxtTest.getText());
    showpane1();
    jPanel1.add(p1);
    contentPane.repaint();
    sreeni,
    [email protected]

  • No scrollbar with JTable

    Hello!!
    I'm working with JTable, and that table is larger than the JFrame. I want to attach a scrollbar onto it so that entire table can be viewable...I used JScrollPane in NetBeans.. but it is not working....
    is there any way out???
    plz help!!!
    thanks in adv..

    There's a well known deficiency in JTable that prevents horizontal scrollbars from appearing depending on the specific display options indicated for the JTable instance.
    Some searching the bug database should provide information and a workaround.

  • Mouselistner is not working with jtable in the browser

    Hi
    I am having a problem with jTable.
    I added a mouselistener to table header to sort table but when i run that applet from my netbean ide it works fine but when i run that applet in my browser it doesn't work, i have tested, its not even generate mouseclick event .Please help me guys.
    I call this function after calling initComponents() method of JApplet.
    public void setTableAction()
    //set mouselistener to sort table on click of table header
    final JTableHeader head= jTable1.getTableHeader();
    head.addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseClicked(java.awt.event.MouseEvent evt)
    Vector data= ((DefaultTableModel)jTable1.getModel ()).getDataVector();
    sortTable(data, head.columnAtPoint(evt.getPoint()));
    //set action map to change the default action performed for enter key pressed
    InputMap imap = jTable1.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    KeyStroke tabKey = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    final Action oldAction= jTable1.getActionMap().get(imap.get(tabKey)); // get map to set enter key.
    imap.put(enterKey, "enter"); // set enter key
    Action newAction = new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
    oldAction.actionPerformed(e);
    JTable table= (JTable)e.getSource();
    table.changeSelection(0,0,false,false);
    if(table.isCellEditable(0,0))
    String sTemp= (String)table.getValueAt(0,0);
    if(sTemp.length()>0) {
    if(bRenewItem)
    retrieveRcodeDetails("",sTemp);
    else
    processRCodeDetails(sTemp, e);
    }else
    table.editCellAt(0,0);
    jTable1.getActionMap().put("enter", newAction);
    jTable1.setPreferredScrollableViewportSize(jTable1.getPreferredSize());
    }

    Hi,
    I also am using the Bépo layout with an encrypted drive and encountered the same problem: the Return key does not work.
    It seems to work fine if you use the fr-bepo-latin9 keymap.
    # /etc/vconsole.conf
    KEYMAP=fr-bepo-latin9
    But I also looked at the files /usr/share/kbd/keymaps/i386/bepo/fr-bepo.map.gz and /usr/share/kbd/keymaps/i386/bepo/fr-bepo-latin9.map.gz (you can open gzipped files in vim directly). fr-bepo-latin9.map.gz defines keycode 28 (Return) but fr-bepo.map.gz does not.
    I modified fr-bepo.map.gz:
    # vim /usr/share/kbd/keymaps/i386/bepo/fr-bepo.map.gz # Append that line : "keycode 28 = Return".
    # mkinitcpio -p linux # Rebuild the initramfs.
    The Return key now works, but the Backspace (14, "Delete") and Shift (54) keys don’t work. I found that both the cf.map.gz (french canadian layout) and fr-bepo-latin9.map.gz files define those keycodes as well as other non-printing keys so I copied the following lines from fr-bepo-latin9.map.gz to fr-bepo.map.gz:
    keycode 1 = Escape Escape
    keycode 14 = Delete Delete
    keycode 15 = Tab Tab
    keycode 28 = Return
    keycode 29 = Control
    keycode 42 = Shift
    keycode 54 = Shift
    keycode 56 = Alt
    keycode 58 = Caps_Lock
    keycode 97 = Control
    It works! Don’t forget to rebuild the initramfs after you change the keymap file.
    # mkinitcpio -p linux
    I will send a message to the kbd and bépo projects mailing lists and report back.

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

  • Any body please can solve my problem that iam facing with JTable

    Dear sir,
    Iam doing an educational product using Swing as front end in that
    iam using JTables. And back end iam using sqlserver. With jtable iam
    facing very serious problem the problem is actually iam entering the values
    in all the columns after that iam pressing the save button its not
    saving but if i click on any of the columns and try to save its saving.
    please anybody can solve my problem.Please if a piece of code is there ill
    be very thankful to you. my mailid is [email protected]
    regards
    surya

    The problem is, the cellEditor does not know that editing has stopped and therefore has not updated the model (where the data actually resides). When you click off the cell to another cell, the first cell knows it must be done editing because you are leaving it. If you click a button (or anything other than another cell), the cell being edited has no knowledge of this. You need to call stopCellEditing() on the cell editor and your problem will be solved. To do this, put the following method into your code and call it when you click the button to clear, save or whatever you need to do.
    public void ceaseEditing() {    int row = this.getEditingRow();
      int col = this.getEditingColumn();
      if (row != -1 && col != -1)
        this.getCellEditor(row,col).stopCellEditing(); 
      }Hope this helped...

  • JScrollPane with scrollbar as needed packs to the wrong size.

    Hi!
    I just noticed a strange problem when packing a JScrollPane with scrollbar policy "as needed" and wondered if it's me or if it is a real bug in Swing.
    I create a JFrame with a JScrollPane in it and a JPanel as viewportview. The JPanel (called "stuffPanel") contains a few components which give it a preferred size, and the JScrollPane is set to grow as needed if the window grows. A button in the center of the stuffPanel will invoke pack() on the window when clicked.
    Now, if I resize the window such that the JScrollPane can't display the entire stuffPanel, I get scrollbars as expected. If I click the pack button the window correctly resizes to the preferred size (without scrollbars).
    On the other hand, if I resize the window to become larger than the preferred size and then click the pack button, the window (and the stuffPanel) is resized to include 17 pixels of extra size around the edges.
    Put simply, pack() will resize the JPanel to different sizes depending on whether the scrollbars of the JScrollPane were visible at the time. Note that this only occurs when you're using the "scrollbars as needed" scrollbar policy.
    An even more interesting situation occurs if you resize the window to include (for example) only horizontal scrollbars and then packs the window repeatedly...
    Code for a Java app which displays the strange behaviour is included below:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestJScrollPane {
      static {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch (Exception e) { }
      private JFrame mainWindow;
      public TestJScrollPane() {
        mainWindow = createMainWindow();
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainWindow.pack();
        mainWindow.show();
      public JFrame createMainWindow() {
        JFrame window = new JFrame("Test of scrollpane");
        window.getContentPane().setLayout(new GridBagLayout());
        final JPanel stuffPanel = new JPanel();
        stuffPanel.setBorder(BorderFactory.createTitledBorder("Collection of stuff"));
        stuffPanel.setLayout(new GridBagLayout());
        JLabel stuffLabel = new JLabel("A label");
        JTextField stuffField = new JTextField(10);
        JButton stuffButton = new JButton("Pack the window");
        JList listOfStuff = new JList();
        listOfStuff.setListData(new String[] {"Fish", "Bird", "Mammal", "Insect", "Spider"});
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        stuffPanel.add(stuffLabel, gbc);
        gbc.gridx = 1;
        stuffPanel.add(stuffField, gbc);
        gbc.gridy = 1;
        gbc.gridx = 0;
        gbc.gridwidth = 2;
        stuffPanel.add(stuffButton, gbc);
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.BOTH;
        stuffPanel.add(listOfStuff, gbc);
        final JScrollPane scroller = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroller.setViewportView(stuffPanel);
        gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1;
        gbc.weighty = 1;
        window.getContentPane().add(scroller, gbc);
        stuffButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            mainWindow.pack();
            System.out.println("Stuff panel size: " + stuffPanel.getSize());
            System.out.println("Stuff panel preferred size:" + stuffPanel.getPreferredSize());
            System.out.println("Scroller size: " + scroller.getSize());
            System.out.println("Scroller preferred size: " + scroller.getPreferredSize());
        return window;
      public static void main(String[] args) {
        new TestJScrollPane();
    }

    Why would the JScrollPane be as big as the entire
    frame when you added 800x600 panels on all sides of
    it? It's going to be in the center surrounded by
    huge panels. Thanks, kablair. However, if you look at the code, these panels are not 800x600 on all sides. The north and south panels only add a combined height of 100, and the east and west panels only add a combined width of 100. so the whole window, minus insets, should be 900x700.
    Anyway, i took the advice of the guy above, and that has gotten me much closer. In the bigger app that I'm trying to calculate the size, now I'm only 2 pixels away from the true size, although I can't figure out what I'm forgetting.

  • Problems with JTABLEs

    How can I make a non editable JTable? And...
    How can I set the columns in my JTable to not be reorganizable?
    I'd like someone to help me if posible.
    Thanks.
    Y si me lee alguien que sepa espa�ol, mi problema es:
    En mi aplicaci�n uso una JTable dentro de un ScrollPane y luego visualizo la JTable que contiene unos datos que he leido de una base de datos. �Com� puedo hacer para impedir que las celdas de la tabla se puedan editar? Y... �C�mo impido que las columnas de la tabla se puedan reorganizar usando el rat�n?
    Muchas gracias a todos.
    Saludos.

    Hi,
    you should not be afraid of this column repositioning feature - the columns in your table model (your data) do not change this way - they stay on their postions, but you will have to use the getValueAt(...) method of the table model with your model indices, not that one of the JTable class, which uses column model indices.
    Say, if you only want a JTable to be not editable and you have used the constructor
    JTable jt = new JTable(myDataArray,myColumnNames);
    to create it from an Object[][] and a String[] - you can simply use an inner class to achieve this:
    DefaultTableModel m = new DefaultTableModel(myDataArray,myColumnNames) {
    public boolean isCellEditable(int row,int column) { return false; }};
    JTable jt = new JTable(m);
    to retrieve cell data from this model use:
    Object obj = m.getValueAt(row,column);
    See the documentation of DefaultTableModel for more information
    greetings Marsian

  • Issue with JTable

    Hi,
    I have a issue with JTable. I am reading an array and populating the cells in the JTable. After editing the cell values, on clicking a button, I update the value in to an array. The probelm is that after editing the value in the cell, if I don't use tab or enter key and move the focus away from the cell, I dont get the updated value when using the getValueAt method. Pleease let me know if there is any workaround for this behaviour.
    Thanks,
    Baskar N

    Just so you understand why that code snippit works, you have to stop or cancel editing before you can get the updated value of a cell.

  • Where can I find a JClient demo with JTable ?

    Hi,
    Where can I find a good JClient demo with JTable and Bc4J?
    Thanks
    Friedhold

    Friedhold,
    there exist a JTable example on otn.oracle.com/products/jdev
    For example ther exists a component binding demo
    http://otn.oracle.com/sample_code/products/jdev/jclient/JClientBindingDemo.zip
    that also shows a table
    and a sorter demo that shows how to sort JTables with JClient
    http://otn.oracle.com/sample_code/products/jdev/jclient/TableSorter.zip
    Finally, a demo that shows how to replace a table cell by a combo box using the table cell renderer
    http://otn.oracle.com/sample_code/products/jdev/jclient/JTableCombo.zip
    Frank

  • Another problem with JTable

    Hi,
    I have encountered a problem with JTable, i am trying to display some 15 columns and their values , one of the columns value is null, then the JTable is not displaying its value from this column(which is with null value) onwards.
    Can anybody assiss me in this matter.
    Regards
    khiz_eng

    I don't know If I can fix your problem, but
    I know just that it works on my PC.... It's very very
    slow... I don't know how to insert PageSetUp option... I have to study the problem.....
    However I don't think it's a hard problem....
    I want ask to you if you have found some problems when you are in Editing mode in a cell.....
    in the jdk1.2 version I could save while was in editing mode using the editingStopped method.
    It permit to update all data .... also the data in the cell I was editing.
    in the jdk 1.3 if I use this method It doesn't work properly... It maybe destroy the content object in the Cell..... because I'm able to print all the table except the editing cell (it throw an exception...)
    What's changed????
    I don't know...
    Can u help me?

Maybe you are looking for

  • How do I get my PC laptop to print to my printer?

    I have my USB printer connected to my Airport Express network. It works fine from my iBook and my iMac. But although my PC laptop gets on the internet just fine, I cannot print. I have the idea that there is something about a printer port setup and a

  • Anyone had a problem with Micro/Smart sims not fitting in the Iphone 4s Tray?

    Just got the Iphone 4s did the whole process of cutting up an original sim to fit, finally went to the phone shop to get a Micro sim just incase the cut sim was doing damage or not fitting correctly only to find that the Micro sims wont fit into my 4

  • Error 1034 when trying to save.

    I was going to post this in the Bug Report form but Adobe Muse isn't listed. The error is simple, when I attempt to save my progress, I get this error. "Error #1034:cannot convert...." as pictured below. After clicking OK the program crashes. When I

  • Why i can't add a credit card

    It keeps coming up as can't verify card please help as there is nothing wrong with my card

  • CreateODBCDate and cfqueryparam with cf_sql_date

    Hi all. I've got a form that's accepting the following date formats (YYYY-MM-DD and MM-DD-YYYY). Just wondering if it's even necessary to use the CreateODBDate when I'm passing in the dates in my <cfquery> using a queryparam with a type of cf_sql_dat