TablecellRenderer and TableCellEditor

Source: Internet
Author: User

TableCellRenderer is used to draw and display the value of the current cell. You can use text, numeric values, or images to represent the content. Of course, the most powerful display method is to customize your renderer component, you can use Java2D to draw various effects.

TableCellEditor is mainly used to edit components when users click on a specific cell. Therefore, TableCellEditor can also perform interactive operations in addition to drawing functions like TableCellRenderer, for example, a more complex dialog box is displayed in the cell drop-down box, a check box, or even a button to allow users to enter and edit the dialog box.

 

They are all subclasses of JPanel.

Public Component getTableCellEditorComponent (JTable arg0, Object arg1,
Boolean arg2, int arg3, int arg4)
{
// TODO Auto-generated method stub
Return null;
}

Is the main method of TableCellEditor this

If you add a JButton, the components are added to the basic JComponent.

 

TableCellRenderer is similar

------------------------------------------------

Import java. awt .*;
Import java. awt. event .*;
Import javax. swing .*;
Import javax. swing. table .*;
// Main class
// @ SuppressWarnings ("unchecked ")
Public class TryJTable extends JFrame
{
Private static final long serialVersionUID = 1L;
// Create a custom table model object
MyTableModel dtm = new MyTableModel ();
// Create a JTable object
JTable jt = new JTable (dtm );
// Encapsulate JTable into the scroll pane
JScrollPane jsp = new JScrollPane (jt );
// Custom table model
Private class MyTableModel extends acttablemodel
{

Private static final long serialVersionUID = 1L;
// Create an array of different column types
Class [] typearray =
{Object. Class, double. Class, Boolean. Class, icon. class, color. Class };
// Create a column title String Array
String [] Head = {"object", "Number", "Boolean", "icon", "color "};
// Create the initial table data
Object [] [] DATA = {"here is the string 1", new INTEGER (20), new Boolean (true ),
New imageicon ("D:/p1.gif"), color. Black },
{"Here is string 2", new Double (12.34), new Boolean (false ),
New ImageIcon ("D:/p2.gif"), Color. darkGray },
{"Here is string 3", new Integer (125), new Boolean (true ),
New ImageIcon ("D:/p3.gif"), Color. white }};
// Override the getColumnCount Method
Public int getColumnCount ()
{
Return head. length;
}
// Override the getRowCount Method
Public int getRowCount ()
{
Return data. length;
}
// Override the getColumnName Method
Public String getColumnName (int col)
{
Return head [col];
}
// Override the getValueAt Method
Public Object getValueAt (int r, int c)
{
Return data [r] [c];
}
// Override the getColumnClass Method
Public Class getColumnClass (int c)
{
Return typeArray [c];
}
// Override the isCellEditable Method
Public boolean isCellEditable (int r, int c)
{
Return true;
}
// Override the setValueAt Method
Public void setValueAt (Object value, int r, int c)
{
Data [r] [c] = value;
//
This. fireTableCellUpdated (r, c );
}
}
// Custom painter
Private class MyCellRendererForColorClass
Extends JLabel implements TableCellRenderer
{
Private static final long serialVersionUID = 1L;
// Define the constructor
Public MyCellRendererForColorClass ()
{
// Set the label to an opaque state
This. setOpaque (true );
// Set the text alignment of the label to center
This. setHorizontalAlignment (JLabel. CENTER );
}
// Implement the getTableCellRendererComponent method for obtaining the Rendering Control
Public Component getTableCellRendererComponent (JTable table, Object value,
Boolean isSelected, boolean hasFocus, int row, int column)
{
// Obtain the color to be rendered
Color c = (Color) value;
// Set the background color based on the parameter value
This. setbackground (C );
// Set the foreground color to the background color.
This. setforeground (new color (255-c.getred ()
, 255-c.getgreen (), 255-c.getblue ()));
// Set the label to display the RGB Value
This. settext ("[" + C. getred () + "," + C. getgreen () + "," + C. getblue () + "]");
// Return the result
Return this;
}
}
// Declare a custom Color editor
Class MyEditorForColorClass extends actcelleditor
Implements TableCellEditor, ActionListener
{
Private static final long serialVersionUID = 1L;
// Define the Color variable
Color c;
// Define dialog box Variables
JDialog jd;
// Create a button
JButton jb = new JButton ();
// Create a JColorChooser object
JColorChooser jcc = new JColorChooser ();
// Declare a constant
Public static final String EDIT = "edit ";
// Define the constructor
Public MyEditorForColorClass ()
{
// Register the listener with a click
Jb. addActionListener (this );
// Set this command
Jb. setActionCommand (EDIT );
// Obtain the color selector
Jd = JColorChooser. createDialog (jb, "select color", true, jcc, this, null );
}
// Implement the actionreceivmed Method
Public void actionreceivmed (ActionEvent e)
{
// Test whether the obtained Action Command is equal to the EDIT constant
If (e. getActionCommand (). equals (EDIT ))
{
// Set the color of the pressed background
Jb. setBackground (c );
// Set the foreground color to the background color.
Jb. setForeground (new Color (255-c.getRed ()
, 255-c.getGreen (), 255-c.getBlue ()));
// The RGB value is displayed in the set button.
Jb. setText ("[" + c. getRed () + "," + c. getGreen () + "," + c. getBlue () + "]");

// Set the color of the color selector
Jcc. setColor (c );
// Set the color selector to be visible
Jd. setVisible (true );
// Notify all listeners to create event objects in a delayed manner
This. fireEditingStopped ();
}
Else
{
// Obtain the color
C = jcc. getColor ();
}
}
// Define the color value returned by the getCellEditorValue Method
Public object getcelleditorvalue ()
{
Return C;
}
// Override the gettablecelleditorcomponent Method
Public component gettablecelleditorcomponent (jtable table,
Object value, Boolean isselected, int row, int column)
{
C = (color) value;
Return JB;
}
}
// Declare an Icon-type custom Editor
Class MyEditorForIconClass extends actcelleditor
Implements TableCellEditor, ActionListener
{
Private static final long serialVersionUID = 1L;
// Define the Icon variable
Icon;
// Create a button
JButton jb = new JButton ();
// Create a JColorChooser object
JFileChooser jfc = new JFileChooser ();
// Declare a constant
Public static final string edit = "edit ";
// Define the constructor
Public myeditorforiconclass ()
{
// Register the listener with a click
JB. addactionlistener (this );
// Set this command
JB. setactioncommand (edit );
}
// Implement the actionreceivmed Method
Public void actionreceivmed (ActionEvent e)
{
// Test whether the obtained Action Command is equal to the EDIT constant
If (e. getActionCommand (). equals (EDIT ))
{
// Set the button
Jb. setIcon (icon );
// Display the file selector dialog box
Jfc. showOpenDialog (jb );
// Get new image
If (jfc. getSelectedFile ()! = Null)
{
Icon = new ImageIcon (jfc. getSelectedFile (). getAbsolutePath ());
}
// Notify all listeners to create event objects in a delayed manner
This. fireEditingStopped ();
}
}
// Define the getCellEditorValue method return icon
Public Object getCellEditorValue ()
{
Return icon;
}
// Override the getTableCellEditorComponent Method
Public Component getTableCellEditorComponent (JTable table,
Object value, boolean isSelected, int row, int column)
{
Icon = (Icon) value;
Return jb;
}
}

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/wzh32/archive/2009/05/01/4141543.aspx

-----------------------------------------------------

Import java. awt .*;

Import javax. swing .*;
Import javax. swing. table .*;

Public class RoundColorTable extends JFrame

{
Private string [] colname = {"1st columns", "2nd columns", "3rd columns", "4th columns"}; // header information
Private string [] [] DATA = new string [10] [5]; // table content
Private jtable table;
Public roundcolortable (){
// Table content assignment
For (INT I = 0; I <10; I ++ ){
For (Int J = 0; j <5; j ++ ){
Data [I] [J] = "(" + (J + 1) + "," + (I + 1) + ")";
}
}
Table = new JTable (new DefaultTableModel (data, colname ));
TableCellRenderer CTL = new ColorTableCellRenderer ();
Table. setDefaultRenderer (Object. class, CTL); // Add a Renderer for JTable, because it is for all cells in the table, all objects. class
Add (new JScrollPane (table), BorderLayout. CENTER );
SetVisible (true );
SetSize (500,300 );
Setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
}
Public static void main (String args []) {
New RoundColorTable ();
}
}

Class ColorTableCellRenderer extends DefaultTableCellRenderer
{
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer ();
Public Component getTableCellRendererComponent (JTable table, Object value,
Boolean isSelected, boolean hasFocus, int row, int column ){
If (row % 2 = 0 ){
// Call the base class Method
Return super. getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column );
}
Else {
Return renderer. getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column );
}
}
// This class inherits from JLabel. Graphics is used to draw cells and draw red lines.
Public void paintComponent (Graphics g ){
Super. paintComponent (g );
Graphics2D g2 = (Graphics2D) g;
Final BasicStroke stroke = new BasicStroke (2.0f );
G2.setColor (Color. RED );
G2.setStroke (stroke );
G2.drawLine (0, getHeight ()/2, getWidth (), getHeight ()/2 );
}
}

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/chosen0ne/archive/2009/08/16/4453267.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.