Java Swing - Jtable Text Alignment And Column W... | FAST VERSION |
The table itself was simple. It displayed a list of product orders for "QuickShip Logistics," a client whose patience was wearing thin. The data was perfect. The backend was solid. But the presentation? It was a crime against visual design.
It wasn't modern. It wasn't glamorous. But when Lena saw the working table the next morning, her simple "Oh, that looks perfect" was the only reward he needed.
At 11:47 PM, with bloodshot eyes and trembling fingers, he compiled one last time.
He resized the Description column by dragging the header. The text rewrapped in real-time , adjusting to the new width like water finding its level. Java Swing - JTable Text Alignment And Column W...
Simon had grunted in reply. He knew Swing was ancient. He knew that JTable was powerful but quirky. He had spent the first two hours searching Stack Overflow, copying and pasting snippets that promised the world but delivered only compiler errors.
He looked at the Description column. A long sentence stretched across multiple lines, wrapping neatly at the column boundary, pushing the row taller just enough to contain it. The next row, with a short description, was shorter. The row heights were dynamic. Perfect. Beautiful.
Simon's eye started to twitch. He missed dinner. He heard Lena leave, shouting "Good luck!" over her shoulder. He was alone with the JTable . The table itself was simple
He tried the naive approach first. He overrode the getColumnClass() method in his TableModel to return Integer.class for the quantity and Double.class for the price. Swing, in its automatic mercy, should have right-aligned numbers. It did not. The numbers remained left-aligned, mocking him.
The numbers were perfectly right-aligned. The dollar signs lined up like soldiers on parade. The quantities were crisp and flush to the right.
The product descriptions, which could be verbose sentences like "Heavy-duty, weather-resistant, industrial-grade aluminum cargo strap (10-pack)," were bleeding off the right edge of the column. Users had to drag the column header manually every single time to read the full text. And the numbers—the quantities, unit prices, and totals—were sitting stubbornly on the left edge, ignoring every international standard of financial reporting that demands numbers be right-aligned. The backend was solid
Simon had been staring at the same screen for four hours. The coffee in his mug had long gone cold, forming a thin, oily film on top. Around him, the open-plan office hummed with the quiet chaos of a startup on the edge of a deadline. But for Simon, the world had shrunk to a single, infuriating component: a JTable in a Java Swing application.
He wrote the class by hand, line by line, feeling like a scribe copying a lost manuscript. He added a JList of JTextArea objects as a cache to improve performance. He calculated the row height dynamically in the JTable 's prepareRenderer method.