This type of post has been dealt with before, but I am having issues based on how my code is structured.
I am just simply trying to add a JComboBox to all rows in my last column. The code is below.
//Return Person objects from a method
ArrayList<Person> people = getPersonList();
String[] columnNames {"Name", "Age", "English Speaker?" };
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
JTable table = new JTable(model);
//Create JComboBox for last column (English Speaker?)
JComboBox<Integer> englishCombo = new JComboBox<>();
int count = 1;
//For loop to add each Person to there rows
//Also add a boolean value to determine check box
for(Person p: people)
{
boolean english =false;
if(p.isEnglishSpeaker() == true)
{
english = true;
}
else
{
english = false;
}
questionCombo.addItem(count);
model.addRow(new Object[]{p.getName(), p.getAge(), english);
}
//Get 3rd column (English Speaker)
TableColumn englishColumn = table.getColumnModel().getColumn(2);
//Add JComboBox to English Speaker
englishColumn.setCellEditor(new DefaultCellEditor(englishCombo));
When I run this code, it only displays true of false in the 3rd column, not the JcomboBox?
Could anyone identify the problem?
Thanks much appreciated
You've specified a custom editor; now you need to address the renderer. I see two possibilities:
Use JComboBox<String> with the desired true and false values, as shown here.
Use the default renderer and editor, JCheckBox, for values whose type is Boolean.class, as shown here and here.
Related
Once I have a JTable with many lines and each line has a column with a JComboBox, how to I read the column? I have been struggling with many classes and getting the components, but so far I can not get the combo box handle to remove, read or add item dynamically. I need to add values to the combo box dynamically (now they are static), remove them and then save to the database. getValueAt(row, col) only gives me the value of the object but not the instance of the combo box to manipulate it, maybe I don't have the correct approach.
This is how I created it:
private void startup() {
String[] values = {"001-abc", "002-fgh, "003-xyz"};
TableColumn comboCol15 = this.table.getColumnModel().getColumn(15);
comboCol15.setCellEditor(new DefaultCellEditor(getComboBox(values)));
}
private JComboBox getComboBox(String[] values) {
if (comboBox == null) {
comboBox = new JComboBox();
}
if (values != null && values.length > 0) {
comboBox.removeAllItems();
for (String key : values) {
comboBox.addItem(key);
}
}
return comboBox;
Solved:
ComboBoxTableCellEditor editor = new ComboBoxTableCellEditor();
TableColumn comboCol15 = this.tableFacturacion.getColumnModel().getColumn(15);
comboCol15.setCellEditor(editor);
ComboBoxTableCellEditor editor = (ComboBoxTableCellEditor)this.tableFacturacion.getCellEditor(0, 15);
JComboBox combobox = editor.getComboBox();
combobox.addItem("hola");
Today I did a simple student / course selection database.
Everything works fine so far.
Now I want to implement a graphical representation. I decided to use a JTable (wahltabelle) where each column is a course and each row a student.
There a different ways how a student can visit a course. That’s why I want a Combobox in each cell. The currently selected value represents the student’s current selection and can be changed by the course manager.
The values are loaded and stored from / to a database.
Unfortunately I didn’t find out how to represent an individual combobox in each cell of a table. Therefore I currently have a String representation of my comboboxes.
I know that I can easily change the default cell editor for a complete column. But unfortunately I’m not sure how to do that for a individual cell.
Do I have to write my own cellRenderer?
public void addWahldata(List<Fach> faecher)
{
Vector head = new Vector<>();
head.add("");
for(Fach aktuell : faecher)
{
head.add(aktuell.getBezeichner());
}
Vector data = new Vector<>();
wahltabelle.setModel(new DefaultTableModel(data, head));
Vector rowx = new Vector<>();
rowx.add("");
JComboBox temp= null;
for (int i=1; i<wahltabelle.getColumnCount(); i++)
{
JComboBox cb = new AbiMoeglichkeitenGetter().getAbiMoeglichkeiten(wahltabelle.getColumnName(i));
temp = cb;
rowx.add(cb);
}
data.add(rowx);
wahltabelle.setModel(new DefaultTableModel(data, head));
}
Thanks for any explanation.
I am experiencing a issue while trying to add new row in my JTable. My JTable is using DefaultTableModel, here is the code I use for adding a new row:
AddDialog diag = new AddDialog(MainWindow.getInstance(),"Add Entity",true,tab);
diag.setVisible(true);
if(diag.isSaved()) {
entity = diag.getEntity();
table = diag.getTableModel();
table.getEntities().add(entity);
if(tab instanceof TablePreview) {
tablePreview = (TablePreview)tab;
tableModel = (DefaultTableModel) (tablePreview.getTableView().getModel());
Object[] newRow = new Object[entity.getAttributes().size()];
int i=0;
for (Entry<String, Object> entry : entity.getAttributes().entrySet()) {
newRow[i++]=entry;
}
tableModel.addRow(newRow);
}else if(tab instanceof ChildTablePreview) {
System.out.println("Tab is instanceof ChildTablePreview");
}
}else {
System.out.println("Entity not saved!");
}
diag is instance of AddDialog which extends JDialog, and when I fill in the fields of the dialog and click save it creates an Entity class which I want to add to the table as a new row. The logic works fine, but when the row gets inserted into the table, for some reason table looks like this:
If anyone has any idea how I can fix this, I would really appreciate the help!
You need to use a custom cell renderer in your JTable.
How data appears is based on the class of the columns. The default renderer simply calls the .toString() function for the objects in the column. If the column contains a key value pair, its common for these to appear as key=value.
You need to set the renderer using the TableColumn method setCellRenderer. You can define this renderer to only display the value for the objects in that column.
Hi I want to check if table is made to add rows.If is not I want to show message :create table first. My problem : I do not know what I should type to if statement to check if is although one row made(which can suggest me that table was created).
I create table via NetBeans JFrame options this way:
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
/*
space is empty here because on start I do not create any rows.
user has to click button create or add rows.
*/
},
new String [] {
"Name", "Surname"
}
));
My if statment:
if(//do not know what type here because new Object [][] will not work){
JOptionPane.showMessageDialog(null, "Create table!");
}else //add row to table because exist {
Object[][] temp = new Object[data.length + 1][2];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 2; j++) {
temp[i][j] = data[i][j];
}
}
data = temp;
jTable1.setModel(new DefaultTableModel(data, columns));
}
Looks like you're using NetBeans GUI builder. If you go to the properties pane (the tab to the very right in Netbeans design view) with the jTable highlighted, you will see a property model
Click on the ... button to the right of the property, and a Dialog will pop up
Set the number of rows to 0, and the number of columns to how many columns you want, and set the column title and type and if you want it editable
Then in your actionPerformed, however you get the data for rows, add an array of that data to the model with model.addRow()
public void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// get row data, and put it into an array
Object[] row = {data1, data2, data3 ...};
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(row);
}
So whenever the button is pressed, a row will be added dynamically to your table. That's the easiest way to do it with GUI Builder
EDIT
If you want to check the number of rows then you check the rowCount
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
if (model.getRowCount() < 1) {
do something.
}
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);
}
}