Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Table comboBox

Status
Not open for further replies.

kohinoor2007

Programmer
Mar 21, 2007
69
0
0
DE
Hi guys,

Iam developing under java swing and found it difficult to achieve the following goals which I wanted to.

Iam attaching an image also along with this.

Have rendered the "StartRange" and "EndRange" columns ,so that it looks like a combobox(see figure)."SheetRange" column could use the Table default renderer.

So the behaviours I want to implement in this table are:

[1]Single mouse click on the "StartRange" or "EndRange" column should display a yellow background selection.The selectionmode of the table is "singleselection".

so only one cell will be yellow coloured on selecting it.If there was any previous cell selection ,it goes away.

[2]Double click on the combo cells or single click on the drop down arrow icon should dropdown the combo drop down list.The background colour of the cell should remains yellow.

[3]The combo cells are not editable.That means the user cant type in anything into the cell.But must be able to change the value in the cell when the user selects something from the combobox or by calling the Table function "SetValueAt"


I have tried to achieve the above said things,but in vain...

Attaching what I have tried.This is the code which has generated the image.Please advice what must be changed in the code to achieve the above said behaviour and how?.The code will compile if any one wants to run it...





Code:
package set.test;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import java.awt.*;
import java.awt.event.*;

public class TableCellColour extends JPanel {

		private int tableHilightedRow, tableHilightedCol;
	    JTable table = null;
	
public TableCellColour(){
	
	super(new GridLayout(1,0));
	this.tableHilightedRow = -1;
	this.tableHilightedCol = -1;
	table = new JTable(new MyTableModel());
	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	 

	table.setPreferredScrollableViewportSize(new Dimension(500,70));	
   
	
	JScrollPane scrollpane = new JScrollPane(table);
	
	//Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);  
    
    table.addMouseListener(new MouseHandler());    
    setUpRowHeaderColumn(table, table.getColumnModel().getColumn(0));   
    setUpStartRangeColumn(table, table.getColumnModel().getColumn(1));
    setUpEndRangeColumn(table, table.getColumnModel().getColumn(2));
    
    //Set up column sizes.
    initColumnSizes(table);
    
    
    
  	add(scrollPane);
}

private void initColumnSizes(JTable table){
	
	MyTableModel model = (MyTableModel)table.getModel();
	int columnCount =3;
	TableColumn column = null;
	Component comp =null;
	int headerWidth =0;
	int cellWidth =0;
	Object [] longValues = model.longValues;
	TableCellRenderer headRenderer =table.getTableHeader().getDefaultRenderer();
	
	for(int i=0;i<columnCount;i++){
		
		column = table.getColumnModel().getColumn(i);
		comp = headRenderer.getTableCellRendererComponent(null,
				column.getHeaderValue()
				,false,false,0,0);
		
		headerWidth = comp.getPreferredSize().width;

		comp = table.getDefaultRenderer(model.getColumnClass(i)
				).getTableCellRendererComponent(table,longValues[i],false,false,0,i);
		
		
		cellWidth = comp.getPreferredSize().width; 
		 //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.		
		if(i==0)
			column.setPreferredWidth(2);
		else
			column.setPreferredWidth(Math.max(headerWidth, cellWidth));
	}	
}


public void setUpSheetRangeColumn(JTable table,TableColumn sheetColumn){
	
	// These are the combobox values
	String[] values = new String[]{"item1", "item2", "item3"};	
	JComboBox comboBox = new JComboBox(values);
	sheetColumn.setCellEditor(new DefaultCellEditor(comboBox));
	MyComboBoxRenderer  comboRenderer= new MyComboBoxRenderer();
	for(int i=0;i<=values.length;i++){
		comboRenderer.addItem(values[i]);
	}	
	sheetColumn.setCellRenderer(comboRenderer);        
	
}
public void setUpRowHeaderColumn(JTable table,TableColumn rowHeader){

	//rowHeader.setCellRenderer(new MyRowHeaderRenderer(table));         
	
}
public void setUpStartRangeColumn(JTable table,TableColumn startRange){
	
	// These are the combobox values
	String[] values1 = new String[]{"4567", "2345", "erw3"};	
	JComboBox comboBox = new JComboBox(values1);
	DefaultCellEditor cellEditor = new DefaultCellEditor(comboBox);	
	startRange.setCellEditor(cellEditor);
	MyComboBoxRenderer  comboRenderer= new MyComboBoxRenderer();
	for(int i=0;i<=(values1.length -1);i++){
		comboRenderer.addItem(values1[i]);
	}	
	startRange.setCellRenderer(comboRenderer);   
	
	
	String[] values2 = new String[]{"455", "5678", "6789"};
	//comboBox.removeAllItems();
	JComboBox comboBox2 = new JComboBox(values2);		
	comboRenderer.removeAllItems();
	for(int i=0;i<=(values2.length-1);i++){
		comboRenderer.addItem(values2[i]);
	}	
	TableColumn endRange = table.getColumnModel().getColumn(2);
	endRange.setCellEditor(new DefaultCellEditor(comboBox2));	
	endRange.setCellRenderer(comboRenderer);    
	
	
}

public void setUpEndRangeColumn(JTable table,TableColumn endRange){
	
	// These are the combobox values
	//String[] values = new String[]{"455", "5678", "6789"};
	//JComboBox comboBox = new JComboBox(values);		
	//endRange.setCellEditor(new DefaultCellEditor(comboBox));	
	//endRange.setCellRenderer(new MyComboBoxRenderer(values));        
	
}
public void setTableRowColSelection() {

	if (tableHilightedRow != -1)
		table.setRowSelectionInterval(0, tableHilightedRow);
	if (tableHilightedCol != -1)
		table.setColumnSelectionInterval(0, tableHilightedCol);
}

class MyTableModel extends AbstractTableModel{
	
	private String [] columnNames= {
			"SheetRange",
            "StartRange",
            "EndRange"            
	};
	private Object [][]data = {
				// {"","Mary", "Campione","Snowboarding"},
	             {"","Alison", "Huml","Rowing"},
	             {"","Kathy", "Walrath", "Knitting"},
	             {"","Sharon", "Zakhour","Speed reading"},
	             {"","Philip", "Milne","Pool"}
	};
	
	public final Object[] longValues = {
			"","Sharon", "Campione","None of the above"};
	
	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 columnIndex){
		
		return getValueAt(0,columnIndex).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 ||col==2)
			return true;
			else 
				return false;
	}
   
}
public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
	
	int highlightRow = -1;
	int highlightCol = -1;
	
    public MyComboBoxRenderer() {
        //super(items);
    }
    
    
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
     	if (row == highlightRow && column == highlightCol) {
			setBackground(Color.yellow);
		} else if (isSelected) {
						
			 setForeground(table.getSelectionForeground());
	         super.setBackground(table.getSelectionBackground());	        
			
		} else
		{
			 setForeground(table.getForeground());
			 setBackground(table.getBackground());
       
		}		
		return this;
    }
    
    public void setHighlightCell(int row, int col) {
		highlightRow = row;
		highlightCol = col;
		tableHilightedRow = highlightRow; 
		tableHilightedCol = highlightCol;			
		setTableRowColSelection();
	}
    
}

 class MouseHandler extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
        JTable table = (JTable) e.getSource();
        MyTableModel model =(MyTableModel)table.getModel();
        TableColumnModel columnModel = table.getColumnModel();
        int viewColumn = columnModel.getColumnIndexAtX(e.getX());      
        int column = columnModel.getColumn(viewColumn).getModelIndex();
        //MyRowHeaderRenderer renderer = null;
        int click = e.getClickCount();
        JComboBox comp = null;
        Point p = e.getPoint();
    	int row = table.rowAtPoint(p);
		int col = table.columnAtPoint(p);
		if(col==0)
			return;
		MyComboBoxRenderer render = (MyComboBoxRenderer) table.getCellRenderer(row, col);
		String eVal = (String)table.getValueAt(row,col);
		comp = (JComboBox) render.getTableCellRendererComponent(table,eVal,true,true,row,col);
        if(col !=0 &click==2)        
        {
        	render.setHighlightCell(row, col);			
        	//comp.setPopupVisible(true);
        }
        else if (col !=0 &&click==1)
		{
				render.setHighlightCell(row, col);
				//comp.setPopupVisible(false);
        }
        
        table.repaint();       	
      
        	
    }
}

private static void  createAndShowGUI(){
	
	JFrame frame = new JFrame("TableComBoBox");
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	TableCellColour newContentPane = new TableCellColour();	
	newContentPane.setOpaque(true);
	frame.setContentPane(newContentPane);
	
	frame.pack();
	frame.setVisible(true);
	
	
}
public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {            
           createAndShowGUI();
        }
    });
}
}








Thanks in advance
P
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top