I had a Person class (I mentioned it earlier in other threads) and I had a class called TablePanel and a Tester class. It showed my picture.
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; } }
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; import javax.swing.JInternalFrame; import javax.swing.JPopupMenu; import javax.swing.JMenuItem; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; 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"}; private JInternalFrame tableFrame; 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.setPreferredScrollableViewportSize(new java.awt.Dimension(500, 200)); personTable.setModel(new MyTableModel(data, headers)); //personTable.setFillsViewportHeight(true); //personTable.setAutoResizeMode(JTable. AUTO_RESIZE_OFF); 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(new JScrollPane(personTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ) , BorderLayout.NORTH); 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()); //personTable.getTableHeader().getColumnModel().getColumn(0).setPreferredWidth(400); // personTable.getColumnModel().getColumn(7).setColumnSelectionAllowed(false); //be.alex.examples.ColumnsAutoSizer.sizeColumnsToFit(personTable, 3); personTable.getColumnModel().getColumn(7).setPreferredWidth(400); personTable.setRowHeight(200); for (int i =0; i < 7; i++) { personTable.getColumnModel().getColumn(i).setPreferredWidth(400); personTable.getColumnModel().getColumn(i).setCellEditor( new javax.swing.DefaultCellEditor((new SpecialTextField()))); } //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); }}); System.out.println(personTable.getColumnCount()); } protected class MyTableModel extends javax.swing.table.DefaultTableModel { public MyTableModel(Object[][] data, Object[] columnNames) { super(data, columnNames); } public boolean isCellEditable(int row, int col) { if (row == 0 && col == 7) return false; else return true; } } protected class SpecialTextField extends javax.swing.JTextField { private JPopupMenu popup; private JMenuItem copy, paste, selectAll; public SpecialTextField() { super(); popup = new JPopupMenu(); setComponentPopupMenu(popup); copy = new JMenuItem("Copy"); copy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { copy(); }}); selectAll = new JMenuItem("Select All"); selectAll.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { selectAll(); }}); paste = new JMenuItem(new javax.swing.text.DefaultEditorKit.PasteAction()); paste.setText("Paste"); popup.add(copy); popup.add(paste); popup.add(selectAll); } } public JTable getTable() { return personTable; } public Person getPerson() { return p; } }
package addressbook.gui; import javax.swing.JScrollPane; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Tester1ForTable extends JFrame { public Tester1ForTable() { add (new TablePanel()); pack(); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); //JOptionPane.showMessageDialog(null, "Could not find the xml file. " + System.getProperty("line.break") + "Creating new one....', "There was a disturbance in the Force....", JOptionPane.ERROR_MESSAGE, new javax.swing.ImageIcon("./oops.gif")); } public static void main(String[] args) { new Tester1ForTable(); } }
working.jpgworking.jpg
When I tried to make it more sophisticated and get toward the final project, I added the following classes. (Also, that main class above was just a test one. The one below is actually the project main class.)
package addressbook.util; import java.util.TreeSet; import java.util.Iterator; public class PersonSearcher { private TreeSet<Person> people; public PersonSearcher(TreeSet<Person> people) { this.people = people; } public boolean add(String name, String address, String city, String zip, String home, String cell, String email, String picture) { return people.add(new Person(name, address, city, zip, home, cell, email, picture)); } public boolean remove(Person p) { return people.remove(p); } public java.util.ArrayList<Person> findByName(String name) { java.util.ArrayList<Person> peoples = new java.util.ArrayList<Person>(); Iterator<Person> it = people.iterator(); while (it.hasNext()) { Person temp = it.next(); if (temp.getName().equals(name)) peoples.add(temp); } return peoples; } public java.util.ArrayList<Person> findByCity(String city) { java.util.ArrayList<Person> peoples = new java.util.ArrayList<Person>(); Iterator<Person> it = people.iterator(); while (it.hasNext()) { Person temp = it.next(); if (temp.getCity().equals(city)) peoples.add(temp); } return peoples; } public java.util.ArrayList<Person> findByZip(String zip) { java.util.ArrayList<Person> peoples = new java.util.ArrayList<Person>(); Iterator<Person> it = people.iterator(); while (it.hasNext()) { Person temp = it.next(); if (temp.getZip().equals(zip)) peoples.add(temp); } return peoples; } public TreeSet<Person> getPeople() { return people; } public Person get(int index) { if (index < 0 || index >= people.size()) { throw new IndexOutOfBoundsException("Bad index."); } Iterator<Person> it = people.iterator(); int count = 0; while (it.hasNext()) { Person p = it.next(); if (count == index) return p; else count++; } return null; } }
(Note: I don't think PersonSearcher is the problem. Though, maybe it's my get() method.)
package addressbook.util; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.Attributes; import java.util.TreeSet; import java.io.File; import java.io.FileNotFoundException; import javax.swing.JOptionPane; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class PersonXMLHandler extends DefaultHandler { private TreeSet<Person> peopleList; private File xmlFile; private Person tmp; private String tmpValue; public PersonXMLHandler(TreeSet<Person> peopleList, File xmlFile) { if (!xmlFile.exists()) { JOptionPane.showMessageDialog(null, "Could not find the xml file. " + System.getProperty("line.separator") + "Creating new one.", "There was a disturbance in the Force....", JOptionPane.ERROR_MESSAGE, new javax.swing.ImageIcon("./oops.gif")); java.io.PrintWriter pw = null; try { pw = new java.io.PrintWriter(new File(xmlFile.getCanonicalPath())); } catch(java.io.FileNotFoundException fnfe) { } catch(java.io.IOException iowe) { } pw.println("<addressbook>"); pw.println("<person>"); pw.println("<name> Unnamed </name>"); pw.println("<address> </address>"); pw.println("<city> </city>"); pw.println("<zip> </zip>"); pw.println("<home> </home>"); pw.println("<cell> </cell>"); pw.println("<email> </email>"); pw.println("<picture> noPic.jpg </picture>"); pw.println("</person>"); pw.println("</addressbook>"); pw.close(); peopleList.add(new Person()); this.peopleList = peopleList; try { this.xmlFile = new java.io.File(xmlFile.getCanonicalPath()); } catch(java.io.IOException ioe) { } parseDocument(); return; } this.peopleList = peopleList; this.xmlFile = xmlFile; parseDocument(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("person")) tmp = new Person(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("person")) peopleList.add(tmp); if(qName.equalsIgnoreCase("name")) tmp.setName(tmpValue); if (qName.equalsIgnoreCase("address")) tmp.setAddress(tmpValue); if (qName.equalsIgnoreCase("city")) tmp.setCity(tmpValue); if(qName.equalsIgnoreCase("zip")) tmp.setZip(tmpValue); if(qName.equalsIgnoreCase("home")) tmp.setHomePhone(tmpValue); if (qName.equalsIgnoreCase("cell")) tmp.setCellPhone(tmpValue); if(qName.equalsIgnoreCase("email")) tmp.setEmail(tmpValue); if(qName.equalsIgnoreCase("picture")) tmp.setPicture(tmpValue); } @Override public void characters(char[] ac, int i, int j) throws SAXException { tmpValue = new String(ac, i, j); } private void parseDocument() { // parse SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); parser.parse(xmlFile, this); } catch (ParserConfigurationException e) { System.out.println("ParserConfig error"); } catch (SAXException e) { System.out.println("SAXException : xml not well formed"); } catch (java.io.IOException e) { System.out.println("IO error"); } } }
package addressbook.gui; import javax.swing.JTabbedPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.BorderLayout; import javax.swing.BorderFactory; import java.awt.Color; import addressbook.util.PersonSearcher; import addressbook.util.PersonXMLHandler; import java.util.TreeSet; import javax.swing.border.EtchedBorder; import addressbook.util.Person; public class JAddressFrame extends JFrame { private JTabbedPane tabPane; private JMenuBar mBar; private JMenu file, search, about; private JMenuItem print, addNew, remove, exit; private JMenuItem searchByName, searchByCity, searchByZip; private JMenuItem about2; private PersonSearcher pSearch; public JAddressFrame() { super("Address book"); JPanel contentPane = new JPanel(); add(contentPane); contentPane.setLayout(new BorderLayout()); tabPane = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT); contentPane.add(tabPane, BorderLayout.PAGE_START); TreeSet<Person> peoples = new TreeSet<Person>(); PersonXMLHandler pxml = new PersonXMLHandler(peoples, new java.io.File("./people.xml")); pSearch = new PersonSearcher(peoples); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); mBar = new JMenuBar(); file = new JMenu("File"); mBar.add(file); print = new JMenuItem("Print"); print.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, ActionEvent.CTRL_MASK)); file.add(print); file.addSeparator(); addNew = new JMenuItem("Add New Person"); addNew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, ActionEvent.CTRL_MASK)); file.add(addNew); remove = new JMenuItem("Remove Person"); remove.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, ActionEvent.CTRL_MASK)); file.add(remove); file.addSeparator(); exit = new JMenuItem("Exit"); exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); file.add(exit); setJMenuBar(mBar); search = new JMenu("Search"); mBar.add(search); searchByName = new JMenuItem("Search By Name"); search.add(searchByName); searchByCity = new JMenuItem("Search By City"); search.add(searchByCity); searchByZip = new JMenuItem("Search By Zip"); search.add(searchByZip); about = new JMenu("About"); mBar.add(about); about2 = new JMenuItem("About"); about.add(about2); createBorderedMenuBarAndMenus(mBar, Color.RED, Color.WHITE, Color.BLUE); for (int i =0; i < pSearch.getPeople().size(); i++) { tabPane.addTab(pSearch.get(i).getName(), new TablePanel(pSearch.get(i))); //((TablePanel) (tabPane.getComponentAt(i))).repaint(); } } private void createBorderedMenuBarAndMenus(JMenuBar mBar, Color backgroundColor, Color borderColor, Color borderColor2) { mBar.setBackground(backgroundColor); mBar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED, borderColor, borderColor2)); JMenu temp = null; for (int i=0; i < mBar.getMenuCount(); i++) { temp = mBar.getMenu(i); if (temp != null) { formatJMenus(temp, backgroundColor, borderColor, borderColor2); } } } private void formatJMenus(JMenuItem menu, Color backgroundColor, Color borderColor, Color borderColor2) { if (menu != null) { menu.setBackground(backgroundColor); menu.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED, borderColor, borderColor2)); menu.setOpaque(true); if (menu instanceof JMenu) { JMenu menu2 = (JMenu) menu; for (int i =0; i < menu2.getItemCount(); i++) { formatJMenus((JMenuItem) (menu2.getItem(i)), backgroundColor, borderColor, borderColor2); } } } } }
package addressbook.gui; public class AddressBookTester { public static void main(String[] args) { new JAddressFrame(); } }
Now, when I run it, it doesn't show the picture, at least, not until I upload a new one. But, as it would really ruin part of the point of what I'm trying, I need the picture to show up right away. My default picture, which is in the same spot, pretty much, as the code, is
noPic.jpg
When I run it now, however, it won't show up.
not working.jpg
However, once I hit "upload" and upload, it'll show the picture all of a sudden. So I know that my structure has to been working right with my CellRenderer subclass.
working now.jpg
I can say that it's not in the part where I'm formatting the menus and probably couldn't be in any but the setPicture() part of the Person class. (Though I doubt it as it worked there earlier and works when I upload.)
The PersonSearcher doesn't appear to be it.
It likely could be because of the fact that I don't have canonical path for the default image but the upload has it.
It may well be a glitch in the way I'm using my XML Parser (the PersonXMLHandler or whatever it was called).
I doubt it is anything in the JAddressBook or the testing class for the project. I have no clue where and can't pair down the code in there too much further or it wouldn't compile for you.
I'm just baffled as to what could have happened to make it work with just Person, TablePanel, and that test class at the top, but not work when I add PersonSearcher, PersonXMLHandler, JAddressBook, and the project test class. And why, if it won't work initially, will it show suddenly when I use the upload button? (Somehow, I feel that the canonical path may be an issue. The other likely culprit is the XML parser class.)
I'm just so lost as to what's going wrong.