2 JScrollPanes and 1 JTable

I have searched for about an hour and I can't find anything related to this. I apologize in advance if this is a repeat post.
I have a JTable that is being displayed in a JScrollPane that is nestled into a JFrame. I am attempting to build another Scroll Pane with the same table in it, using the following code.:
JScrollPane scrollPane = new JScrollPane(this.table);
int width = this.table.getPreferredSize().width + 5;
int height = this.table.getPreferredSize().height + 5 +
                     this.table.getTableHeader().getHeight();
Dimension ps = new Dimension( width, height );
scrollPane.setPreferredSize(ps);
JWindow window = new JWindow();
window.setSize(ps);
window.getContentPane().add(scrollPane);
window.pack();
window.show();The new window displays fine and the table shows up, but the original table disappears as soon as the JFrame it is in redraws?! Can anybody provide an explanation of why this is happening and hopefully how to fix it?

A Swing component can only belong to one container. Thanks, that was the small but very important piece of information I didn't know. I already had implemented something similar to what you suggested, but it was a little more complicated due to the nature of the table. I was hoping to get away with being lazy. Oh well...

Similar Messages

  • Plz help me about allignment of Jscrollpane and JTable

    Hi...
    I am currently working for a mini project with platform as JAVA.
    I used Grid Bag Layout for allignment of all buttons and textfields.
    I have 18 columns and 20 rows to be added to a JTable.
    My problem is that the JScrollPane is fixed and is not moving.
    The table displays all columns with each column in a row showing partial details with. ...(elipsis)
    My requirement is each column should be wide enough and should show remaining rows and columns when scrolled instead of showing narrowly everything at once and scrollpanes remaining tight.
    If any one does this favour, i will be somuch grate ful to u.
    Thanks

    I used Grid Bag Layout for allignment of all buttons and textfields.Use multiple different nested layout managers to get the desired layout.
    Give it another try.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • 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

  • Using KeyMap in Editable JComboBoxes and JTable

    I am using Keymapping for JTextFields. It works fine ! I am interested in extending the keymap feature to JComboBoxes and JTable.

    if you want to do the keymapping inside the editable component of the combobox or the table, make sure you apply it on the editor component.e.g. comboBox.getEditor().getEditorComponent() and table.getCellEditor().getTableCellEditorComponent().

  • Escape key "dies" in combobox and JTable

    I have set in my JDialog the default key ESCAPE as this standard code:
              KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
              int param = JComponent.WHEN_IN_FOCUSED_WINDOW;
              root.getInputMap(param).put(escKey, "close");
              root.getActionMap().put("close", actionCancel);
         this.btCancel.setAction(actionCancel);
    The problem is when I have JComboBoxs and JTables. All key events seem to be consumed
    In this components (and maybe more components). So, if I press ESCAPE and my focus
    in a combobox, the dialog won't close.
    How could I work around this?
    thank you

    I've got the solution!
    I have a javaBean (JPanel) that has only one JComboBox. I trigger key pressed (don't know
    if should be key released in this case) on comboBox. Then I check if...
    this.comboBox.isPopupVisible().
    Simple. If popup is not visible and dispatch the event to this.
    I just wonder how the event goes to my javaBean, my javabean is in a dialog and this
    dialog of mine ends up to catch the event. ???
    Ok, this stays has a solution for future developers to found - in case they guess that
    right keywords :)

  • A small problem with a JScrollPane and child windows

    Hi !
    I have created a customized JComponent inside a JScrollPane and when my application starts I create two JTextField's that I put in the JComponent and so far it all works fine to start with, but when ever the JComponent is redrawn after that the JTextField's are overdrawn or at least are not visible any longer...
    Do I need to repaint the sub components of my own JComponent myself or am I doing something very wrong here ?
    a JScrollPane
    a JComponent with some drawing going on in paint()
    a JTextField
    another JTextField
    Mikael

    Ooppps !
    Forget about it, I forgot to put a super.paint( g) at the top of my paint method, that was the problem.
    Mikael

  • 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))!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • Questions about Using Vector To File And JTable

    hi all
    I want to write all data from Vector To File and read from file To Vector
    And I want To show all data from vector to JTable
    Note: I'm using the JBuilder Compiler
    This is Class A that my datamember  And Methods in it
    import java.io.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2008</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public  class A implements Serializable {
      int no;
      String name;
      int age;
      public void setA (int n,String na,int a)
        no=n;
        name=na;
        age=a;
      public void set_no(int n)
        no = n;
      public void set_age(int a)
        age = a;
        public int getage ()
        return age;
      public void setName(String a)
        name  = a;
      public String getname ()
        return name;
      public int getno ()
        return no;
    This is The Frame That the JTextFeild And JButtons & JTable in it
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import com.borland.jbcl.layout.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2008</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class Frame1 extends JFrame {
    /* Vector v = new Vector ();
      public int i=0;*/
      A a = new A();
      XYLayout xYLayout1 = new XYLayout();
      JTextField txtno = new JTextField();
      JTextField txtname = new JTextField();
      JTextField txtage = new JTextField();
      JButton add = new JButton();
      JButton search = new JButton();
      /*JTable jTable1 = new JTable();
      TableModel tableModel1 = new MyTableModel(*/
                TableModel dataModel = new AbstractTableModel() {
              public int getColumnCount() { return 2; }
              public int getRowCount() { return 2;}
              public Object getValueAt(int row, int col) { return new A(); }
          JTable table = new JTable(dataModel);
          JScrollPane scrollpane = new JScrollPane(table);
      TitledBorder titledBorder1;
      TitledBorder titledBorder2;
      ObjectInputStream in;
      ObjectOutputStream out;
      JButton read = new JButton();
      public Frame1() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        titledBorder1 = new TitledBorder(BorderFactory.createEmptyBorder(),"");
        titledBorder2 = new TitledBorder("");
        this.getContentPane().setLayout(xYLayout1);
        add.setBorder(BorderFactory.createRaisedBevelBorder());
        add.setNextFocusableComponent(txtno);
        add.setMnemonic('0');
        add.setText("Add");
        add.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            add_actionPerformed(e);
        add.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            add_actionPerformed(e);
        search.setFocusPainted(false);
        search.setText("Search");
        search.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            search_actionPerformed(e);
        xYLayout1.setWidth(411);
        xYLayout1.setHeight(350);
        read.setText("Read");
        read.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            read_actionPerformed(e);
        this.getContentPane().add(txtno, new XYConstraints(43, 35, 115, 23));
        this.getContentPane().add(txtname,  new XYConstraints(44, 67, 114, 22));
        this.getContentPane().add(txtage,      new XYConstraints(44, 97, 115, 23));
        this.getContentPane().add(add,      new XYConstraints(60, 184, 97, 26));
        this.getContentPane().add(search,  new XYConstraints(167, 185, 88, 24));
        this.getContentPane().add(table,   new XYConstraints(187, 24, 205, 119));
        this.getContentPane().add(read,   new XYConstraints(265, 185, 75, 24));
        this.setSize(450,250);
        table.setGridColor(new Color(0,0,255));
      void add_actionPerformed(ActionEvent e)
        a.set_no(Integer.parseInt(txtno.getText()));
        a.setName(txtname.getText());
        a.set_age(Integer.parseInt(txtage.getText()));
        fileOutput();
        txtno.setText(null);
        txtname.setText(null);
        txtage.setText(null);
        try
          out.writeObject(a);
          out.close();
        }catch (Exception excep){};
    /*  try
           add.setDefaultCapable(true);
          v.addElement(new A());
         ((A)v.elementAt(i)).setA(Integer.parseInt(txtno.getText()),txtname.getText(),Integer.parseInt(txtage.getText()));
        JOptionPane.showMessageDialog(null,"The Record is Added");
        txtno.setText(null);
        txtname.setText(null);
        txtage.setText(null);
        i++;
      }catch (Exception excep){};*/
      void search_actionPerformed(ActionEvent e) {
        int n = Integer.parseInt(JOptionPane.showInputDialog("Enter No:"));
        for (int i=0;i<v.size();i++)
          if (((A)v.elementAt(i)).getno()==n)
            txtno.setText(Integer.toString(((A)v.elementAt(i)).getno()));
            txtname.setText(((A)v.elementAt(i)).getname() );
            txtage.setText(Integer.toString(((A)v.elementAt(i)).getage()));
      public void fileOutput()
        try
          out = new ObjectOutputStream(new FileOutputStream("c:\\UserData.txt",true));
        }catch(Exception excep){};
      public void fileInput()
        try
          in = new ObjectInputStream(new FileInputStream("c:\\UserData.txt"));
        }catch(Exception excep){};
      void read_actionPerformed(ActionEvent e) {
      fileInput();
        try
          a = (A)in.readObject();
          txtno.setText(Integer.toString(a.getno()));
          txtname.setText(a.getname());
          txtage.setText(Integer.toString(a.getage()));
        }catch (Exception excep){};
    }

    //program which copies string data between vector and file
    import java.util.*;
    import java.io.*;
    class Util
    private Vector v;
    private FileReader filereader;
    private FileWriter filewriter;
    Util(String data[])throws Exception
      v=new Vector();
      for(String o:data)
        v.add(o);
    public void listData()throws Exception
      int size=v.size();
      for(int i=0;i<size;i++)
       System.out.println(v.get(i));
    public void copyToFile(String data,String fname)throws Exception
      filewriter =new FileWriter(fname);
      filewriter.write(data);
      filewriter.flush();
      System.out.println("Vector content copied into file..."+fname);
    public void copyFromFile(String fname)throws Exception
      filereader=new FileReader(fname);
      char fcont[]=new char[(int)new File(fname).length()];
      filereader.read(fcont,0,fcont.length);
      String temp=new String(fcont); 
      String fdata[]=temp.substring(1,temp.length()-1).split(",");
      for(String s:fdata)
        v.add(s.trim()); 
      System.out.println("File content copied into Vector...");
    public String getData()throws Exception
       return(v.toString());
    class TestUtil
    public static void main(String a[])throws Exception
      String arr[]={"siva","rama","krishna"};
      Util util=new Util(arr);
      System.out.println("before copy from file...");
      util.listData();
      String fname=System.getProperty("user.home")+"\\"+"vecdata";
      util.copyToFile(util.getData(),fname);
      util.copyFromFile(fname);
      System.out.println("after copy from file...");
      util.listData();
    }

  • Problem with JPanel, JScroll and JTable

    Hi.
    On one of my Jframes, i have 3 Jpanels. There are two on one side, and one of the other which spans the height of the other two. However, it does more than span the height of the other two, it streches the height of the Jframe as it is about 300 pixels too heigh.
    I'm not sure which element is streching the JPanel, it might be either the Jpanel itself, the JScroll or the JTable. Theres alot of code, however i'm going to try and cut out the irrelevent parts.
    I call the Jpanel via:
    FarmList = new javax.swing.JPanel();
    FarmList.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Farm List", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
    FarmList.add(new GetFarms());And the code for the GetFarms() class is:
    public class GetFarms extends JPanel {
         private final int COLUMNS = 4;
         private int ROWS = 2;
         private JTable sampleJTable;
         private String[][] cells = new String[ROWS][COLUMNS];
        public static void main(String[] args) throws Exception {
            JFrame frame = new JFrame("Covenant Farm List");
              frame.add(new GetFarms());
            frame.setSize(450,150);
            frame.setVisible(true);
         public GetFarms() throws Exception {
              URL theUrl = new URL("http://www.allydm.co.uk/Covenant/farm_list.php");
              BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        theUrl.openStream()));
              String inputLine = in.readLine();
              String[] lines = inputLine.split("<br>");
              for (int i = 0; i < ROWS; i++) {
                   String[] stuff = lines.split(" ");
                   for (int j = 0; j < COLUMNS; j++) {
                        cells[i][j] = stuff[j];
              in.close();
              String[] columnNames = {"Username", "DA", "Sentry", "Last Update"};
              sampleJTable = new JTable(cells, columnNames);
              JScrollPane tablePane = new JScrollPane(sampleJTable);
    add(tablePane, BorderLayout.CENTER);
    If anyone has any ideas, on how to limit the size of the Jpanel or JScroll it'd be greatly appreciated.

    did you implement setxxxSize() methods?
    see
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html

  • How to enter values in JList box and JTable ???

    Hi friends...
    i am new to Swing
    SInce i am using Netbeans IDE 5.5
    and there is easy to do swing programming using this IDE
    now i am confused using JTable and JList box
    since i used method Insert in AWT
    but how to add values in LIST BOX ( JList )
    ex.
    JList list = new JList( );
    list.add(mystringvalue, ? );
    here it ask for component so what should i write here..
    when i write here this, gives error.
    what to do to insert string or vector or object in JList
    and to enter value in JTable
    THanks

    hi Ghanshyam,
    i am also new to swing i was just wondering are you using the swing palette to create your interface
    by the look of the code
    JList list = new JList( );
    list.add(mystringvalue, ? );you may not be because every JList is put in a JScrollPane
    but if you do want to do it through the palette there is an option in properties - model which you can uses to add in values.
    and if your looking to get info. from a database look up
    AbstractListModel &
    AbstractTableModel
    the is a lot of info on the internet (example net beans CarTableModel) is a
    good start off
    happy hunting.
    JJ

  • PLS help with stupid JPanel and JTable :-(

    Hi all im crying now :-(
    Ive just recreated a panel for use with SWING. Now I want the table to be displayed but it just is not there.
    Nothing i seem to do makes it appear and im really confused????? Just add this to a simple JFrame and you will see what I mean
    it should look like this
    TITLE
    lbl1 txt1 lbl2 txt2
    lbl3 txt3 lbl4 txt 4
    button
    Table
    however the table is not there :-(
    Author: Justin Thomas
    Date  : 14 Jan 2002
    Notes : A simple login display
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Options extends JPanel implements ActionListener
        private IDNTester parent;
        private TextArea Results = new TextArea(18,80);
        private JButton Start = new JButton("Start Test");
        private JLabel error = new JLabel ("");
        private JTextField txtConns = new JTextField("1",4);
        private JTextField txtClients = new JTextField("10",4);
        private JTextField txtServer = new JTextField("Nutcracker",10);
        private JTextField txtPort = new JTextField("8101",5);
        public String Server;
        public int Port;
        public int Connections;
        public int Clients;
        private String newline;
        public Options(IDNTester ref)
            parent = ref;
            newline = System.getProperty("line.separator");
            JLabel lblMain = new JLabel ("WebIDN Performance Tester");
            JLabel  lblServer = new JLabel ("Server:");
            JLabel  lblPort = new JLabel ("Port:");
            JLabel  lblConns = new JLabel ("Connections:");
            JLabel  lblClients = new JLabel ("Clients:");
            GridBagLayout gridBag = new GridBagLayout();
            GridBagConstraints constraints = new GridBagConstraints();
            setLayout(gridBag);
            constraints.anchor = GridBagConstraints.CENTER;
            constraints.gridwidth = 4;
            constraints.gridx = 0;
            gridBag.setConstraints(lblMain, constraints);
            add(lblMain);
            constraints.insets = new Insets(10,0,0,0);  //top padding
            constraints.gridy = 1;
            gridBag.setConstraints(error, constraints);
            error.setForeground(Color.red);
            add(error);
            constraints.anchor = GridBagConstraints.WEST;
            constraints.gridwidth = 1;
            constraints.gridx = 0;
            //********************************Server and COnnections***************
            constraints.fill = GridBagConstraints.BOTH;
            constraints.gridy = 2;
            gridBag.setConstraints(lblServer, constraints);
            add(lblServer);
            constraints.gridx = 1;
            gridBag.setConstraints(txtServer, constraints);
            add(txtServer);
            // Add some space between fields
            constraints.gridx = 2;
            gridBag.setConstraints(lblConns, constraints);
            add(lblConns);
            constraints.gridx = 3;
            gridBag.setConstraints(txtConns, constraints);
            add(txtConns);
            //********************************** Port and clients******************
            constraints.gridy = 3;
            constraints.insets = new Insets(5,0,0,0);
            constraints.gridx = 0;
            gridBag.setConstraints(lblPort, constraints);
            add(lblPort);
            constraints.gridx = 1;
            gridBag.setConstraints(txtPort, constraints);
            add(txtPort);
            constraints.gridx = 2;
            gridBag.setConstraints(lblClients, constraints);
            add(lblClients);
            constraints.gridx = 3;
            gridBag.setConstraints(txtClients, constraints);
            add(txtClients);
            //********************************** Buttons***************************
            constraints.anchor = GridBagConstraints.CENTER;
            constraints.gridy = 4;
            constraints.insets = new Insets(10,0,0,0);  //top padding
            constraints.gridwidth = 4;   //4 columns wide
            constraints.gridx = 0;
            gridBag.setConstraints(Start, constraints);
            add(Start);
            // Results area
            constraints.gridx = 0;
            constraints.gridy = 5;
            constraints.gridwidth = 5;   //Colum width
            //gridBag.setConstraints(Results, constraints);
            //add(Results);
            // JTable
            DefaultTableModel defaultTab = new DefaultTableModel();
            JTable jtable = new JTable(defaultTab);
            defaultTab.addColumn("ThreadID");
            defaultTab.addColumn("ClientID");
            defaultTab.addColumn("RIC");
            defaultTab.addColumn("TimeTaken");
            defaultTab.addColumn("RCount");
            defaultTab.addColumn("Bytes");
            //add scrollpane to our table
            gridBag.setConstraints(jtable, constraints);
            add(new JScrollPane(jtable));
            // Add listeners
            txtConns.addActionListener(this);
            txtClients.addActionListener(this);
            txtServer.addActionListener(this);
            txtPort.addActionListener(this);
            Start.addActionListener(this);
        public void actionPerformed(ActionEvent event)
            // Validate fields and if correct then start
            boolean valid = true;
            Server = txtServer.getText();
            try {
                Port= Integer.parseInt(txtPort.getText());
                Connections = Integer.parseInt(txtConns.getText());
                Clients = Integer.parseInt(txtClients.getText());
            catch(NumberFormatException nfe) {
                valid = false;
            if (valid && Server.length() > 0)
                error.setText("");
                parent.connect();
            else
                error.setText("Port/Client/Connections must be numerical");
                validate();
        // Add a new line to the test
        public void addLine(String text)
            Results.append(text + newline);
    }

    Hi,
    It looks like you haven't closed the comments. Is anything added after error.
    Anyway try setting the fill constrains on your table to BOTH. The table you have created in empty so it may have trouble determining it's size.
    regards,
    Terry

  • Please help with Database and JTable.

    The class listed below is for a JTable. The main in this class is for testing only, when complete main will reside elsewhere. I need to know how to make this JTable universal. How can I set it up so that when called in a main and passed parameters it will display the information contained in that users database?? Again it must be universal so no matter who uses it, it will perform the same on all database's.
    Here's the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class DisplayTable extends JFrame{
    public DisplayTable() {
         JFrame jf = new JFrame("Window Title");
              jf.setSize(1100,700);
              jf.setLocation(25,50);
              jf.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);}
         TableModel tm = new AbstractTableModel(){
              String[][] data = { {"How to get database data??"}};
              String[] headers = {"How to get database headers??"};
              public int getRowCount() {return data.length;}
              public int getColumnCount() {return headers.length;}
              public Object getValueAt(int r, int c) {return data[r][c];}
              public String getColumnName(int c) {return headers[c];}
         JTable jt = new JTable(tm);
         JScrollPane jsp = new JScrollPane(jt);
              jf.getContentPane().add(jsp, BorderLayout.CENTER);
              jf.setVisible(true);
    public static void main(String args[]){
         DisplayTable dt = new DisplayTable(Database Parameters to be given here);

    You could generalize it, but it gets tricky to deal with the data types and if the JTable is editable because you would read the DB table data at run time. Using the ResultSetMetaData, you would be able to find the column type too. But, how can we cast an object at run-time?
    Below, I have provided an overview as of doing a read-only (all-strings version) of it. You may have some ideas from there.
    The database parameters that you pass to the constructor would tell the model where to connect and which DB table to read the data from. Couple of options:
    1. You can read the data in the constructor of DisplayTable into final variables and have the inner class (model) set its data and headers from those variables.
    Or
    2. Pull out the model as a separate class extending AbstractTableMode. Doing this, you can pass on the DB information to the model and have the model talk to the DB.
    And, I would use dynamic datastructures like Vector or List instead of arrays.
    You would have the following logic wherever you chose to talk to the DB:
    I am assuming that you are trying to read a complete DB table into your JTable (or may be you would pass a SELECT-query alongwith your DB information). Whatever may be the case, you would execute a select- to the DB and get a resultset back. Using that you would be able to get the ResultSetMetaData, which will give you the column count and column names. You may chose to use these column names as the header names for your JTable. With the column count you would query every row to get the object at each column.
    Here is a sample model:
    class MyModel extends AbstractTableModel {
        ArrayList columnNames = new ArrayList();
        ArrayList data = new ArrayList();
        MyModel(<DB Info>) {
            // Use the DB info and get the resultset
            ResultSetMetaData rsm = rs.getMetaData();
            int col = rsm.getColumnCount();
            for(int i=1; i<=col; i++) {
                columnNames.add(rsm.getColumnName(i));
            // Read the data
            while(rs.next()) {
                ArrayList row = new ArrayList();
                data.add(row);
                for(int j=1; j<=col; j++) {
                    // Here is the tricky part which I did not figure yet. For now, I am reading in all as Strings.
                    row.add(rs.getObject(j).toString());
        public String getColumnName(int c) {
            return (String)columnNames.get(c);
        public int getColumnCount() {
            return columnNames.size();
        public Object getValueAt(int r,int c) {
            ArrayList row = (ArrayList)data.get(r);
            return (String)row.get(c);
        public int getRowCount() {
            return data.size();
    }If you figured a way to handle run-time casting, please let us know.
    HTH.
    Vijay

  • TableModel and JTable

    I'm fairly new to Java and am currently working on a class project involving JDBC and mySQL.
    The information that I pull out of the database is being displayed in a table. I have textfields and buttons that allow users to input new information. The problem is that I need the tables to update when this new information is submitted.
    I have figured out that I should use a tablemodel and the method fireTableDataChanged, but I have no idea how to implement a tabelmodel. Currently I create an array from the database data, create a table and add the arrays, then I add the table to a scroll plane, and finally add the scrollpane to a tab.
    Where and how do I implement/use TableModel? Can I just use DefaultTableModel?
    I am very confused right now :(

    I believe that when learning how to use JTable you should just use the DefaultTableModel, especially for a simple requirement like reading data from a database. Here is a simple example. Notice how only a couple of lines of code are for the creation and display of the JTable. The rest of the code is for reading the database
    import java.awt.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableFromDatabase extends JFrame
         public TableFromDatabase()
              Vector columnNames = new Vector();
            Vector data = new Vector();
            try
                //  Connect to the Database
                String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    //            String url = "jdbc:odbc:Teenergy";  // if using ODBC Data Source name
                String url =
            "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/teenergy/data/teenergy.mdb";
                String userid = "";
                String password = "";
                Class.forName( driver );
                Connection connection = DriverManager.getConnection( url, userid, password );
                //  Read data from a table
                String sql = "Select * from Page";
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery( sql );
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                //  Get column names
                for (int i = 1; i <= columns; i++)
                    columnNames.addElement( md.getColumnName(i) );
                //  Get row data
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++)
                        row.addElement( rs.getObject(i) );
                    data.addElement( row );
                rs.close();
                stmt.close();
            catch(Exception e)
                System.out.println( e );
            //  Create table with database data
            JTable table = new JTable(data, columnNames)
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            JPanel buttonPanel = new JPanel();
            getContentPane().add( buttonPanel, BorderLayout.SOUTH );
        public static void main(String[] args)
            TableFromDatabase frame = new TableFromDatabase();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }If you want to know when data has been changed in the table then you need to add a TableModelListener to your TableModel. This posting shows a simple example of of using a TableModelListener:
    http://forum.java.sun.com/thread.jspa?threadID=527578&messageID=2535291

  • Applet and JTable

    Hi all,
    here's an easy one... i have an applet trying to diplay a JTable... i can't make the header being displayed... what's wrong with it?
    public void start()
         JTable table = new JTable(new String[][]{{"1","12:30","Out of Communication","J1"},{"2","12:31","Flashing Yellow","J3"}}, new String[]{"Number","Time","Description","Item"} );
         this.add(table);
    Thanks,
    Dani.

    Add your table to a scroll pane and add the scroll pane to your applet.
    e.g.
    JTable table = new JTable();
    JScrollPane pane = new JScrollPane(table);
    applet.add(pane);

Maybe you are looking for

  • About stock report

    Hi gurus, I am looking for a report or a functional module which will give me closing stock on any date, storage location wise. I am getting some data in MB5B and other reports as MC. A etc. but I am not getting the stock and storage location along w

  • SRM & R/3

    Hi SRM Experts, The following is the process we can use in SUS scenarios. 1 Create a purchase requistion in r3 mm 2 create a purchase order with respect to purchase requisition in r3 mm 3 create a purcashe order response to the purchase order in SUS

  • Itunes update fail with 1XE800000A what is it?

    Today i want to make an update for itunes.... but it fails with mistake number 1XE800000A Who knows what it means... Who can help? OS is win 7 64bit

  • Replacing Xml Code Blocks

    Hi, Fellas I have a problem regarding an Xml document, where I need to remove blocks of xml code, if there are control characters found in a block. (you know those squares that sometimes appear). Of course i need to manipulate the code using Java API

  • ITunes8.2 might not sync contacts, calendar and notes with Outlook 2007

    My ipod touch has been synching on a Windows XP machine with Outlook 2003 and iTunes 8.2 nicely for a few weeks. Now I need to move to a different computer. That one had Outlook 2000 this morning. The sync that was intended to move the contacts and c