Put JTextComponent and JComboBox in JTable - java

I have List and List and I need to create JTable with theese two columns. I am confused with model, can anybofy show me how to do that please, I am new to swing and Java ?

Please check out my answer to some other question. Where I have presented a simple table model often use.
In your case you would create data in a following way:
//I assumed here list 1 and 2 have the same sizes
List<Object> list1 = getList1();
List<Object> list2 = getList2();
int rNo = list1.size();
List<List<Object>> data = new ArrayList<List<Object>>(rNo);
int cNo = 2;
for(int i = 0; i < rNo; i++)
{
List<Object> r = new ArrayList<Object>(cNo);
r.add(list1.get(i));
r.add(list2.get(i));
data.add(r);
}
tm.setData(data);

No worries, just set your desired component as a cell editor for that column. Simple ain't it.
Example Snippet
public class JTextFieldCellEditor extends DefaultCellEditor {
JTextField textField;
public JTextFieldCellEditor() {
super(new JTextField());
textField = (JTextField) getComponent();
}
}
Then include it like below,
TableColumn column = myTable.getColumnModel().getColumn(0);
column.setCellEditor(new JTextFieldCellEditor());
Further reading:
Here is your best bet, Swing tutorial for JTable.

Related

How to Insert row data from database into specific columns of a JTable?

I have written a GUI Java program that manages a MySQL database. The user selects which columns (which tables and columns will be selected from the database) he/she wants to populate the JTable with.
I hard-coded the column names for the JTable so even if the user chooses to only display the data from a subset of columns, all of the column-names will be visible.
The problem is that when the user chooses columns in a different order than my JTable is anticipating, the data gets displayed in the wrong column.. It's a bit hard to explain so here's a screenshot of the genre data being loaded into the length column:
tableGenerator class:
package gui;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
public class TableGenerator
{
private ArrayList columnNames = new ArrayList();
private ArrayList data = new ArrayList();
private Vector columnNamesVector = new Vector();
private Vector dataVector = new Vector();
private int columns = 0;
private int rows = 0;
#SuppressWarnings("unchecked")
public TableGenerator(ResultSet rs)
{
try{
ResultSetMetaData md = rs.getMetaData();
columns = md.getColumnCount();
// Get column names
columnNames.add("Title");
columnNames.add("Year");
columnNames.add("Length");
columnNames.add("Genre");
columnNames.add("Actor");
columnNames.add("Producer");
columnNames.add("Director");
columnNames.add("Writer");
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columnNames.size());
for (int i = 1; i <= columns; i++)
{
row.add(rs.getObject(i));
}
data.add( row );
rows++;
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
}
public Vector getColumns(){
return columnNamesVector;
}
public Vector getData(){
return dataVector;
}
public ArrayList getColumnNames(){
return columnNames;
}
public int getNumberOfRows(){
return rows;
}
}
I'm using the DefaultTableModel with some modifications.. :
model = new DefaultTableModel(rows, columns){
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
#Override
public Class<?> getColumnClass(int column) {
if (column < classes.length)
return classes[column];
return super.getColumnClass(column);
};};
Your query should always return the data for all columns. This means the data will be stored in the same manner in the TableModel.
You can then change the view for the columns to be displayed. That is you can remove TableColumns from the TableColumnModel of the JTable and only the data the user want to view will be displayed, even though it is still available in the model. Then means the user can click on any check box at any time and you don't need to redo the database query, only add the TableColumn back to the table.
Check out Table Column Manager for an example of this approach. This class uses a popup menu to manage the columns, but you can still use your check boxes. You just need to invoke the appropriate method of the TableColumnManager to hide/show a column. That is, assuming the labels of the check boxes match the headings in the table you can just use the check box text to hide/show a column.
The other approach is to NOT hard code the column names (if you build your query to only get specific columns) but instead get the column names from the meta data of the ResultSet. The TableFromDatabaseExample.java from Table From Database shows how this can be done. The code is generic so that appropriate renderers are used for Dates, Integers etc.

How to add a row to JTable after populating data using DbUtils.resultSetToTableModel?

I have a JTable defined in this way:
public JTable table_1;
model_3 = new DefaultTableModel();
table_1 = new JTable(model_3);
scrollPane_5.setViewportView(table_1);
Add row:
model_3.addRow(new Object[]{table.getValueAt(row,0) , table.getValueAt(row,1) ,table.getValueAt(row,2) , commentFood });
Remove Row:
model_3.removeRow(row); //row is an integer
Until here, it used to work properly. As you can see this table is defined as public because sometimes I need to fill it up from another JFrame in this way:
takeOrder to = new takeOrder();
//Get data from DB to resultSet
to.table_1.setModel(DbUtils.resultSetToTableModel(resultSet));
If I fill up the table in this way and try to add or remove my model_3, it will not work! Any suggestion that how I can add or remove to the table after using DbUtils.resultSetToTableModel(resultSet) will be appreciated.
As I couldn't find any information on the internet and I saw couple of people asked same question with no answer. I came up with this solution:
if (formOut) {
for (int i = 0; i < table_1.getRowCount(); i++) {
model_3.addRow(new Object[]{table_1.getValueAt(i,0),
table_1.getValueAt(i, 1), table_1.getValueAt(i, 2)});
}
}
formOut = false;
table_1.setModel(model_3);
fromOut is a boolean to check if I have used another model for my table. If so I add data from table to previous model, and then I reference that model to my table. Now I can add to that model as well.

Set VALUE and LABEL to an ITEM JComboBox in Java

I have a JComboBox where the items are the results of a query. The combo shows all the categories names taken from a query, right? Ok, it works. Now I need to give each item a value, which would be the ID of the product.
This is what I've got so far:
final JComboBox proveedorCombo = new JComboBox();
contentPanel.add(proveedorCombo);
ProveedorDAO dao = new ProveedorDAO();
List<Proveedor> proveedor = dao.getAll();
Object[][] elementos = new Object[proveedor.size()][2];
for (int i = 0; i < proveedor.size(); i++) {
Proveedor p = proveedor.get(i);
elementos[i][0] = p.getId();
elementos[i][1] = p.getNombre();
proveedorCombo.addItem(elementos[i][1]);
}
As you can see in the code, the "label" of each item is the name of it. Now, how can I set each item its ID so I can manipulate after?
You'll want to use the IDs of the values as the values in your JComboBox, and use a custom ListCellRenderer to look up the name for an ID value.
You can do this by building a Map of names by their ID, and having your renderer return names for values.

How do I get an updated post-sort TableModel?

I have a JTable using setAutoCreateRowSorter(true) and a RowSorterListener attached, per below, because I need to perform some operations elsewhere in my application upon a sort of the JTable.
I find that whenever I click a column header to sort, the JTable redisplays the rows in the proper order and the listener is called, but the TableModel I pull out is always the original pre-sort table model.
table.getRowSorter().addRowSorterListener(new RowSorterListener() {
#Override
public void sorterChanged(RowSorterEvent rsevent) {
rsevent.getSource().getModel(); // Nope, original ordering here
table.getModel(); // Same thing
}
};
How do I get the new post-sort ordering of the rows, as is now displayed in the JTable?
The data in the TableModel never changes, only the view of the data changes.
If you want the data from the model in the order it is displayed in the table then you just use:
table.getValueAt(row, column);
In other words you need to iterate through all the rows and columns to get the data in the currently viewed order.
I think you can use table.convertRowIndexToModel(int ...), however I think that there's a better solution available.
If you define your own convertRowIndexToModel() that's a quick lookup (perhaps through a map, O(1)), that solution should be sufficient. If it's O(n), then that's what needs to be fixed.
Simply go through a loop of the rows, convert each one and do the lookup using the resulting index.
Here's 2 methods in TableSorter that should be of interest:
private Row[] getViewToModel() {
if (viewToModel == null) {
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) {
viewToModel[row] = new Row(row);
}
if (isSorting()) {
Arrays.sort(viewToModel);
}
}
return viewToModel;
}
and:
private int[] getModelToView() {
if (modelToView == null) {
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) {
modelToView[modelIndex(i)] = i;
}
}
return modelToView;
}
Hi I know this is a really late answer, but I tried the code used on the comment of #LazyCubicleMonkey and it did work here is my code in getting the row when the jTable is sorted.
DefaultTableModel search_model = (DefaultTableModel) jTable.getModel();
search_model.removeRow(jTable.convertRowIndexToModel(row));
jTable.setModel = (search_model)

How do I populate a JComboBox with an ArrayList?

I need to populate a JComboBox with an ArrayList. Is there any way to do this?
Use the toArray() method of the ArrayList class and pass it into the constructor of the JComboBox
See the JavaDoc and tutorial for more info.
Elegant way to fill combo box with an array list :
List<String> ls = new ArrayList<String>();
jComboBox.setModel(new DefaultComboBoxModel<String>(ls.toArray(new String[0])));
I don't like the accepted answer or #fivetwentysix's comment regarding how to solve this. It gets at one method for doing this, but doesn't give the full solution to using toArray. You need to use toArray and give it an argument that's an array of the correct type and size so that you don't end up with an Object array. While an object array will work, I don't think it's best practice in a strongly typed language.
String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);
Alternatively, you can also maintain strong typing by just using a for loop.
String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);
DefaultComboBoxModel dml= new DefaultComboBoxModel();
for (int i = 0; i < <ArrayList>.size(); i++) {
dml.addElement(<ArrayList>.get(i).getField());
}
<ComboBoxName>.setModel(dml);
Understandable code.Edit<> with type as required.
I believe you can create a new Vector using your ArrayList and pass that to the JCombobox Constructor.
JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));
my example is only strings though.
Check this simple code
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class FirstFrame extends JFrame{
static JComboBox<ArrayList> mycombo;
FirstFrame()
{
this.setSize(600,500);
this.setTitle("My combo");
this.setLayout(null);
ArrayList<String> names=new ArrayList<String>();
names.add("jessy");
names.add("albert");
names.add("grace");
mycombo=new JComboBox(names.toArray());
mycombo.setBounds(60,32,200,50);
this.add(mycombo);
this.setVisible(true); // window visible
}
public static void main(String[] args) {
FirstFrame frame=new FirstFrame();
}
}
By combining existing answers (this one and this one) the proper type safe way to add an ArrayList to a JComboBox is the following:
private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
In your GUI code you set the entire list into your JComboBox as follows:
DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);
i think that is the solution
ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String hql = "FROM table ";
org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();
cat.getLibCat();//table colonm getter
combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());

Categories

Resources