JBTable ColumnInfo with button - java

I have a JBtable and in one of the columns I would like to insert a button.
My attempt was as follows:
private class DeleteColumn extends ColumnInfo<Field, JButton> {
public DeleteColumn() {
super("Delete");
}
#Nullable
#Override
public JButton valueOf(final Field field) {
final JButton removalButton = new JButton();
removalButton.setText("-");
removalButton.addActionListener((e) -> {
// do something
});
return removalButton;
}
#Override
public Class<?> getColumnClass() {
return JButton.class;
}
}
However when this is rendered, it still only displays the .toString() of the JButton. How can I display a button in the table?

You should write a custom renderer. Please look at:
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender
There are also examples you could look at:
http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableRenderDemoProject/src/components/TableRenderDemo.java

I would like to insert a button
You should NOT be adding a JButton to the table. The data of the JTable should not be a Swing component. You should just be storing text in the column and then use a JButton to render the text.
For example check out Table Button Column for a class that allow you to use a button as the renderer/editor.

Related

2D JTextField array setText using MouseClicked/MousePressed

So I have a JTextField array called fields and I have a string called value (the value of value is replaced when I click on a button). What I want is when I click on one of the JTextFields, I want to put the value in it (using setText, maybe).
private JTextField[][] fields;
fields = new JTextField[totalX][totalY];
Is there a way to do this with a MouseClicked/MousePressed event. Any help is appreciated. Thank you.
Use FocusListener instead of mouse listener. Example:
JTextField field = new JTextField();
field.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
field.setText(value);
}
});
Tutorial - https://docs.oracle.com/javase/tutorial/uiswing/events/focuslistener.html

Setting Actor To Listen For Button Click In LibGDX

Background Information: I am currently working in a Dialog class I have extended for my game. Inside of this dialog's content table I have both an Image and a Table (lets call it ioTable). Inside of ioTable I have a combination of both Labels and TextFields. The idea is that the dialog becomes a sort of form for the use to fill out.
Next, inside of the Dialog's button table, I want to include a "Clear" TextButton (clearButton). The idea that clearButton will clear any values written to the TextFields of ioTable.
My Question: Is is possible to add a listener to each of the TextFields of ioTable that will trigger when clearButton is pressed. As always, any other creative solution is more than welcome.
You could just give the EventListener a reference to the table you want to clear:
// Assuming getSkin() and ioTable are defined elsewhere and ioTable is final
TextButton clearButton = new TextButton("Clear", getSkin());
clearButton.addListener(new EventListener() {
#Override
public boolean handle(Event event) {
for(Actor potentialField : table.getChildren()) {
if(potentialField instanceof TextField) {
((TextField)potentialField).setText("");
}
}
return true;
}
});
// Add clearButton to your dialog
If you see yourself creating multiple clearButtons, you could easily wrap this in a helper method or extend TextButton.

How to add listener to table?

I am trying to add a listener to JTable that delete a selected rows.
I have a class ToolBar in which contains all the buttons,
but all my JTable setting is on another class: TablePanel.
I want to be able to delete row(s) when the user click a buttons in ToolBar Class.
ToolBar.java
public class ToolBar extends JPanel
{
TablePanel tablePane;
JButton openButton, saveButton, addButton, delButton;
ImageIcon openIcon, saveIcon, addIcon, delIcon;
Image openImage, saveImage, addImage, delImage;
Image openImage2, saveImage2, addImage2, delImage2;
ButtonListener listener;
public ToolBar(TablePanel tablePane)
{
this.tablePane = tablePane;
//Bunch of codes here to initialize all the buttons and icons
}
//Button Listener
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == openButton)
JOptionPane.showMessageDialog(null, "hello");
if (event.getSource() == saveButton)
tablePane.saveData();
if (event.getSource() == addButton)
tablePane.addRow();
if (event.getSource() == delButton)
tablePane.delRow();
}
}
}
TablePanel
public class TablePanel extends JPanel
{
//Table's column name
private ArrayList<String> columnNames = new ArrayList<String>();
//List of data, later needs to be change
//so that it will be editable on the go
//It starts with 5 columns
//User can add more columns
private ArrayList<Object[]> data = new ArrayList<Object[]>();
//DefaultTableModel is needed for adding new rows
private JTable table;
private TModel tModel;
private JScrollPane scrollPane;
//For importing & exporting data
JFileChooser fileChooser;
public TablePanel()
{
//Column Names:
columnNames.add("Date");
columnNames.add("Category");
columnNames.add("Details");
columnNames.add("Add/Subtract");
columnNames.add("Total");
//Example data:
data.add(new Object[]{20140925, "Grocery", "Supermarket", -5.23,600.00});
data.add(new Object[]{20141013,"Car Maintenance", "Changing Tires", -200.00, 400.00});
//Some codes here
}
private class TModel extends AbstractTableModel implements TableModelListener
{
//Bunch of codes(methods) in here such as:
//public voide setValueAt, public Boolean isCellEditable, getColumnCount etc.
//Method for deleting row
public void delRow()
{
public void tableChanged(TableModelEvent event)
{
int row = event.getFirstRow();
fireTableRowsDeleted(row, row);
}
}
} //End of TModel class
} //End of TablePanel Class
How should I implement listener and fireTableDeleted(int row)?
What should I add in the public void delRow()?
Someone is going to need a reference to someone else, but you also want to maintain a level of separation so you don't end up tightly coupling your components together
You could use a controller of some kind, which has a reference to the table and is either listening directly to the buttons on the toolbar or which the tool bar can call and instruct it on what it wants to do.
For example, when clicked, the delete button would simply instruct the controller to "delete the selected rows". The controller would ask the TablePane to "Delete the selected rows" and the TablePane would comply.
This could be achieved through the Actions API where the Action would act as the controller.
Basically you would create a new DeleteRowAction (this is class you'd have to create), which had a reference to the TablePane and which you would pass to the ToolBar pane. You would then apply the Action to the delete button (JButton#setAction) and let it take care of everything else for you

How to fix this ActionListener to pass back the String to the widget

I am really new in Java, and just practising ActionListeners. As the part of the application I work on, I will have a JTextField that lets the user to search a name, and then a JTextArea to show the result of the search. I have a api for searching and fining the the names, only problem is to connect the widgets to the methods and action listener file.
Here is some parts of the code:
Widget File:
//Text Field
JTextField searchbox = new JTextField();
leftSide.add(searchbox, cnt);
String userText = searchbox.getText();
ActionListener sendsText = new SearchListener(search box);
searchbox.addActionListener(sendsText);
//TextArea
JTextArea stationList = new JTextArea(12, 0);
leftSide.add(stationList, cnt);
String entered = userText;
stationList.append(entered);
SearchListener:
public class SearchListener implements ActionListener {
private JTextField searchbox;
private JTextArea stationList;
public SearchListener(JTextField search box) {
this.searchbox = searchbox;
}
public void ListF(JTextArea stationList){
this.stationList = stationList;
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchbox.getText());
for (NAMES station : stations) {
//System.out.println(station);
*Problem*> String result = (searchbox.getText());
*Problem*> stationList.append(result);
}
So in this program, the TextFiels is connected and the ActionListener working, but it prints out the list on Similar names in the CMD, (I commented it here). But I want it to send the list back to the Text Area in the API.(Widget File). So I am not sure my ActionListener method at the top of the SearchListener is right. Also the Problem> in the code is where I tired to pass the search result to the text field, which doesnt work.
So anyone know how to fix it?
Thank is advance.
I think you may be twisting a few things around, but perhaps this is what you're trying to accomplish:
A search field who's value determines what the text area is populated with.
If this is the case, then a few things have to change. First, only code within the ActionListener will be axecuted upon UI events, so there is no reason to call getText() on any of the UI elements during initialization.
Second, adding a button to this UI greatly simplifies the logic here. If attaching the listener to the search box, issues begin to arise such as "when do I know the user is done entering text?" and "How do I handle partial text?", however using a "Search" button puts this logic in the hands of a user.
Once the "Search" button is clicked, the action event from the listener that is attached to the button will trigger, and the stationListArea will be populated with the results of similarNames(<text from search box>).
Note that though what is shown below is not the cleanest way to perform this task (which would involve fields and anonymous inner classes), it is straightforward and easy to understand.
Widget (not sure what cnt was, so I omitted in in sample code below)
//Create the search text box
JTextField searchBox = new JTextField();
leftSide.add(searchBox);
// Create a button that will serve as the "Action" for the search box
JButton searchButton = new JButton("Search");
lefSide.add(searchButton);
// Create the station-list text area that will display text
// based on results from the search box
JTextArea stationListArea = new JTextArea(12, 0);
leftSide.add(stationListArea);
// Create a listener that listens to the Button, then performs an
// action from the search box to the text area
ActionListener searchButtonListener = new SearchListener(searchBox, stationListArea);
searchButton.addActionListener(searchButtonListener);
SearchListener
NOTE: Logic here will continue adding text into your stationListArea every time the button is clicked and HHHH.SimilarNames() returns a value. To have the stationListArea just update with the new text every time, replacing the old, add a stationListArea.setText("") at the beginning of actionPerformed().
public class SearchListener implements ActionListener {
private JTextField searchBox;
private JTextArea stationListArea;
public SearchListener(JTextField searchBox, JTextArea stationListArea) {
this.searchBox = searchBox;
this.stationListArea = stationListArea;
}
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchBox.getText());
for (NAMES station : stations) {
stationListArea.append(station);
}
}
}
Updated based on feedback in main comments
Your NAMES object needs some way to provide a String representation of itself. This way, you can then append that value to your text area..
public class SearchListener implements ActionListener {
private JTextField searchbox;
private JTextArea stationList;
public SearchListener(JTextField search box) {
this.searchbox = searchbox;
}
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchbox.getText());
for (NAMES station : stations) {
stationList.append(station.getLocationName()());
}
}

Listeners to dynamically created Swing Components

I am dynamically creating jTABLES. The number of jTABLES depends on the database.
while(rset.next())
{
//Create Scroll Pane
JScrollPane newScrollPane = new JScrollPane();
//Create Table
JTable newTable = new JTable();
//Add Table to Scroll Pane
newScrollPane.setViewportView(newTable);
//Add Scroll Pane to a Tabbed Pane
jTabbedPane1.addTab(rset.getString(1),newTable);
}
I need to add MouseListener to each jTABLE, it is basically the same Listener, same actions.
while(rset.next())
{
//Table Created.....
newTable.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
String data = newTable.getValueAt(0,0).toString();
}
//More Abstract Methods...
});
}
Netbeans, forces me to make new Table final, and as far as I know, that final variables cannot be changed later, is there something wrong here? Am I doing this the right way?
When you are using a variable(outside variable) inside annonymous inner classes, it is necessary that it is declared final. That's why netbeans is forcing you to do it.
Final variables can't be changed later but do you need to change the final local variables out of the while loop?
If yes carete an array or list and store the references there.
final is required to use the reference in anonimous inner class (your listener).
What you can do to avoid the final problem:
Create another class that implements MouseListener.
class MyMouseListener extends MouseListener {
JTable table;
public MyMouseListener(JTable table) {
this.table = table;
}
Then use that table in any of the methods.
public void mouseClicked(MouseEvent e) {
String data = table.getValueAt(0,0).toString();
}
then add that mouse listener to the table.
myTable.addMouseListener(new MyMouseListener(myTable));

Categories