Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Many problems with JTable

  1. #1
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Many problems with JTable

    I was trying to make an address book with JTable. I have some classes, Person, and PersonSearcher, neither of which is the issue but I'm posting as it is needed right now for it to run.

    I have tried and tried to find a way to resize just one cell and have found some code online that should auto-resize column width as necessary, but it's not going to width 100 like I wanted. I want the whole name viewable (not just part of it.)

    Also, I could not for the life of me find anything that would resize just one cell and had to grow the entire row in height to make sure that the picture could fit. Ideally, I'd like the picture to resize as necessary to fit and to scale if it's bigger than 200 by 200 so that it fits in 200 by 200 but can't figure that out.

    Also, my table cells are all a strange bluish color and I didn't tell it to change the background to that.

    In addition, I'm trying to get it to change the Image of the picture when they click the upload button. It shows that it got the picture and returns its canonical path, but somehow, even though I'm calling repaint() on the JTable, it's not changing.


    Also, my JTable is taking up only a small space on the page (and I'm wondering if that's why everything seems so squished) and I would like it to take up more room if it could.


    [h2] Person.java [/h2]
     
    package addressbook.util;
     
    import javax.swing.ImageIcon;
     
     
     
    public class Person implements Comparable<Person> 
    {
     
     
       private String name;
       private String address;
       private String city;
       private String zip;
       private String email;
       private String home;
       private String cell;
       private String picture;
     
     
       public Person()
       {
     
          name = "Unnamed";
          address = "";
          city = "";
          zip = "";
          home = "";
          cell = "";
          email = "";
          picture ="./noPic.jpg";
     
     
     
       }
     
     
       public Person(String name, String address, String city, String zip, String home, String cell, String email, String picture)
       {
     
          if (name == null)
             this.name = "Unnamed";
     
          else
             this.name = name;
     
          if (address == null)
             this.address = "";
     
          else
             this.address = address;
     
          if (city == null)
             this.city = "";
     
          else
             this.city = city;
     
          if (zip == null)
             this.zip = "";
     
          else
             this.zip = zip;
     
          if (home == null)
             this.home = "";
     
          else
             this.home = home;
     
          if (cell == null)
             this.cell = "";
     
          else
             this.cell = cell;
     
          if (email == null)
             this.email = "";
     
          else
             this.email = email;
     
          if (picture == null)
             this.picture = "./noPic.jpg";
     
     
     
     
     
     
     
     
       }
     
     
     
     
     
       public void setName(final String name)
       {
          if (name == null)
             this.name = "Unnamed";
     
          else
             this.name = name;
       }
     
       public String getName()
       {
          return name;
       }
     
       public void setZip(final String zip)
       {
          if (zip == null)
             this.zip = "";
     
          else
             this.zip = zip;
     
     
       }
     
       public String getZip()
       {
          return zip;
       }
     
     
     
       public void setAddress(final String address)
       {
          if (address == null)
             this.address = "";
     
          else
             this.address = address;
       }
     
       public String getAddress()
       {
          return address;
       }
     
       public void setCity(final String city)
       {
          if (city == null)
             this.city = "";
     
          else
             this.city = city;
     
       }
     
       public String getCity()
       {
          return city;
       }
     
     
       public void setHomePhone(final String home)
       {
          if (home == null)
             this.home = "";
     
          else
             this.home = home;
       }
     
       public String getHomePhone()
       {
          return home;
       }
     
       public void setCellPhone(final String cell)
       {
          if (cell == null)
             this.cell = "";
     
          else
             this.cell = cell;
       }
     
       public String getCellPhone()
       {
          return cell;
       }
     
       public void setEmail(final String email)
       {
          if (email == null)
             this.email = "";
     
          else
             this.email = email;
       }
     
       public String getEmail()
       {
          return email;
       }
     
       public void setPicture(final String picture)
       {
     
          if (picture == null)
             this.picture = "./noPic.jpg";
     
          else
             this.picture = picture;
     
       }
     
       public String getPicture()
       {
          return picture;
       }
     
     
     
     
       public int compareTo(Person person)
       {
     
          if (getName().compareTo(person.getName()) < 0)
             return -1;
     
          else if (getName().compareTo(person.getName()) == 0)
          {
     
             if (getAddress().compareTo(person.getAddress()) < 0)
                return -1;
     
             else if (getAddress().compareTo(person.getAddress()) == 0)
             {
     
                if (getCity().compareTo(person.getCity()) < 0)
                   return -1;
     
                else if (getCity().compareTo(person.getCity()) == 0)
                   return 0;
     
                else
                   return 1;
     
             }
     
             else
                return 1;
     
     
          }
     
          else
             return 1;
     
     
     
       }
     
       public boolean equals(Object person)
       {
     
     
          if (person instanceof Person)
          {
     
             Person dude = (Person) person;
     
     
             if (compareTo(dude) == 0)
                return true;
     
             else
                return false;
     
     
          }
     
     
          else
             return false;
     
     
       }
     
     
     
     
    }

    [h2] TablePanel.java [/h2]
    package addressbook.gui;
     
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.ImageIcon;
    import java.io.File;
    import javax.swing.JOptionPane;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JLabel;
    import java.awt.Component;
    import addressbook.util.Person;
    import javax.swing.JScrollPane;
     
    public class TablePanel extends JPanel
    {
     
     
       private JTable personTable;
       private JPanel tablePanel;
       private JPanel buttonPanel;
       private JButton upload, save;
       private Person p;
       private final String[] headers = {"Name", "Address", "City", "Zip", "Home", "Cell", "Email", "Picture"};
     
       public TablePanel()
       {
     
          p = new Person();
          initialize();
     
     
     
     
     
       }
     
     
       public TablePanel(Person p)
       {
          this.p = p;
          initialize();
     
     
       }
     
       public void setPerson(final Person p)
       {
          this.p = p;
     
     
       }
     
       public Person getPseron()
       {
          return p;
       }
     
     
       protected class ImageRenderer extends DefaultTableCellRenderer
       {
     
          @Override
          public Component getTableCellRendererComponent(JTable table,Object value, boolean isSelected,boolean hasFocus, int row, int column)
          {
             JLabel label = new JLabel();
     
             if (value!=null) {
                label.setHorizontalAlignment(JLabel.CENTER);
     
                label.setIcon(new ImageIcon((String)value));
             }
     
     
             return label;
          }
       }
     
     
       private void initialize()
       {
     
     
          Object[][] data = new Object[1][8];
     
          data[0][0] = p.getName();
          data[0][1] = p.getAddress();
          data[0][2] = p.getCity();
          data[0][3] = p.getZip();
          data[0][4] = p.getHomePhone();
          data[0][5] = p.getCellPhone();
          data[0][6] = p.getEmail();
          data[0][7] = p.getPicture();
     
     
          personTable = new JTable(data, headers);
          personTable.getColumnModel().getColumn(7).setCellRenderer(new ImageRenderer());
          tablePanel = new JPanel();
     
          setLayout(new BorderLayout());
          add(tablePanel, BorderLayout.NORTH);
          tablePanel.add(new JScrollPane(personTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED   ));
     
          upload = new JButton("Upload Image");
          save = new JButton("Save");
     
          buttonPanel = new JPanel(new java.awt.FlowLayout());
     
          add(buttonPanel, BorderLayout.CENTER);
     
          buttonPanel.add(upload);
          buttonPanel.add(save);
          setVisible(true);
     
          personTable.getTableHeader().setBackground(java.awt.Color.GREEN);
     
          be.alex.examples.ColumnsAutoSizer.sizeColumnsToFit(personTable, 5);
          personTable.getColumnModel().getColumn(7).setPreferredWidth(400);
     
          personTable.setRowHeight(400);
     
          for (int i =0; i < 7; i++)
          {
     
             personTable.getColumnModel().getColumn(i).setPreferredWidth(100);
     
     
          }
     
          //personTable.setPreferredSize(new java.awt.Dimension(800, 800));
          personTable.getTableHeader().setReorderingAllowed(false);
     
          //personTable.setModel(new MyTableModel(data, headers));
     
     
          upload.addActionListener(
                new ActionListener()  {
     
     
                   public void actionPerformed(ActionEvent e)
                   {
     
                      JFileChooser uploadFileChooser = new JFileChooser("./");
     
                      int option = uploadFileChooser.showOpenDialog(null);
     
                      File f = uploadFileChooser.getSelectedFile();
     
                      if (f == null)
                      {
                         JOptionPane.showMessageDialog(null, "Could not open file.", "No file selected.", JOptionPane.ERROR_MESSAGE);
                         return;
                      }
     
                      if (!f.exists())
                      {
                         JOptionPane.showMessageDialog(null, "Could not open file.", "File not found.", JOptionPane.ERROR_MESSAGE);
                         return;
                      }
     
                      try
                      {
                         p.setPicture(f.getCanonicalPath());
                      }
     
                      catch(java.io.IOException ioe)
                      {
     
                      }
     
     
     
                      System.out.println(p.getPicture());
                      personTable.repaint();
     
     
     
     
     
                   }});
     
     
     
       }
     
     
    }

    Also, I'm use a class I found online that is supposed to be making my columns fit and resize as necessary (or at least that's what I thought it was supposed to do.)
    (It recommended that I do some setting that I'm not sure how to set. I can see the settings in the JTable fields but not where to set them in the methods.)

    package be.alex.examples;
     
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.FontMetrics;
     
    public class ColumnsAutoSizer {
     
       public static void sizeColumnsToFit(JTable table) {
          sizeColumnsToFit(table, 5);
       }
     
       public static void sizeColumnsToFit(JTable table, int columnMargin) {
          JTableHeader tableHeader = table.getTableHeader();
     
          if(tableHeader == null) {
             // can't auto size a table without a header
             return;
          }
     
          FontMetrics headerFontMetrics = tableHeader.getFontMetrics(tableHeader.getFont());
     
          int[] minWidths = new int[table.getColumnCount()];
          int[] maxWidths = new int[table.getColumnCount()];
     
          for(int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++) {
             int headerWidth = headerFontMetrics.stringWidth(table.getColumnName(columnIndex));
     
             minWidths[columnIndex] = headerWidth + columnMargin;
     
             int maxWidth = getMaximalRequiredColumnWidth(table, columnIndex, headerWidth);
     
             maxWidths[columnIndex] = Math.max(maxWidth, minWidths[columnIndex]) + columnMargin;
          }
     
          adjustMaximumWidths(table, minWidths, maxWidths);
     
          for(int i = 0; i < minWidths.length; i++) {
             if(minWidths[i] > 0) {
                table.getColumnModel().getColumn(i).setMinWidth(minWidths[i]);
             }
     
             if(maxWidths[i] > 0) {
                table.getColumnModel().getColumn(i).setMaxWidth(maxWidths[i]);
     
                table.getColumnModel().getColumn(i).setWidth(maxWidths[i]);
             }
          }
       }
     
       private static void adjustMaximumWidths(JTable table, int[] minWidths, int[] maxWidths) {
          if(table.getWidth() > 0) {
             // to prevent infinite loops in exceptional situations
             int breaker = 0;
     
             // keep stealing one pixel of the maximum width of the highest column until we can fit in the width of the table
             while(sum(maxWidths) > table.getWidth() && breaker < 10000) {
                int highestWidthIndex = findLargestIndex(maxWidths);
     
                maxWidths[highestWidthIndex] -= 1;
     
                maxWidths[highestWidthIndex] = Math.max(maxWidths[highestWidthIndex], minWidths[highestWidthIndex]);
     
                breaker++;
             }
          }
       }
     
       private static int getMaximalRequiredColumnWidth(JTable table, int columnIndex, int headerWidth) {
          int maxWidth = headerWidth;
     
          TableColumn column = table.getColumnModel().getColumn(columnIndex);
     
          TableCellRenderer cellRenderer = column.getCellRenderer();
     
          if(cellRenderer == null) {
             cellRenderer = new DefaultTableCellRenderer();
          }
     
          for(int row = 0; row < table.getModel().getRowCount(); row++) {
             Component rendererComponent = cellRenderer.getTableCellRendererComponent(table,
                 table.getModel().getValueAt(row, columnIndex),
                 false,
                 false,
                 row,
                 columnIndex);
     
             double valueWidth = rendererComponent.getPreferredSize().getWidth();
     
             maxWidth = (int) Math.max(maxWidth, valueWidth);
          }
     
          return maxWidth;
       }
     
       private static int findLargestIndex(int[] widths) {
          int largestIndex = 0;
          int largestValue = 0;
     
          for(int i = 0; i < widths.length; i++) {
             if(widths[i] > largestValue) {
                largestIndex = i;
                largestValue = widths[i];
             }
          }
     
          return largestIndex;
       }
     
       private static int sum(int[] widths) {
          int sum = 0;
     
          for(int width : widths) {
             sum += width;
          }
     
          return sum;
       }
     
    }

    I've spent hours and hours looking for a way to set this up just right but can't find anything, not even on Google, that will do what I want with setting the height of just one column.

    I've tried calling pack() to resize the JTable to look better, but it isn't quite making it bigger. It is still small.


  2. #2
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Many problems with JTable

    Any ideas? I have looked but still can't find what I need to make the text fields resize to show all the text rather than making the user have to move (which is a pain and makes accidental typeover easy.)


    I had an idea of how to set the sizes of stuff, perhaps I try and set the size of the TableCellRenderer or something like that. However, I've tried setting the size of ImageRenderer and it didn't really help.

    I'm just at a loss as to what to do.

  3. #3
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Many problems with JTable

    Ok, I got the image to work better, but I'm still having trouble getting the table to fill more of the screen, and now it has a gray area below the main entry. I want the cells to be able to resize if the text is long enough in them.

     
    package addressbook.gui;
     
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.ImageIcon;
    import java.io.File;
    import javax.swing.JOptionPane;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JLabel;
    import java.awt.Component;
    import addressbook.util.Person;
    import javax.swing.JScrollPane;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
     
    public class TablePanel extends JPanel
    {
     
     
       private JTable personTable;
       private JPanel tablePanel;
       private JPanel buttonPanel;
       private JButton upload, save;
       private Person p;
       private final String[] headers = {"Name", "Address", "City", "Zip", "Home", "Cell", "Email", "Picture"};
     
       public TablePanel()
       {
     
          p = new Person();
          initialize();
     
     
     
     
     
       }
     
     
       public TablePanel(Person p)
       {
          this.p = p;
          initialize();
     
     
       }
     
       public void setPerson(final Person p)
       {
          this.p = p;
     
     
       }
     
       public Person getPseron()
       {
          return p;
       }
     
     
       protected class ImageRenderer extends DefaultTableCellRenderer
       {
     
          @Override
          public Component getTableCellRendererComponent(JTable table,Object value, boolean isSelected,boolean hasFocus, int row, int column)
          {
             JLabel label = new JLabel();
     
             if (value!=null) {
                label.setHorizontalAlignment(JLabel.CENTER);
     
                ImageIcon icon = new ImageIcon((String) value);
     
     
                java.awt.Image image = icon.getImage().getScaledInstance(200, 200, java.awt.Image.SCALE_SMOOTH);
                icon.setImage(image);
     
                label.setIcon(icon);
             }
     
     
             return label;
          }
       }
     
     
       private void initialize()
       {
     
     
          Object[][] data = new Object[1][8];
     
          data[0][0] = p.getName();
          data[0][1] = p.getAddress();
          data[0][2] = p.getCity();
          data[0][3] = p.getZip();
          data[0][4] = p.getHomePhone();
          data[0][5] = p.getCellPhone();
          data[0][6] = p.getEmail();
          data[0][7] = p.getPicture();
     
     
          personTable = new JTable(data, headers);
          //personTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
          personTable.getColumnModel().getColumn(7).setCellRenderer(new ImageRenderer());
     
     
          personTable.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.ORANGE, 2, true));
     
          tablePanel = new JPanel();
     
          setLayout(new BorderLayout());
          add(tablePanel, BorderLayout.NORTH);
          tablePanel.add(new JScrollPane(personTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED   ));
     
          upload = new JButton("Upload Image");
          save = new JButton("Save");
     
          buttonPanel = new JPanel(new java.awt.FlowLayout());
     
          buttonPanel.setBackground(new java.awt.Color(100, 50, 200));
          tablePanel.setBackground(buttonPanel.getBackground());
     
          add(buttonPanel, BorderLayout.CENTER);
          //buttonPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(120, 180, 220), 2));
     
          buttonPanel.add(upload);
          buttonPanel.add(save);
          setVisible(true);
     
          personTable.getTableHeader().setBackground(java.awt.Color.GREEN);
          personTable.getTableHeader().setForeground(java.awt.Color.BLUE);
          personTable.getTableHeader().setBorder(personTable.getBorder());
     
     
     
          be.alex.examples.ColumnsAutoSizer.sizeColumnsToFit(personTable, 5);
          personTable.getColumnModel().getColumn(7).setPreferredWidth(400);
     
          personTable.setRowHeight(200);
     
          for (int i =0; i < 7; i++)
          {
     
             personTable.getColumnModel().getColumn(i).setPreferredWidth(100);
     
     
          }
     
          for (int i =0; i < 7; i++)
          {
     
             //dec.getComponent().setSize(new java.awt.Dimension(200, 200));
     
             personTable.getColumnModel().getColumn(i).setCellEditor(new javax.swing.DefaultCellEditor(new javax.swing.JTextField(100)));
     
             javax.swing.DefaultCellEditor dec = (javax.swing.DefaultCellEditor) (personTable.getColumnModel().getColumn(i).getCellEditor());
     
             ((javax.swing.JTextField) (dec.getComponent())).setPreferredSize(new java.awt.Dimension(20, 300));
     
     
          }
     
          personTable.setPreferredSize(new java.awt.Dimension(800, 200));
          personTable.getTableHeader().setReorderingAllowed(false);
     
          //personTable.setModel(new MyTableModel(data, headers));
     
     
          upload.addActionListener(
                new ActionListener()  {
     
     
                   public void actionPerformed(ActionEvent e)
                   {
     
                      JFileChooser uploadFileChooser = new JFileChooser("./");
     
                      int option = uploadFileChooser.showOpenDialog(null);
     
                      if (option == JFileChooser.CANCEL_OPTION)
                         return;
     
                      File f = uploadFileChooser.getSelectedFile();
     
                      if (f == null)
                      {
                         JOptionPane.showMessageDialog(null, "Could not open file.", "No file selected.", JOptionPane.ERROR_MESSAGE);
                         return;
                      }
     
                      if (!f.exists())
                      {
                         JOptionPane.showMessageDialog(null, "Could not open file.", "File not found.", JOptionPane.ERROR_MESSAGE);
                         return;
                      }
     
                      try
                      {
                         p.setPicture(f.getCanonicalPath());
                      }
     
                      catch(java.io.IOException ioe)
                      {
     
                      }
     
     
     
                      System.out.println(p.getPicture());
                      personTable.repaint();
     
     
                      ((ImageRenderer) (personTable.getColumnModel().getColumn(7).getCellRenderer())).repaint();
     
                      personTable.setValueAt(p.getPicture(), 0, 7);
                      personTable.repaint();
     
     
     
                   }});
     
     
          save.addActionListener(
                new ActionListener() {
     
     
                   public void actionPerformed(ActionEvent e)
                   {
     
     
                      String name = (String) (personTable.getValueAt(0, 0));
                      String address = (String) (personTable.getValueAt(0, 1));
                      String city = (String) (personTable.getValueAt(0, 2));
                      String zip = (String) (personTable.getValueAt(0, 3));
                      String homePhone = (String) (personTable.getValueAt(0, 4));
                      String cellPhone = (String) (personTable.getValueAt(0, 5));
                      String email = (String) (personTable.getValueAt(0, 6));
                      String picture = (String) (personTable.getValueAt(0,7));
     
                      p.setName(name);
                      p.setAddress(address);
                      p.setCity(city);
                      p.setZip(zip);
                      p.setHomePhone(homePhone);
                      p.setCellPhone(cellPhone);
                      p.setEmail(email);
                      p.setPicture(picture);
     
                      //JOptionPane.showMessageDialog(null, "Successfully updated.", "Saved",  JOptionPane.INFORMATION_MESSAGE);
     
     
     
                   }});
     
     
     
     
     
       }
     
     
    }

  4. #4
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Many problems with JTable

    Well, I seem to have been shooting myself in the foot.

    It seems that my attempt to resize the cells automatically using that class I found online was part of the issue. I still can't find a way to get it to have the cells have a smaller height for the non-image ones, but that's a small loss. (Though, if you know how, please tell me. I couldn't find a way to set row height for just certain cells in a row on Google and I've spent hours.)

    I got everything else now to work. Now to figure out how to work a Java XML Parser and use it to read stuff from an XML file..............

Similar Threads

  1. Replies: 21
    Last Post: November 27th, 2012, 10:58 PM
  2. Problems with Jtable.setModel() with Db connecton
    By justyStepi in forum JDBC & Databases
    Replies: 0
    Last Post: September 18th, 2012, 07:22 AM
  3. JTable
    By adra in forum Java Theory & Questions
    Replies: 5
    Last Post: August 30th, 2011, 07:05 AM