Warp text in JTable
hi,
I have an application with Jtable.
In the Jtable I want to display warp text.
In order to do so I use HTML tags.
My problem is that when i try to get the height of the cell in order to ditrminate the row height I get wrong height.
I think that the height that return from the cell is one row text height althoght the cell contains more then one row.
I'll be glad to get help with that.
thanks, yaniv
Maybe this article will help:
[http://www.javaspecialists.eu/archive/Issue106.html|http://www.javaspecialists.eu/archive/Issue106.html]
Similar Messages
-
I have Adobe Photoshop Elements 10. It came installed on my HP Desktop. I am can not get the warp text tool to work. It has worked in the past. Once I click warp text, the little window does not pop up, and if I try to do anything else after I click warp text, it wont let me. Just sounds the ding, alert, can still slightly navigate the program but can not use any other tools after clicking warp text. I just have to open task manager and close the program. not sure if I'm doing something wrong or maybe I just need to uninstall and re install. Having trouble finding out how to uninstall and reinstall because the program came pre installed on my desktop.
It actually sounds like the warp text window is opening off screen.
Resetting the photoshop elements 10 preferences should fix it.
*Press and hold the Shift+Ctrl+Alt keys just after you start the launch of the photoshop elements 10 editor
*Keep holding the keys down until you get a dialog asking if you want to delete the adobe photoshop elements setting file
*Press Yes -
Warp text in flash such as arcing or bending
is there any way to warp text in flash such as arcing or
bendingyes, but it's not easy and definitely not a beginning a.s.
project. you can distribute your text into different textfields
that you arrange in an arc or you can use the bitmapdata class and
its displacementmap filter. -
Centering text in JTable cells
How do I center the text in JTable cells? By default, all data is left aligned.
Thanks,
JasonRead up on cell renderers from the Swing tutorial on "Using Tables":
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender
Here's an example to get you started.
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.text.*;
public class TableRenderer extends JFrame
public TableRenderer()
String[] columnNames = {"Date", "String", "Integer", "Decimal", "Boolean"};
Object[][] data =
{new Date(), "A", new Integer(1), new Double(5.1), new Boolean(true)},
{new Date(), "B", new Integer(2), new Double(6.2), new Boolean(false)},
{new Date(), "C", new Integer(3), new Double(7.3), new Boolean(true)},
{new Date(), "D", new Integer(4), new Double(8.4), new Boolean(false)}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
// Create cell renderer
TableCellRenderer centerRenderer = new CenterRenderer();
// Use renderer on a specific column
TableColumn column = table.getColumnModel().getColumn(3);
column.setCellRenderer( centerRenderer );
// Use renderer on a specific Class
table.setDefaultRenderer(String.class, centerRenderer);
public static void main(String[] args)
TableRenderer frame = new TableRenderer();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
** Center the text
class CenterRenderer extends DefaultTableCellRenderer
public CenterRenderer()
setHorizontalAlignment( CENTER );
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
return this; -
Help! How do I warp text to fit a ribbon?
Hi,
Does anybody know how to warp text to fit a shape - in this case a ribbon? Attached are two pics, hopefully showing what I'm trying to achieve!
The pencil sketch shows how the text should roughly be the second shows the clear paths that I want the text to warp to. I need the text to fill the shape of the ribbon and flow (top and bottom as if were printed on) - not just by using the clunky text path tool as shown.
Is this possible in Illustrator?
Help!
[URL=http://img402.imageshack.us/my.php?image=picture1k.png][IMG]http://img402.imageshack.us/im g402/8054/picture1k.png[/IMG][/URL]
[URL=http://img412.imageshack.us/my.php?image=balletshoeb.jpg][IMG]http://img412.imageshack.us/ img412/8373/balletshoeb.jpg[/IMG][/URL]The closest I can come to duplicating the effect you want is with the 3D effect, and mapping the text to the object. Type the text and save the text object as a Symbol. Draw the ribbon as a single path, then apply a 3D Extrude & Bevel, then apply the text (as a Symbol) to that. These last two steps can be done in the same step. Here's a quick attempt:
-
Validate user-entered text in JTable
How do I validate user entered text in JTable cell, so only the values 1234567890. are acceptet? The cell should contain only doubles....
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class aslan extends JFrame {
public aslan() {
TableModel model = new CustomTableModel();
JTable table = new JTable(model);
getContentPane().add(new JScrollPane(table), "Center");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setLocation(300,300);
setVisible(true);
private class CustomTableModel extends AbstractTableModel {
String[] headings = new String[] {
"Cost", "Item", "Type"
Object[][] data = new Object[][] {
{ new Double(12.75), "glue", "tube" },
{ new Double(15.20), "hammer", "claw" },
{ new Double(8.32), "saw", "hack" }
public int getRowCount() {
return data.length;
public int getColumnCount() {
return data[0].length;
public Object getValueAt(int row, int column) {
return data[row][column];
public void setValueAt(Object value, int row, int column) {
data[row][column] = value;
fireTableDataChanged();
public String getColumnName(int column) {
return headings[column];
public Class getColumnClass(int column) {
return data[0][column].getClass();
public boolean isCellEditable(int row, int column) {
return true;
public static void main(String[] args) {
new aslan();
} -
Control handles or points and warping text
The transform controls in Photoshop CS6 disappear as soon as I click on the warp mode icon, preventing me from manually warping the layer on which I am working. Oh sure, I can click on Show Transform Controls and, voila, there they are. But as soon as I click on the icon that switches me between warp and free transform, the handles disappear (no mesh either) and without them there is no way to manually warp text or images. Because this used to work perfectly in CS5, I am just a tad frustrated. None of the prebuilt warp modes involve perspective (although I understand this option is maybe, perhaps, it's possible, coming at some point in the future) I can't even get the look I'm after with any prebuilt mode.
3D doesn't offer a simple perspective tool either. Yes, it does a lot, but not what I want.
So, why do the handles disappear and how can I get them to stick when I need them?
And, yes, I do have View > Extras active. Or at least the option is checked as active.
Thank you for any help.PECourtejoie, That was a lot of text! I did not include most of it, but I did include anything related to the video card. I hope I included what you need. If not, I can copy the whole shebang. Thank you for all your help.
Adobe Photoshop Version: 13.1.2 (13.1.2 20130105.r.224 2013/01/05:23:00:00) x64
Operating System: Windows 8 64-bit
Version: 6.2
System architecture: Intel CPU Family:6, Model:10, Stepping:7 with MMX, SSE Integer, SSE FP, SSE2, SSE3, SSE4.1, SSE4.2
Physical processor count: 4
Processor speed: 3293 MHz
Built-in memory: 8045 MB
Free memory: 4931 MB
Memory available to Photoshop: 7046 MB
Memory used by Photoshop: 60 %
Image tile size: 1024K
Image cache levels: 4
The GPU Sniffer crashed on 2/6/2013 at 3:19:27 PM
OpenGL Drawing: Enabled.
OpenGL Drawing Mode: Advanced
OpenGL Allow Normal Mode: True.
OpenGL Allow Advanced Mode: True.
OpenGL Allow Old GPUs: Not Detected.
OpenCL Version: 1.1 CUDA 4.2.1
OpenGL Version: 3.0
Video Rect Texture Size: 16384
OpenGL Memory: 1024 MB
Video Card Vendor: NVIDIA Corporation
Video Card Renderer: GeForce GTX 650 Ti/PCIe/SSE2
Display: 2
Display Bounds: top=-30, left=1680, bottom=1020, right=3360
Display: 1
Display Bounds: top=0, left=0, bottom=1050, right=1680
Video Card Number: 2
Video Card: NVIDIA GeForce GTX 650 Ti
Driver Version: 9.18.13.1106
Driver Date: 20130118000000.000000-000
Video Card Driver: nvd3dumx.dll,nvwgf2umx.dll,nvwgf2umx.dll,nvd3dum,nvwgf2um,nvwgf2um
Video Mode: 1680 x 1050 x 4294967296 colors
Video Card Caption: NVIDIA GeForce GTX 650 Ti
Video Card Memory: 1024 MB
Video Card Number: 1
Video Card: Intel(R) HD Graphics 3000
Driver Version: 9.17.10.2932
Driver Date: 20121212000000.000000-000
Video Card Driver: igdumd64.dll,igd10umd64.dll,igd10umd64.dll,igdumd32,igd10umd32,igd10umd32
Video Mode:
Video Card Caption: Intel(R) HD Graphics 3000
Video Card Memory: 2172 MB
Serial number: 90970570205633490069
Application folder: C:\Program Files\Adobe\Adobe Photoshop CS6 (64 Bit)\
Temporary file path: C:\Users\Sheryl\AppData\Local\Temp\
Photoshop scratch has async I/O enabled
Scratch volume(s):
C:\, 1.82T, 1.74T free
Required Plug-ins folder: C:\Program Files\Adobe\Adobe Photoshop CS6 (64 Bit)\Required\
Primary Plug-ins folder: C:\Program Files\Adobe\Adobe Photoshop CS6 (64 Bit)\Plug-ins\
Additional Plug-ins folder: not set -
I have a text layer which I want to do some warping to. When I hit the warp text tool all the options are greyed out ??? Any help ? Incidentally, I tried to just transform warp it but no "handles" appear...
In the create warped text dialog did you click on one
of the options in the dropdown menu. (it's always on none
unless you already have some warped text)
MTSTUNER -
Cannot display JLabel text in JTable
Hi, This is a simple but frustrating little problem
I am having trouble displaying the label text in a column of a JTable.
I have hacked up a copy of TableDialogEditDemo.java from the tutorials
on using JTables. This uses a renderer and editor models to deal with a
column of colors.
I have changed it to use JLabels instead. What want is for the label
text to appear and when the user selects the cell be allowed to launch
a dialog box (such as the demo program does with colorchooser).
The dialog launching funcionalty works fine but the label text does not display.
I end up with the column of JLabels as blank, even though the values
are properly set. It seems like the TableCellRenderer doesn't display the
controls text.
I've spent the better part of two work days trying to get this one to work.
Compiling and just running the code (without any interaction with the table)
shows the problem. The second column of items will be blank instead of
cells with text.
Help!
Thanks!
/Steve McCauley
Sanera Systems
[email protected]
Here is the code:
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.DefaultCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.JLabel;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.*;
import java.awt.event.*;
* This is like TableEditDemo, except that it substitutes a
* Favorite Color column for the Last Name column and specifies
* a custom cell renderer and editor for the color data.
public class TableDialogEditDemo extends JFrame {
private boolean DEBUG = false;
public TableDialogEditDemo() {
super("TableDialogEditDemo");
MyTableModel myModel = new MyTableModel();
JTable table = new JTable(myModel);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Set up renderer and editor for the Favorite Color column.
setUpColorRenderer(table);
setUpColorEditor(table);
//Set up real input validation for integer data.
setUpIntegerEditor(table);
//Add the scroll pane to this window.
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
class ColorRenderer extends JLabel
implements TableCellRenderer {
Border unselectedBorder = null;
Border selectedBorder = null;
boolean isBordered = true;
public ColorRenderer(boolean isBordered) {
super();
this.isBordered = isBordered;
// setOpaque(true); //MUST do this for background to show up.
public Component getTableCellRendererComponent(
JTable table, Object color,
boolean isSelected, boolean hasFocus,
int row, int column) {
// setBackground((Color)color);
setForeground(Color.black);
setBackground(Color.white);
System.out.println(" Label: " + ((JLabel)color).getText());
if (isBordered) {
if (isSelected) {
if (selectedBorder == null) {
selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
table.getSelectionBackground());
setBorder(selectedBorder);
} else {
if (unselectedBorder == null) {
unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
table.getBackground());
setBorder(unselectedBorder);
return this;
private void setUpColorRenderer(JTable table) {
table.setDefaultRenderer(JLabel.class,
new ColorRenderer(true));
//Set up the editor for the Color cells.
private void setUpColorEditor(JTable table) {
//First, set up the button that brings up the dialog.
final JButton button = new JButton("") {
public void setText(String s) {
//Button never shows text -- only color.
button.setBackground(Color.white);
button.setBorderPainted(false);
button.setMargin(new Insets(0,0,0,0));
//Now create an editor to encapsulate the button, and
//set it up as the editor for all Color cells.
final ColorEditor colorEditor = new ColorEditor(button);
table.setDefaultEditor(JLabel.class, colorEditor);
//Set up the dialog that the button brings up.
final JColorChooser colorChooser = new JColorChooser();
ActionListener okListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorEditor.currentLabel = new JLabel("xxx");
final JDialog dialog = JColorChooser.createDialog(button,
"Pick a Color",
true,
colorChooser,
okListener,
null); //XXXDoublecheck this is OK
//Here's the code that brings up the dialog.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// button.setBackground(colorEditor.currentColor);
// colorChooser.setColor(colorEditor.currentColor);
//Without the following line, the dialog comes up
//in the middle of the screen.
//dialog.setLocationRelativeTo(button);
dialog.show();
* The editor button that brings up the dialog.
* We extend DefaultCellEditor for convenience,
* even though it mean we have to create a dummy
* check box. Another approach would be to copy
* the implementation of TableCellEditor methods
* from the source code for DefaultCellEditor.
class ColorEditor extends DefaultCellEditor {
JLabel currentLabel = null;
public ColorEditor(JButton b) {
super(new JCheckBox()); //Unfortunately, the constructor
//expects a check box, combo box,
//or text field.
editorComponent = b;
setClickCountToStart(1); //This is usually 1 or 2.
//Must do this so that editing stops when appropriate.
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
protected void fireEditingStopped() {
super.fireEditingStopped();
public Object getCellEditorValue() {
return currentLabel;
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
((JButton)editorComponent).setText(value.toString());
currentLabel = (JLabel)value;
return editorComponent;
private void setUpIntegerEditor(JTable table) {
//Set up the editor for the integer cells.
final WholeNumberField integerField = new WholeNumberField(0, 5);
integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
DefaultCellEditor integerEditor =
new DefaultCellEditor(integerField) {
//Override DefaultCellEditor's getCellEditorValue method
//to return an Integer, not a String:
public Object getCellEditorValue() {
return new Integer(integerField.getValue());
table.setDefaultEditor(Integer.class, integerEditor);
class MyTableModel extends AbstractTableModel {
final String[] columnNames = {"First Name",
"Favorite Color",
"Sport",
"# of Years",
"Vegetarian"};
// final Object[][] data = {
// {"Mary", new Color(153, 0, 153),
// "Snowboarding", new Integer(5), new Boolean(false)},
// {"Alison", new Color(51, 51, 153),
// "Rowing", new Integer(3), new Boolean(true)},
// {"Kathy", new Color(51, 102, 51),
// "Chasing toddlers", new Integer(2), new Boolean(false)},
// {"Mark", Color.blue,
// "Speed reading", new Integer(20), new Boolean(true)},
// {"Philip", Color.pink,
// "Pool", new Integer(7), new Boolean(false)}
final Object[][] data = {
{"Mary", new JLabel("label-1"),
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", new JLabel("label-2"),
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", new JLabel("label-3"),
"Chasing toddlers", new Integer(2), new Boolean(false)},
{"Mark", new JLabel("label-4"),
"Speed reading", new Integer(20), new Boolean(true)},
{"Philip", new JLabel("label-5"),
"Pool", new Integer(7), new Boolean(false)}
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 1) {
return false;
} else {
return true;
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
System.out.println();
System.out.println("--------------------------");
public static void main(String[] args) {
TableDialogEditDemo frame = new TableDialogEditDemo();
frame.pack();
frame.setVisible(true);You pretty much hit the nail on the head. Thank!
Just didn't realize I needed to set the text of the component but with your
tip and thinking about it, it makes sense.
Actually I needed to use:
setText(t_label.getText());
Using toString got me: "java.swing......" (the components text representation)
Thanks a bunch!
/Steve -
HighLishg search text in JTable
Hi, I want to search for particular words in JTable, I am able to search for JTextComponent using HighLighter ,
same way I convered my all data of JTable to JTextComponent, but Its failing to give the Index text.indexOf(pattern, pos)(where text is my JTextComponent , pattern is my search word, and pos is 0 initial),
below is the code,
public void highlight(JTextComponent textComp, String pattern) {
// First remove all old highlights
removeHighlights(textComp);
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
System.out.println(text);
System.out.println(pattern);
System.out.println(text.indexOf(pattern, pos));
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
// Create highlighter using private painter and apply around
// pattern
hilite.addHighlight(pos, pos + pattern.length(),
myHighlightPainter);
pos += pattern.length();
} catch (BadLocationException e) {
public void highlight(JTable table, String pattern) {
// First remove all old highlights
try {
//calling table
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"One two three four"},
{"Uno dos tres quatro"},
{"Odin dva tri chetire"},
{"1111 2222 3333 4444 One"}
new String [] {
"Strings"
Class[] types = new Class [] {
java.lang.String.class
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
JTextComponent textComp = null;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
DefaultCellEditor ed = (DefaultCellEditor)table.getCellEditor(i,j);
textComp = (JTextComponent)ed.getComponent();
removeHighlights(textComp);
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
System.out.println(text);
System.out.println(pattern);
System.out.println(text.indexOf(pattern, pos));
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
// Create highlighter using private painter and apply around
// pattern
hilite.addHighlight(pos, pos + pattern.length(),
myHighlightPainter);
pos += pattern.length();
} catch (BadLocationException e) {
} It will really help if nay one find why its giving -1 for index.
Thanks
Srikanthbelow is the solution
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.DefaultHighlighter;
public class TableCellRendererBug extends JFrame {
private boolean DEBUG = false;
public TableCellRendererBug() {
super("TableCellRendererBug");
Object[][] data = { { "Jay Four Four Jay", "Four" }, { "Jay", "Jay" }, };
String[] columnNames = { "Column 1", "Column 2" };
JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(200, 50));
// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
table.setDefaultRenderer(Object.class, new CellHighlightRenderer());
System.out.println(table.getColumnClass(0).toString());
// Add the scroll pane to this window.
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
class CellHighlightRenderer extends JTextField implements TableCellRenderer {
public DefaultHighlighter high = new DefaultHighlighter();
public DefaultHighlighter.DefaultHighlightPainter highlight_painter = new DefaultHighlighter.DefaultHighlightPainter(
new Color(198, 198, 250));
public CellHighlightRenderer() {
setBorder(BorderFactory.createEmptyBorder());
setHighlighter(high);
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
setFont(table.getFont());
setValue(value);
int len = getText().length();
int first = (row & 1) + 1;
int last = (row & 1) + first + 1;
int pos =0;
String pattern="Jay";
//if (len > last) {
while ((pos = value.toString().indexOf(pattern, pos)) >= 0) {
try {
//high.addHighlight(first, last, highlight_painter);
high.addHighlight(pos, pos + pattern.length(), highlight_painter);
pos += pattern.length();
} catch (Exception e) {
e.printStackTrace();
return this;
protected void setValue(Object value) {
setText((value == null) ? "" : value.toString());
public static void main(String[] args) {
TableCellRendererBug frame = new TableCellRendererBug();
frame.pack();
frame.setVisible(true);
Srikanth -
How to catch selected text in JTable Column
Hi there,
I am learning JTable. Need help for How to get the selected text from the JTable Column which is set to be editable.
for example in JTextFiled you have method on getSelectedText(), is there any method for tracking the selected text.
Thanks in advance
MinalHere's an example of the model I used in my JTable. Not the "getValueAt" method & "getRecordAt" method. You will have to have a Record object - but it only contains the attributes of an inserted record (with appropriate getters & setters). Hope this helps.
public class FileModel5 extends AbstractTableModel
public boolean isEditable = false;
protected static int NUM_COLUMNS = 3;
// initialize number of rows to start out with ...
protected static int START_NUM_ROWS = 0;
protected int nextEmptyRow = 0;
protected int numRows = 0;
static final public String file = "File";
static final public String mailName = "Mail Id";
static final public String postName = "Post Office Id";
static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
// List of data
protected Vector data = null;
public FileModel5()
data = new Vector();
public boolean isCellEditable(int rowIndex, int columnIndex)
// The 2nd & 3rd column or Value field is editable
if(isEditable)
if(columnIndex > 0)
return true;
return false;
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
* Retrieves number of columns
public synchronized int getColumnCount()
return NUM_COLUMNS;
* Get a column name
public String getColumnName(int col)
return columnNames[col];
* Retrieves number of records
public synchronized int getRowCount()
if (numRows < START_NUM_ROWS)
return START_NUM_ROWS;
else
return numRows;
* Returns cell information of a record at location row,column
public synchronized Object getValueAt(int row, int column)
try
FileRecord5 p = (FileRecord5)data.elementAt(row);
switch (column)
case 0:
return (String)p.file;
case 1:
return (String)p.mailName;
case 2:
return (String)p.postName;
catch (Exception e)
return "";
public void setValueAt(Object aValue, int row, int column)
FileRecord5 arow = (FileRecord5)data.elementAt(row);
arow.setElementAt((String)aValue, column);
fireTableCellUpdated(row, column);
* Returns information of an entire record at location row
public synchronized FileRecord5 getRecordAt(int row) throws Exception
try
return (FileRecord5)data.elementAt(row);
catch (Exception e)
throw new Exception("Record not found");
* Used to add or update a record
* @param tableRecord
public synchronized void updateRecord(FileRecord5 tableRecord)
String file = tableRecord.file;
FileRecord5 p = null;
int index = -1;
boolean found = false;
boolean addedRow = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
{ //update
data.setElementAt(tableRecord, index);
else
if (numRows <= nextEmptyRow)
//add a row
numRows++;
addedRow = true;
index = nextEmptyRow;
data.addElement(tableRecord);
//Notify listeners that the data changed.
if (addedRow)
nextEmptyRow++;
fireTableRowsInserted(index, index);
else
fireTableRowsUpdated(index, index);
* Used to delete a record
public synchronized void deleteRecord(String file)
FileRecord5 p = null;
int index = -1;
boolean found = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
data.removeElementAt(i);
nextEmptyRow--;
numRows--;
fireTableRowsDeleted(START_NUM_ROWS, numRows);
* Clears all records
public synchronized void clear()
int oldNumRows = numRows;
numRows = START_NUM_ROWS;
data.removeAllElements();
nextEmptyRow = 0;
if (oldNumRows > START_NUM_ROWS)
fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
fireTableRowsUpdated(0, START_NUM_ROWS - 1);
* Loads the values into the combo box within the table for mail id
public void setUpMailColumn(JTable mapTable, ArrayList mailList)
TableColumn col = mapTable.getColumnModel().getColumn(1);
javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
int s = mailList.size();
for(int i=0; i<s; i++)
comboMail.addItem(mailList.get(i));
col.setCellEditor(new DefaultCellEditor(comboMail));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for mail Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Mail Id to see a list of choices");
* Loads the values into the combo box within the table for post office id
public void setUpPostColumn(JTable mapTable, ArrayList postList)
TableColumn col = mapTable.getColumnModel().getColumn(2);
javax.swing.JComboBox combo = new javax.swing.JComboBox();
int s = postList.size();
for(int i=0; i<s; i++)
combo.addItem(postList.get(i));
col.setCellEditor(new DefaultCellEditor(combo));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for post office Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Post Office Id to see a list of choices");
} -
Hello!
Could anyone help me out how center text (or left/right aligment) in JTable cells?
Best Regards
StaffanUse your own [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender]renderer?
: jay -
How To Search For a Text In JTable Column?
hi there
i want to search for specific text in a JTable Column
And If The Text Exists Highlits it?
any ideas or useful links or tutorials?Well, then that would be a Swing related question. Did you search the Swing forum to see how rendering works.
-
Vertical text in jTable headers
Hi,
I have got a jTable with quite a bit of columns in it. Is there any way I can write the text - vertically in the header (first) row.
Please let me know if you have got any suggestions.
Thanks.
halosys.I remember reading about it, maybe in the next Java version.
You can do it yourself by creating for the column headers a TableCellRenderer. -
AOA
How to remove the text from cells of JPanel. Just to refresh the GUI.
regardsHow to provide meaningful subject?
The subject of this thread does not match what you are asking in the body.
To set the value of a cell in a JTable, you can simply call setValueAt().
Read the API to find the method parameters.
Maybe you are looking for
-
OTF/PS fonts have recently stopped rendering in Flash Pro CS3 on Windows 7/64
Recently, a number of my OTF/PS fonts have stopped rendering when used in Flash Pro CS3. The fonts appear in the fonts menu, render properly in the font preview popup in the font menu, but the fonts fail to render on stage when used, with certain exc
-
Hello, I am trying to make a image slideshow for my companies new website. I used the Flash Image Viewer plugin from Dreamweaver, but it doesn't contain the transitional effect desired. Every tutorial I find talks about advancing the images through a
-
I am just getting back into using Captivate 2.0 to create some online training and I need some assistance using JavaScript/ActionScript in Flash buttons. I created a series of buttons that are part of a single Flash .swf file. I'm using these buttons
-
Regarding upload GL balance in LSMW?
Hi experts, i want to upload Gl balances through standard LSMW direct input menthod. i have to upload 1000 items with one header, due to Client rule i can upload item only upto 949 and check the (sum of debits = sum of credits) if there is any diffe
-
Hi! I just installed my new macbook pro, which runs Snow Leopard and CS4, and I was wondering what was the best way to transfer my documents and preferences from my old macbook pro which runs Leopard and CS3. Obviously I don't want to migrate my syst