JTable selection listener - java

I have a code which displays Table in applets & consists of two columns:-
image icon
description
Here's my code:
import javax.swing.table.*;
public class TableIcon extends JFrame
{
public TableIcon()
{
ImageIcon aboutIcon = new ImageIcon("about16.gif");
ImageIcon addIcon = new ImageIcon("add16.gif");
ImageIcon copyIcon = new ImageIcon("copy16.gif");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "About"},
{addIcon, "Add"},
{copyIcon, "Copy"},
};
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();
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
Now what i want to know is how can I implement selection listener or mouse listener event on my table , such that it should select a particular image from my table and display on text area or text field(my table contains path of image file)?
Can I add text field on table & table on frame? Please feel free to ask queries if required.

In my code I have a table where I set single selection mode; in my case, listener described in How to Write a List Selection Listener (with a for loop from getMinSelectionIndex to getMaxSelectionIndex) is not useful because releasing mouse button I'm sure I have just one row selected.
So I've solved as follows:
....
int iSelectedIndex =-1;
....
JTable jtable = new JTable(tableModel); // tableModel defined elsewhere
jtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel selectionModel = jtable.getSelectionModel();
selectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
handleSelectionEvent(e);
}
});
....
protected void handleSelectionEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
// e.getSource() returns an object like this
// javax.swing.DefaultListSelectionModel 1052752867 ={11}
// where 11 is the index of selected element when mouse button is released
String strSource= e.getSource().toString();
int start = strSource.indexOf("{")+1,
stop = strSource.length()-1;
iSelectedIndex = Integer.parseInt(strSource.substring(start, stop));
}
I think this solution, that does not require a for loop between start and stop to check which element is selectes, is more suitable when table is in single selection mode

How about this?
protected void handleSelectionEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
final DefaultListSelectionModel target = (DefaultListSelectionModel)e.getSource();
iSelectedIndex = target.getAnchorSelectionIndex();
}

Read the section from the Swing tutorial on How to Write a List Selection Listener.
You can't add a text field to the table, but you can add a textfield and a table to the same frame.

Related

Adding JComboBox to JTable

I'm creating a JTable in Java & I'm asked to add to the table a JCheckBox, JButton and a JComboBox. The table that I created is displaying all the information, the button is working fine and the JCheckBox is also working, the problem I'm facing is that the JComboBox is not working. I really can't figure out why. I've tried to look the problem up but I can't figure it out. Can someone help me please?
The code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class sinX extends JFrame {
private JTable table;
private DefaultTableModel model;
private Object[][] data;
private String[] columnNames;
private JButton button;
JComboBox comboBox;
public sinX() {
comboBox = new JComboBox();
setTitle("Programming Languages");
data = new Object[][]{{"C","Dennis Ritchie",1972,false},{"C++","Bjarne Stroustrup",1983,true},
{"Python","Guido van Rossum",1991,false},{"Java","James Gosling",1995,true},{
"JavaScript","Brendan Eich",1995,true},{"C#","Anders Hejlsberg",2001,false},
{"Scala","Martin Odersky",2003,true}};
columnNames = new String[] {"Language","Author","Year","Check Box"};
//model = new DefaultTableModel(data, columnNames);
//table = new JTable(model);
//table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
final Class[] columnClass = new Class[] {
String.class, String.class, Integer.class, Boolean.class
};
//create table model with data
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column)
{
return false;
}
#Override
public Class<?> getColumnClass(int columnIndex)
{
return columnClass[columnIndex];
}
};
table = new JTable(model);
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
button = new JButton("Remove");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
// check for selected row first
if(table.getSelectedRow() != -1) {
// remove selected row from the model
model.removeRow(table.getSelectedRow());
JOptionPane.showMessageDialog(null, "Selected row deleted successfully");
}
}
});
TableColumn year = table.getColumnModel().getColumn(2);
comboBox.addItem("A");
comboBox.addItem("B");
comboBox.addItem("C");
comboBox.addItem("D");
year.setCellEditor(new DefaultCellEditor(comboBox));
add(new JScrollPane(table), BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 500);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new sinX();
}
}
the problem I'm facing is that the JComboBox is not working.
year.setCellEditor(new DefaultCellEditor(comboBox));
The above code indicates you are trying to use a combo box as an editor for the given column.
public boolean isCellEditable(int row, int column)
{
return false;
}
However, you have stated in your model that none of columns are editable.
You need to return true for any column where you want to edit the data.
the JCheckBox is also working
Not really. Yes you see the boolean value is rendered as a check box. However, you can't change its value by clicking on it, unless of course you return true for that column as well.

how to make JTable cell non editable but should be able to select and copy the value in current cell

I am trying to make JTable cells non-editable but if i do so Iam unable to select a single cell value instead when i try to copy the entire row is getting selected
I want to copy only the selected cell value instead of entire row.Is there a way to do it?
public class EmployeeWin extends JFrame {
DefaultTableModel model = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column){
return false;
}
};
Container cont = this.getContentPane();
JTable tab = new JTable(model);
private TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(model);
private final JTextField searchFilter = new JTextField();
public EmpDataWin(List<EmployeeDTO> pEmployeeDTO) {
initialize(pEmployeeDTO);
}
public void initialize(List<EmployeeDTO> pEmployeeDTOList) {
JPanel panelParent = new JPanel(new BorderLayout());
// Add Header
model.addColumn("Employee Name");
model.addColumn("Department");
model.addColumn("Details");
// Add data row to table
for (EmployeeDTO aEmployeeDTO : pEmployeeDTOList) {
model.addRow(new Object[] { aEmployeeDTO.getEmployee_Name(), aEmployeeDTO.getDepartment(),
aEmployeeDTO.getDetails()});
}
tab.setRowSorter(rowSorter);
tab.setAutoCreateRowSorter(true);
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel(UIConstants.SEARCH), BorderLayout.WEST);
JTextField searchFilter = SearchFilter.createRowFilter(tab);
panel.add(searchFilter, BorderLayout.CENTER);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
tab.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane sp = new JScrollPane(tab,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
panelParent.add(panel,BorderLayout.NORTH);
panelParent.add(sp,BorderLayout.CENTER);
panelParent.setBorder(BorderFactory.createEmptyBorder(10 , 10, 10, 10));
cont.add(panelParent);
this.pack();
}
public static void main(String[] args) {
EmployeeDAO dao = new EmployeeDAO();
List<EmployeeDTO> dto = dao.getemployeeData();
JFrame frame = new EmployeeDataWin(dto);
}
}
when i try to copy the entire row is getting selected I want to copy only the selected cell value instead of entire row
The default Action for the Ctrl+C key is to copy the entire row. If you only want the data of the currently selected cell then you need to replace the default Action with a custom Action.
The logic would be something like:
Action copyCell = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
JTable table = (JTable)e.getSource();
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
Object value = table.getValueAt(row, column);
// copy the data to the clipboard
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection testData = new StringSelection( value.toString() );
c.setContents(testData, testData);
}
};
table.getActionMap().put("copy", copyCell);
The above code will create the custom Action and replace it in the ActionMap of the JTable. See Key Bindings. The program provided in the link shows all the default Actions and the keyword for each Action.

JList with tooltip text in DafaultListModel

I have a JList and each item of the JList has a distinct display text and tooltip text. I would like to use 'DefaultListModel' for the JList. My question is that is it possible to somehow save the tooltip text when added an item to the DefaultListModel.
Thanks.
You can override the getToolTipText(...) method to provide your custom tool tip.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListToolTip extends JFrame
{
public ListToolTip()
{
DefaultListModel model = new DefaultListModel();
model.addElement("one");
model.addElement("two");
model.addElement("three");
model.addElement("four");
model.addElement("five");
model.addElement("six");
model.addElement("seven");
model.addElement("eight");
model.addElement("nine");
model.addElement("ten");
JList list = new JList( model )
{
public String getToolTipText( MouseEvent e )
{
int row = locationToIndex( e.getPoint() );
Object o = getModel().getElementAt(row);
return o.toString();
}
public Point getToolTipLocation(MouseEvent e)
{
int row = locationToIndex( e.getPoint() );
Rectangle r = getCellBounds(row, row);
return new Point(r.width, r.y);
}
};
JScrollPane scrollPane = new JScrollPane( list );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
ListToolTip frame = new ListToolTip();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(400, 100);
frame.setVisible( true );
}
}
Overriding getToolTipLocation(...) is not necessary.
Edit:
I want to save the custom text in the model
Then you would need to save a custom object in the model that contains the value displayed in the list and the text for the tooltip.
Check out ComboBox With Hidden Data for an example of creating an object using this approach.

Refresh table's row (Not row's value) on frame?

Sorry for being so amateur, I created a 'button' on a frame so that when we click the button for the first time, A ROW will be inserted on the frame. But ALL I WANT is that when I click the button THE SECOND TIME, the ROW IS REFRESHED (Not creating a new row!), I know that '.addRow(new Object[] { "", "", ""});' is the cause , because the object is created every time I click the button, so how could I possibly modify the code? Thanks for your attention.
*My weak brain said that if only I can empty 'model' object (or destroying the object, something like that), then I would find the solution, but how I could possibly empty/destroy that 'model' object?
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.DefaultTableModel;
public class MyTable extends JFrame {
private JTable table;
private DefaultTableModel model;
private JScrollPane scroll;
private JButton createRow;
private String headers[] = {"a", "b", "c"};
public MyTable() {
createRow = new JButton("Create Row");
model = new DefaultTableModel();
model.setColumnIdentifiers(headers);
table = new JTable();
table.setModel(model);
scroll = new JScrollPane(table);
add(createRow, java.awt.BorderLayout.NORTH);
add(scroll, java.awt.BorderLayout.CENTER);
createRowOn();
}
// while button is pressed then create A ROW
public void createRowOn() {
createRow.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == createRow) {
model.addRow(new Object[]{"", "", ""});
}
}
});
}
public static void main(String args[]) {
MyTable t = new MyTable();
t.setVisible(true);
t.setSize(300, 300);
}
}
Sorry for being so amateur
please read Oracle tutorial How to use Tables, especially part Creating Table Model
I created a 'button' on frame so that when we click the button for the
first time, A ROW will be inserted on frame. But all i want that when
i click the button on THE SECOND TIME , the ROW IS REFRESHED (Not
creating a new row !) , i suspect 'new Object[] { "", "", ""}' is the
cause , because the object is created everytime i click the button, so
how could i possibly modify the code ?
not clear from question (nothing is added to JTable) if you want to:
add a new row (model.addRow)
remove all rows (setDataVector/setRowCount)
reset value in JTables view (setValueAt)
but everything is described in Oracle tutorial, rest in the DefaultTableModel

JTable update columns header height after multiple header insertion

What should be invoked /fired when I added new column to the table but its header label has more lines (using html and br element) than in the already presents headers so the headers will resize accordingly?
Before adding
After adding
This does not happen if when first painting the table a column already has that number of rows (when the label is <html>Card<br>name</html>).
I fire fireTableStructureChanged() in TableModel when new record is added (so new columns are added).
Starting from #mKorbel's example, the following button alters the appearance as shown. The method setColumnIdentifiers() of DefaultTableModel invokes fireTableStructureChanged() on your behalf. If you extend AbstractTableModel, you should do this from within your TableModel.
Code:
private DefaultTableModel model = new DefaultTableModel(data, columnNames) {…}
…
frame.add(new JToggleButton(new AbstractAction("Toggle") {
#Override
public void actionPerformed(ActionEvent e) {
JToggleButton b = (JToggleButton) e.getSource();
if (b.isSelected()) {
columnNames[0] = "<html>String<br>of pearls</html>";
} else {
columnNames[0] = "String";
}
model.setColumnIdentifiers(columnNames);
}
}), BorderLayout.SOUTH);

Categories

Resources