Sort a Java JTable by one column [duplicate] - java

How do i sort jtable column using radio button?
my jtable is defaultTableModel not vectors.
I have already achieve when user press on column header, it will sort, now i have to implement using radio button..
What would be the best way to achieve this?

To do a sort programmatically you add code like the following to your listener:
DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter());
ArrayList list = new ArrayList();
list.add( new RowSorter.SortKey(2, SortOrder.ASCENDING) );
sorter.setSortKeys(list);
sorter.sort();

Add an actionlistener to the radiobutton, sort and set the tableModel.
The Vector argument is an input to defaultTableModel.
final JTable table = new JTable();
JRadioButton button = new JRadioButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//sort your data here
table.setModel(new DefaultTableModel(sortedDate));
table.repaint();// maybe revalidate too
}
});

Related

multiple JComboBox listeners

I am new to JComboBox
I have 4 JComboBoxes: specialite, etudiant, annee, and semestre.
I need to get the selected item from the 4 of them each time I change the selected item and add the result to the ScrollPane (groupe des matieres ouvertes)
Please look into the below JComboBox basic example given by Java. Use getSelectedItem() of JComboBox in actionPerformed() method of each combo box whenever an item got selected in it.
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
updateScrollpane(petName); // Update your scrollpane
}
Do the same thing for all of your 4 dropdowns and update the scrollpane

How to Sort a JTable's column when I'm entering in a JFrame?

I have a problem when I try to sort a JTable. If I press a column's header, I can sort the column easily. However, I want to automatically sort the first column of my JTable when the JFrame which contains the JTable is entered. I would appreciate any help. Thanks
You can do this using SortKeys. For example
TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel());
table.setRowSorter(sorter);
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
int columnIndexToSort = 0; //This is the first column
sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
Have a look at this website and the java documentation for more information.

Display Data in a Jtable upon Row Selection from Another JTable

I have read one of the question in this website. and since I had the same problem with the one who asked the same question as mine, I want to do a follow up question. HOW DO YOU PUT THIS INTO CODE:
Ask the master table what its selected row is (getSelectedRow()).
Convert this view row index to a model row index (convertRowIndexToModel()).
Ask the model for the data at this index, ands extract the ID of the data. The model should be a class that you wrote, extending AbstractTableModel.
Then get the data to display in the three sub-tables from this ID, and change the model (or the data contained in the model) of these three tables.
Thanks in advance. i am quite having a hard time in this part of my program. since i only know about
tablePersonalProperty.setModel(DbUtils.resultSetToTableModel(rs));
when displaying all the items from the table. what i need is to DISPLAY the items with the same id from what i have chosen from the main table...
Before we can help you write code, we need more information.
Do your tables both have exactly the same columns?
Are you using your own custom data model already? If not, then you probably need to try that on your own. I can't write this for you since I don't know what you need to include in your model. If you are using netbeans, then you can use the form designer to help you write the table model. Just look at the properties of the JTable after you add it to the JFrame of JPanel. I ended up creating my own anyway, but the code that Netbeans generated helped get me started.
This sample code will help you to do what you are looking for, it show how to move table row from one table to another in a click event in rows,
public class InsertRows{
public static void main(String[] args) {
new InsertRows();
}
public InsertRows(){
final JTable table, table2;
final DefaultTableModel model, model2;
JFrame frame = new JFrame("Inserting rows in the table!");
String data[][] = {{"Vinod","100"},{"Raju","200"},{"Ranju","300"}};
String col[] = {"Name","code"};
Object[][] selrowData = {};
model = new DefaultTableModel(data,col);
model2 = new DefaultTableModel(selrowData,col);
GridLayout gl = new GridLayout(2,1);
table = new JTable(model);
table2 = new JTable(model2);
//Insert first position
model.insertRow(0,new Object[]{"Ranjan","50"});
//Insert 4 position
model.insertRow(3,new Object[]{"Amar","600"});
//Insert last position
model.insertRow(table.getRowCount(),new Object[]{"Sushil","600"});
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
String selectedData2 = null;
Object[][] val = {};
int selectedRow = table.getSelectedRow();
int selectedColumns = table.getColumnCount();
model2.insertRow(0,new Object[]{(String) table.getValueAt(selectedRow, selectedColumns-selectedColumns),(String) table.getValueAt(selectedRow, selectedColumns-1) });
}
});
frame.setLayout(gl);
frame.add(new JScrollPane(table));
frame.add(new JScrollPane(table2));
frame.setSize(600,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

JTable doesn't add header row

I try to add header row to my JTable and next put table on panel.
This is my sample code :
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
DefaultTableModel tab = new DefaultTableModel();
tab.setColumnIdentifiers(new String[] {"Name", "Price"});
for (String key : tmpCart.keySet())
tab.addRow(new Object[] {key, tmpCart.get(key)});
JTable jTab = new JTable(tab);
jTab.setBounds(10, 10, 200, 200);
jTab.setBackground(Color.orange);
jTab.setRowHeight(25);
JScrollPane pan =new JScrollPane(jTab);
MainPanel.add(pan);
// MainPanel.add(jTab);
// pan.repaint();
How do I write it properly?
//answer
I try create JTable dynamically, after push button, I want get data from Hashtable, create table and put this table on panel.
First step is remove all components from panel, and next create JTable using data from Hashmap`
full function:
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
DefaultTableModel tab = new DefaultTableModel();
tab.setColumnIdentifiers(new String[] {"Name", "Price"});
for (String key : tmpCart.keySet())
tab.addRow(new Object[] {key, tmpCart.get(key)});
JTable jTab = new JTable(tab);
jTab.setBounds(10, 10, 200, 200);
jTab.setBackground(Color.orange);
jTab.setRowHeight(25);
// MainPanel.add(pan);
MainPanel.add(jTab);
}
This code works, create table and put it on panel, but doesn't set first row with column names ( text : "Names" and "Price").
Can't tell exactly what you are doing from the code sample.
If you are trying to dynamically update a table on a visible GUI, then there is not need to create a new table, just reset the TableModel.
table.setModel( model );
If you need more help then post your SSCCE that demonstrates the problem.
Edit:
First step is remove all components from panel,
Why are your removing components from the panel?
If you need to "swap" panels, then use a CardLayout.
If you need to "refresh" existing components, then just reset the model as explained above.
// MainPanel.add(pan);
MainPanel.add(jTab);
The scrollPane should be added to the GUI, not the table.
The table header is another component that only gets added automatically when the table is inside a JScrollPane. Your best bet is to create a JScrollPane via
new JScrollPane(table)
and add that to your MainPanel.
The other option is to added the header directly wherever you want it, and for that you can do:
panel.add(table.getTableHeader())
Try putting it into a JScrollPane.

How can I filter rows in a JTable?

I have a JTable with many strings in it. I have created a textbox for user entry, above the table. I want a row filter which can remove the rows having strings entered by the user in the text box. Please help me out for this.
from here:
sorting and filtering
In the following example code, you
explicitly create a sorter object so
you can later use it to specify a
filter:
MyTableModel model = new MyTableModel();
sorter = new TableRowSorter<MyTableModel>(model);
table = new JTable(model);
table.setRowSorter(sorter);
Then you filter based on the current
value of a text field:
private void newFilter() {
RowFilter<MyTableModel, Object> rf = null;
//If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter(filterText.getText(),0);
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}
This few line solution seems to work:
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt)
{
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(((DefaultTableModel) jTable1.getModel()));
sorter.setRowFilter(RowFilter.regexFilter(jTextField1.getText()));
jTable1.setRowSorter(sorter);
}
You can use JTable.setAutoCreateRowSorter which will use the default row sorter/filter of the JTable
To pick up the comment from kd304, you could use GlazedLists. There you'll use a FilterList as the input for your JTable, and the FilterList will take care of the rest.

Categories