I wanted to add a JCheckBox column to my JTable without using models. I searched and found some solutions like using models but they are not what I wanted because my project is at its latest stage and might provide some problems and I don't know how to use Models as well. If anyone can help me find a solution I'll be grateful.
for (int cnt = 0; myStudent.currentCourses[cnt] != 0; cnt++){
for (course c : Courses) {
if (myStudent.currentCourses[cnt] == c.getCourseNum() && myStudent.groupNum[cnt] == c.getGroupsContained()) {
data[cnt][0] = String.valueOf(c.getCourseNum());
data[cnt][1] = String.valueOf(myStudent.groupNum[cnt]);
data[cnt][2] = String.valueOf(c.getUnits());
data[cnt][3] = c.getCourseName();
data[cnt][4] = String.valueOf(c.getSignedNum());
data[cnt][5] = c.getProfessorName();
data[cnt][6] = c.getExamDate();
data[cnt][7] = c.getClassSchedule();
data[cnt][8] = c.getPrerequisites();
data[cnt][9] = c.getExtraInfo();
}
}
}
courseTable = new JTable(data, columnNames);
Just to clarify some things that might confuse you (the whole code is about 800 lines). myStudent is an specific object from a student class and Courses is an ArrayList of a course class (the course class has some properties and I set my data with that specific course information using getters). I want to add JCheckBox column to my table for this reason: if the user choose some courses by checkbox (consider we have 4 courses) and then presses a button under the table, I want to remove that course (row) from the table dynamically.
Related
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.
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.
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);
}
}
i hav a ArreayList which is contain PRIvariable(name of the class) class data. Below shows my part of the java code. So now i want to put this Arraylist data to Jtable. how can i do that. Here i already added pri.dateText , pri.sum , pri.count to ar(arraylist)
PRIvariable pri=new PRIvariable();
while (reader.ready()) {
String line = reader.readLine();
String[] values = line.split(",");
if(values[2].equals(pri.incDate)){
if(values[4].equals("KI")){
pri.dateText=values[2]+" "+values[4];
pri.count=pri.count+1;
pri.sum = pri.sum+Integer.parseInt(values[7]);
}
}
}
System.out.println(pri.dateText+" "+pri.sum+" "+pri.count);
ar.add(pri);
Like all Swing components, a JTable relies upon the MVC pattern (at multiple levels, but that's not the subject).
You have one view (the JTable), one model (I'll come back on it later), and a controller (implemented here as a set of event listeners : one controller for each kind of control).
The array you have could be a good model starting point. However, Swing provides far better way to inject your data in JTable. Indeed, a JTable uses as model an implementation of TableModel. Hopefully, there already exist an implementation : DefaultTableModel.
So, here is what I suggest to you : create DefaultTableModel, put in its rows/columns all the data you want to display in your table, then call JTable#setModel(TableModel) to have thze table display your data.
Obviously, you'll soon find various misfits between DefaultTableModel and what you want to do. It will then be time for you to create our very own table model. But that's another question.
Besides, don't forget to take a look at Swing tutorial, it's usually a good thing when dealing with Swing components.
I don't see where you have an ArrayList anywhere.
First you create a PRIvariable object. Then you keep looping as you read a line of data from the file. For each line of data you split it into individual tokens and then add some of the token data to the PRIvariable ojbect. The problem is that you only have a single PRIVariable object. So every time you read a new line of data you change the values of the PRIvariable object. After all the looping you add this single PRIvariable object to your ArrayList, but you will only ever have one object in the ArrayList.
The easier solution is to update the TableModel as you get the data. Something like:
DefaultTableModel model = new DefaultTableModel(...);
JTable table = new JTable( model );
...
...
while (reader.ready())
{
String line = reader.readLine();
String[] values = line.split(",");
String[] row = new String[3];
row[0] = values[?];
row[1] = values[?];
row[2] = values[?];
model.addRow( row );
}
Look into GlazedLists. They make it extremely easy to create a suitable TableModel object from your list.
ArrayList< PRIvariable> myList = new ArrayList<PRIvariable>();
... fill up the list ...
// This assumes your object has a getName() and getAge() methods
String[] propertyNames = {"name","age"};
String[] columnLabels = {"Name","Age"};
// Are these columns editable?
boolean[] writeable = {false, false};
EventList<PRIvariable> eventList = GlazedLists.eventList(myList);
EventTableModel<PRIvariable> tableModel = new EventTableModel<PRIvariable>(eventList,propertyNames,columnLabels,writable);
JTable table = new JTable(tableModel);