MouseMotionListener inside JTable
- by Harish
I am trying to add MouseMotion event to the label and move it based on the dragging of the mouse and make it move along with my mouse.However the mousemotion is very difficult to control making this action not usable.
Here is the code
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class TableTest
{
public TableTest()
{
String[] columnNames =
{ "FileName", "Integer" };
Object[][] data =
{
{ new FileName("AAA.jpg", Color.YELLOW), new Integer(2) },
{ new FileName("BBB.png", Color.GREEN), new FileName("BBB.png", Color.GREEN) },
{ new FileName("CCC.jpg", Color.RED), new Integer(-1) }, };
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
public Class getColumnClass(int column)
{
System.out.println("column is" + column);
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model);
//JTable table = new JTable(data, columnNames);
table.setDefaultRenderer(FileName.class, new FileNameCellRenderer());
final JLabel label = new JLabel("TESTING", SwingConstants.CENTER);
label.setBackground(java.awt.Color.RED);
label.setBounds(450, 100, 90, 20);
label.setOpaque(true);
label.setVisible(true);
label.addMouseMotionListener(new MouseMotionListener()
{
public void mouseDragged(MouseEvent arg0)
{
label.setBounds(arg0.getX(), arg0.getY(), 90, 20);
}
public void mouseMoved(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
});
table.add(label);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(table);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static class FileNameCellRenderer extends DefaultTableCellRenderer
{
public Component getTableCellRendererComponent(JTable table, Object v,
boolean isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, v, isSelected, hasFocus,
row, column);
FileName fn = (FileName) v;
setBorder(BorderFactory.createMatteBorder(0, 60, 0, 0,
new java.awt.Color(143, 188, 143)));
return this;
}
}
static class FileName
{
public final Color color;
public final String label;
FileName(String l, Color c)
{
this.label = l;
this.color = c;
}
public String toString()
{
return label;
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TableTest();
}
});
}
}
I just want to make the label follow the label follow my mouse and the label should be attached to the table.Is there an easy way than this.