Introduction
It so happened that as a designer, I need room for creativity in the implementation of any written programs. Long time ago I laid eyes on such a platform as Java, as I always dreamed of cross-platform software. And just recently, I decided to master such a great component in Java, like JTable, and for the reason that I always liked to use tables in my programs.
In general, I set myself an easy task - to create a table that I could save as an object to a file and track user input in parallel, highlighting errors and simplifying communication with a table of my program by highlighting the most important elements of the table. So, as I support programming on the principle of step-by-step debugging when writing code, the presence of ready-made pieces of stable code on the Internet was very important to me ... But ... After a thorough search, it was experimentally established
that, on the Internet, there are only a couple of normal sources for getting more or less good code.
No, no, I will not send you
here (A popular quote from javatalks.ru users, etc. - “before asking a stupid question, look
here ...”).
')
and
here . (How to Use Tables - tutorial)
or
here (Using Swing Components: Examples).
or in
standard table help
Although, I say this is not simple, as I looked there and realized that the Java docks are a bit out of date, both in perception and in the presence of intelligible working code (I used Java version 7.01). But still, without reading these reference materials, you will never understand the very essence, logic and psychology of Java tables.
For this reason, the stable example of JTable table serialization described below will work for you the way you want it, only if you understand what you are doing and what you want to get. Lastly, I’ll add - some pieces of code were collected on the Internet at various resources (for which we thank everyone for all), but they are all united by one thing - I debugged them myself and wiped my program, that is, I did not find a perfectly working code. Although ... no. I built my code only because I took the working code of the serialization program from one of the English-speaking resources, which I crashed when I tried to change the data in the table (the link to the resource was unfortunately lost) ...
But "about dragons" code in order.
Oh how are you eloquent, dragon great error log
Well, now is the time to tell me: “Are you doing dancing with a tambourine? Or did not read
this ? Googly better and do not clog us all brains with trifles for design ... We can do without it. "And the truth is, after reading this translation of the book" Java 2. Volume 2. Subtleties of programming. Author - Kay Horstman and Harry Cornell "(I have the 8th printed edition), I found a great code:
// FileOutputStream fos = new FileOutputStream("temp.out"); ObjectOutputStream oos = new ObjectOutputStream(fos); SerialTest st = new SerialTest(); oos.writeObject(st); oos.flush(); oos.close(); // FileInputStream fis = new FileInputStream("temp.out"); ObjectInputStream oin = new ObjectInputStream(fis); TestSerial ts = (TestSerial) oin.readObject(); System.out.println("version="+ts.version);
which under no circumstances wanted to work with tables, wherever I put the magic implements Serializable magic mantra.
Yes, you do not implement a separate class, and the tuli immediately in the JTable when creating your TableCellRenderer dynamically and in it do everything you need! - they said some ...
-Nooo ... You need a separate class, because Java is not “fucking crazy” and nobody canceled MVC models. - others said.
In general, all these disputes and proposals for the implementation of classes and methods that did not work or worked partially, I was very upset and I even wanted to spit on everything and make a table with a default gray graphical interface ... Suddenly, in one of the foreign forums, I found a code that, according to the author’s assurances, worked one hundred percent and fits any designer’s whims. Having carefully considered this code, I found the method that created the table template if the file was missing on disk and filled the table with it. After checking the code (very close to the above), I was surprised to find that it works! “Oh heaven!” - I thought - “Is my prayer really heard and I can give the tambourine back to my little daughter?!” ... But as soon as I entered the data into the table and pressed the save button ... like a tambourine, I again became needed ...
Now, it has become a matter of honor! I could not allow some kind of mantra to influence the absence or presence of a tambourine in my little daughter and on nervous breakdowns in the neighbors due to the constant tambourine sounding ... In short, after a short battle with the selection in the table:
I decided to turn to the shamans of the whole world and to the creators themselves ... And I went to the Orakla bug tracker, where I was surprised to see that
it was a mistake.
And the battle lasts for many years, with the Java version "1.4.0-beta2"
Then I saw that especially enlightened shamans, like Kleopatra, have been cutting off the wings of the dragon Error Log for a long time with a simple challenge:
// , // "", table.editingStopped(null); // , Java, /*: * * The first issue in the description deals with the improper behavior * of losing edits on focus exit the first time but for not subsequent * attempts. The problem was correctly diagnosed by Kleopatra in bug * report 4518907. java.swing.JTable indeed does need to set 'editorRemover' * to null after calls to * removePropertyChangeListener("focusOwner", editorRemover); * in both removeNotify() and in removeEditor(). * */ // , table.removeEditor(); // table.removeNotify();
Well, that's all, the dragon is really defeated ...
But no, he was moved to classes with TableCellRenderer ...
Drawing lessons, or "No, no, I need to highlight the line with an error of red"
After not complicated dances at the new campfire kindled by the next table visualization errors, I found that it would be appropriate to implement two classes of table drawing, one for the cells and one for the column names (labels):
// class JCTableCellRenderer extends JLabel implements TableCellRenderer, Serializable {} // class JColumnRenderer extends JLabel implements TableCellRenderer, Serializable {}
Now all this needs to be declared:
// JCTableCellRenderer table.setDefaultRenderer(Object.class, new JCTableCellRenderer());
At the beginning of the loadColumn () method, we write:
Everything immediately fell into place, all the data was perfectly read and rendered.
Now I began to search the Internet for the most necessary for me, drawing cells, rows and columns.
Oddly enough, but all the links with the promise of exactly what I need, led
here .
the information is very valuable, but the design is scanty and about TableCellRenderer, little has been said. I started experimenting myself with different ways of coloring the table and what did I learn in the end?
// public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {...} // : //@param: table - , , //@param: value - //@param: isSelected - ( ) //@param: hasFocus - //@param: row - //@param: column -
Examples of staining in the JTable table:
// JLabel, , - JLabel c = new JLabel(value.toString()); // , - value.toString() // "jpg", if(value.equals("jpg")){c.setOpaque(true);c.setBackground(new Color(152, 251, 152));} // if(column==0){c.setOpaque(true);c.setBackground(new Color(255, 248, 220));} // , "iff" if(table.getValueAt(row, 7).equals("iff")){ c.setOpaque(true); c.setBackground(new Color(255, 105, 180)); c.setForeground(Color.white);} // : , //... //, : (String)table.getModel().getValueAt(row, 4) // int a = Integer.parseInt(""+table.getModel().getValueAt(row, 4)); int b = Integer.parseInt(""+table.getModel().getValueAt(row, 5)); if(a > b) { c.setOpaque(true);c.setBackground(Color.red);c.setForeground(Color.yellow); if(column==8) { c.setText("Error this value: colomn - \"Start\", row - " + (row+1)); table.getModel().setValueAt(c.getText(), row, column); } } else { // , , // , //, , // if(column==8) { java.io.File f = new java.io.File((String) table.getModel().getValueAt(row, 9)); if(f.exists()) { table.getModel().setValueAt("<This file is exist>", row, column); } else { table.getModel().setValueAt("<This file is not exist!!!>", row, column); c.setOpaque(true);c.setBackground(Color.red);c.setForeground(Color.yellow); } } } // http://skipy-ru.livejournal.com/1577.html // - // using L&F colors if(isSelected) { c.setOpaque(true); c.setForeground(isSelected ? UIManager.getColor("Table.selectionForeground") : UIManager.getColor("Table.foreground")); c.setBackground(isSelected ? UIManager.getColor("Table.selectionBackground") : UIManager.getColor("Table.background")); c.setBorder(hasFocus ? BorderFactory.createLineBorder(UIManager.getColor("Table.selectionForeground"), 1) : BorderFactory.createEmptyBorder(2, 2, 2, 2)); // , // if(value.equals("jpg")){c.setOpaque(true);c.setBackground(new Color(0, 128, 128));} if(value.equals("png")){c.setOpaque(true);c.setBackground(new Color(250, 250, 210));} if(value.equals("iff")){c.setOpaque(true);c.setBackground(new Color(72, 61, 139));c.setForeground(Color.white);} if(column==0){c.setOpaque(true);c.setBackground(new Color(210, 105, 30));} }
Well, that seems to be all.
Now everything works - saved to a file and painted in the desired color.
To implement my idea, I used the Eclipse v development environment. 3.7

Well ... If you read this far, thank you for your time.
If you want to ask a question like: “How can I do this with a database?” Or “Why, when I implement loops like when checking values ​​in the JCTableCellRenderer class, I have a terrible table hanging,” then I might add that the databases above I did not use (but for some reason I am sure that it works stably), and also the cycles implemented in drawing classes, this is the same perversion as the timers on the timeline of the clips in Flash. I recommend to always optimize your code on the principle - “the simpler, the faster”.
The necessary external classes and the code of the program itself
are attached (open in Eclipse).
Good luck everyone.