How to clear contents of selected cells in JTable? - java

I use mouse to drag a selection area in some JTable cells, the selection area is the yellow, so can anyone told me exactly how to clear the contents of selected cells by pressing "Delete" key in keyboard or a JButton?
The captured pic of selected cells:

Create an Acton to find the selected cells and clear the text. The easiest way is to loop through each cell in the table.
The basics of the Action would be something like:
Action clearAction = new Action()
{
#Override
public void actionPerformed(ActionEvent e)
{
for (each row in the table)
for (each column in the row)
if (table.isCellSelected(...))
table.setValueAt("", ...);
}
}
Then you create a button to invoke the Action:
JButton clearButton = new JButton( "Clear" );
clearButton.addActionListener( clearAction );
If you also want to use the Delete key then you can use Key Bindings to share the same Action.
The basic logic to add a new Key Binding to the JTable would be:
String keyStrokeAndKey = "DELETE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, keyStrokeAndKey);
table.getActionMap().put(keyStrokeAndKey, action);
Check out Key Bindings for more information.

Related

MouseEvents inside JList objects

I am a bit confused regarding a situation I have. I created a ListModel extending DefaultListModel and ListRenderer implementing ListCellRenderer for displaying a custom cell in a JList. The cells are some objects created from a class extending JPanel, that contain a JLabel and a JButton.
My issue is related to the mouse events: I want to trigger a certain event when clicking on the JButton inside a cell of the JList, yet I can not figure out how to match the mouse source point to that of the JButton from the respective index. More exactly, I added a mouse listener to the list, but I want it to trigger something if the mouse point is located inside the bounds of the JButton, and another action if it's on the data item. I added some prints to find out the cause of this, but before that some code to highlight the structure:
public WifiGuiHandler(JButton reference) {
btnReference = reference;
wifiListener = new WifiListener();
wifiPopupContainer = new JScrollPopupMenu("Connections.");
wifiPopupContainer.setMaximumVisibleRows(7);
connectionsHolder = new ArrayList<>();
listOfConnections = new JList();
listOfConnectionsModel = new ListModel(connectionsHolder);
listOfConnectionsRenderer = new ListRenderer();
listOfConnections.setModel(listOfConnectionsModel);
listOfConnections.setCellRenderer(listOfConnectionsRenderer);
wifiPopupContainer.add(listOfConnections);
wifiPopupContainer.pack();
initializeTestVariables();
initializeListeners();
}
Here, the constructor for the class that takes a JButton and adds a mouse listener to it, that triggers the appearance of a JPopupMenu, which has only one component, the JList that hold the entire data. Also, links the ArrayList with the data items to the ListModel.
public void initializeTestVariables() {
for (int i = 0; i <= 10; i++) {
WifiItem item = new WifiItem("Connection number " + i + ".", i);
connectionsHolder.add(item);
}
}
Setting up the data items.
public void initializeListeners() {
listOfConnections.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int index = listOfConnections.locationToIndex(e.getPoint());
if (index >= 0) {
WifiItem item = (WifiItem) ((ListModel) listOfConnections.getModel()).getElementAt(index);
System.out.println("Button of " + item.getConnectionName() + " is at location :" + item.getButton().getLocation());
System.out.println("Button has the bounds : " + item.getButton().getBounds());
System.out.println("MouseEvent detected on : " + e.getPoint().getLocation());
if (item.getButton().getBounds().contains(e.getPoint())) {
item.connectHere();
}
if (item.getButton().isVisible()) {
System.out.println("Set expanded on : " + item.getConnectionName());
item.setExpandedState(false);
listOfConnectionsModel.fireContentsChanged(item, index, index);
updateGui(false);
} else {
System.out.println("Set expanded on : " + item.getConnectionName());
listOfConnectionsModel.fireContentsChanged(item, index, index);
item.setExpandedState(true);
updateGui(false);
}
}
}
});
btnReference.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
updateGui(true);
}
});
}
And this is where the confusion arises. I correctly get the data item( WifiItem) from the mouse event location/point, but when I click on the JButton of the WifiItem, it doesn't trigger that method, like it doesn't seem to detect that the JButton actually is there. I also set up the prints, and what is strange, the Point for the JButton is always the same, even though it actually is different, and this seems to be the problem. More exactly, from the output of the program:
Button of Connection number 2. is at location :java.awt.Point[x=137,y=33]
Button has the bounds : java.awt.Rectangle[x=137,y=33,width=90,height=26]
MouseEvent detected on : java.awt.Point[x=172,y=125]
Button of Connection number 3. is at location :java.awt.Point[x=137,y=33]
Button has the bounds : java.awt.Rectangle[x=137,y=33,width=90,height=26]
MouseEvent detected on : java.awt.Point[x=172,y=125]
The above mouse events points were actually located on the JButton itself, only it didn't get that. As another strange fact, only if I click the JButton of the FIRST element of the list does it trigger the required mouse action.
Another print revealed that all the JButtons have the same Point and Rectangle, and I don't get it. There are 10 items in the JList, each displayed properly, how can all their JButtons have the same location? I must be missing some key element here. I looked at other posts and tried other recommendations: converting the point with SwingUtilities, removing all the mouse listeners from the JList and adding them to the data items.
To sum it up,the issue is that the list triggers the events for the correct data item in it(meaning, I do get the correct index for the item located there), but if the mouse event happens on the JButton of any data item inside the list, it doesn't trigger the required effect (the point is not withing the bounds of the button, even though it should be).
More exactly, I added a mouse listener for the list, but I want it to trigger something if the mouse point is located inside the bounds of the JButton, and another action if it's on the data item.
An easier solution would be to use a JTable. The data is separated into columns and the JTable has an API to let you know which row/column was selected.
You can use the Table Button Column as your renderer/editor for the button.
Edit:
only if I click the JButton of the FIRST element of the list does it trigger the required mouse action
Sounds like your conversion of the mouse point is off.
, how can all their JButtons have the same location?
Again, the button location is releative to the renderer panel. The panel itself is relative to the row in the JList. So I would guess you need to need the row index and add the height of each of the previous rows to your calculation.

How to add right-click popup menu in jTable row?

I have a simple code for Add button like this :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel dtm = (DefaultTableModel)table.getModel();
dtm.addRow (new Object[] {name.getText(),mobile.getText()});
}
This code will get text from JTextField and insert into JTable row
I want to add function right-click popup menu when i right-click on table row, and add some like add delete rename.
How can I do that ?
Start by reading the section from the Swing tutorial on How to Bring up a Popup Menu for the basics of displaying a menu and a working demo.
In the case of a JTable, you will probably want to highlight the row that was clicked on so your Actions can act on the selected row.
So you would need to add code like the following to the maybeShowPopup(...) method from the demo example in the tutorial:
if (e.isPopupTrigger())
{
JTable source = (JTable)e.getSource();
int row = source.rowAtPoint( e.getPoint() );
int column = source.columnAtPoint( e.getPoint() );
if (! source.isRowSelected(row))
source.changeSelection(row, column, false, false);
popup.show(e.getComponent(), e.getX(), e.getY());
}

Add popup JTextarea to each column title in JTable

I am trying to make a JTable with popup help menus for each column section. For instance, you right click on the first column title and a JTextArea pops up that explains what the column is for and what type of data should be put into it. I have the following code establishing the JTable and the mouselistener event. Is there a way I can write an If statement using ColumnAtPoint() so that if the right click happens at Column 1, then it opens up my JTextArea? Then I can create a second and third separate JTextAreas for my other columns.
final DefaultTableModel tblModel = new DefaultTableModel(null, colHdrs);
final JTable table = new JTable(tblModel);
table.getTableHeader().addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e))
{
JOptionPane.showMessageDialog(null, textArea1, "Type", JOptionPane.PLAIN_MESSAGE);
}
}
});
Try to use JToolTip I think it might be much more suited for your use ;) :)!
You can also add e.g. to a
JLabel label = new JLabel("My Number Label");
a tooltip text like :
label.setToolTipText("Only Numbers From 1-10 are allowed!");
This is also possible for other swing stuff, you can try it :).
The text will appear as soon as you hover over the label .

Setting caret position in editable JComboBox

When an item is selected from a combobox that is longer than the combobox is wide, the end of the string is truncated to show only the beginning portion of the string that will fit.
When the combobox is set to editable, it is the end of the string which is shown, with the begining truncated (which makes sense, as it is as if the user had typed it)
Is there a way to set the caret position to the start of the entry to display the beginning of the value, whilst still allowing the combobox to be editable? Is this something to be achieved by writing a custom editor for the combobox?
This is one way:
JComboBox comboBox = new JComboBox( ... )
{
#Override
public void setSelectedItem(Object item)
{
super.setSelectedItem( item );
ComboBoxEditor editor = getEditor();
JTextField textField = (JTextField)editor.getEditorComponent();
textField.setCaretPosition(0);
}
};

JTable: change traversal order

I want to traverse horizontally through a JTable, when pressing enter. I've tried with JTable.changeSelection but it doesnt seem to work. Any ideas how to change the traversal behavior?
Read up on Key Bindings. You would want to "share an Action with a different KeyStroke"
Enter is vertical traverse , TAB is horisontal, just hold Enter event and generate Tab event or call function for Tab Event. But you should set up next properties:
table.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
JTable.getInputMap(JInternalFrame.WHEN_ANCESTOR_OF _FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "SOME_ACTION");
JTable.getInputMap(JInternalFrame.WHEN_FOCUSED)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "SOME_ACTION");
JTable.getActionMap().put("SOME_ACTION", actions);
actions = new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
//This action will get fired on Enter Key
}
};

Categories