Jay Kandy
Posts: 77
Nickname: jay
Registered: Mar, 2002
|
|
Re: JTable mouse selection "Drawing the rectangle"
|
Posted: Apr 23, 2002 4:28 PM
|
|
Smith, if you already found what you were looking for, please ignore this. But heres a JTable you wanted.
import javax.swing.JTable;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.Point;
public class AnotherTableEx extends JFrame
{
public AnotherTableEx()
{
final TransparentJTable table = new TransparentJTable(new MyTableModel());
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(true);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
setSize(200, 200);
show();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new AnotherTableEx();
}
class MyTableModel extends AbstractTableModel
{
Object[][] data = {
{"Calories", "130", "calories"},
{"Total Fat", "0", "%"},
{"Sodium", "1", "%"},
{"Total Carbs", "12", "%"},
};
String[] columns = {"Item", "Amount", "Units"};
public int getColumnCount()
{ return 3; }
public int getRowCount()
{ return 4; }
public String getColumnName(int c)
{ return columns[c]; }
public Object getValueAt(int rowIndex, int colIndex)
{ return data[rowIndex][colIndex]; }
public boolean isCellEditable(int rowIndex, int colIndex)
{ return false; }
}
}
class TransparentJTable extends JTable implements MouseMotionListener, MouseListener
{
protected Point begin = new Point();
protected Point end = new Point();
public TransparentJTable(TableModel tm)
{
super(tm);
setOpaque(false);
addMouseListener( this );
addMouseMotionListener( this );
}
public void mouseClicked(MouseEvent me)
{ }
public void mousePressed(MouseEvent me)
{
begin = me.getPoint();
}
public void mouseReleased(MouseEvent me)
{ }
public void mouseEntered(MouseEvent me)
{ }
public void mouseExited(MouseEvent me)
{ }
public void mouseDragged(MouseEvent me)
{
end = me.getPoint();
update(getGraphics());
getGraphics().drawRect(begin.x, begin.y, end.x - begin.x, end.y - begin.y);
addRowSelectionInterval(rowAtPoint(begin), rowAtPoint(end));
addColumnSelectionInterval(columnAtPoint(begin), columnAtPoint(end));
}
public void mouseMoved(MouseEvent me)
{ }
}
|
|