How to add rows in JTable at runtime in Swing - java
Currently, i am trying to add rows to a JTable in java swing and getting the following output. Null getting appended with the first cell showing java.lang.someerror
This is the output with cells showing error
, I cant able to append strings in the table. Getting an error like
cannot convert string to object
Need to insert to the table (String Object[][]) which is in the code follows as
class SimpleTableExample
extends JFrame
{
// Instance attributes used in this example
private JPanel topPanel;
private JTable table;
private JScrollPane scrollPane;
// Constructor of main frame
public SimpleTableExample()
{
// Set the frame characteristics
setTitle( "Simple Table Application" );
setSize( 1100, 150 );
setBackground( Color.gray );
// Create a panel to hold all other components
topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create columns names
String columnNames[] = { " Date & Time", "VRP", "VYP", "VBP", "CRP","CYP","CBP","PO","BM","ARM","WT","RH","CNT","BCC","W","F","L","status"};
// Create some data
String dataValues[][] =
{
{ null, null, null , null, null, null, null, null , null, null,null, null, null , null, null, null, null, null },
{ null, null, null , null, null, null, null, null , null, null,null, null, null , null, null, null, null, null },
{ null, null, null , null, null, null, null, null , null, null,null, null, null , null, null, null, null, null },
{ null, null, null , null, null, null, null, null , null, null,null, null, null , null, null, null, null, null },
{ null, null, null , null, null, null, null, null , null, null,null, null, null , null, null, null, null, null },
{ null, null, null , null, null, null, null, null , null, null,null, null, null , null, null, null, null, null },
};
String Object[][] = {{"85", "85","85","85","85","85","85","85","85","85","85","85","85","85","85","85","85","85"}};
DefaultTableModel dm = new DefaultTableModel(0,0);
dm.setColumnIdentifiers(columnNames);
// Create a new table instance
table = new JTable(dm);
TableColumn column = null;
for(int i =0; i<18; i++){
column = table.getColumnModel().getColumn(i);
if(i==0)
{
column.setPreferredWidth(100);
}
else{
column.setPreferredWidth(40);
}
}
table.setModel(dm);
/* i have tried to use vector for insertion didn't work
Vector <Object> data = new Vector <Object>();
data.add(null);
data.add(null);
dm.addRow(data); */
((DefaultTableModel) ((JTable) table).getModel()).addRow(new Object[]{}); //for this code row got inserted with some error displaying in first cell
// Add the table to a scrolling pane
scrollPane = new JScrollPane(table);
topPanel.add( scrollPane, BorderLayout.CENTER );
}
// Main entry point for this example
public static void main( String args[] )
{
// Create an instance of the test application
SimpleTableExample mainFrame = new SimpleTableExample();
mainFrame.setVisible( true );
}
}
((DefaultTableModel) ((JTable) table).getModel()).addRow(new Object[]{"85","85","85","85","85","85","85","85","85","85","85","85","85","85","85","85","85","85"});
If I use this, getting this error...
Type mismatch: cannot convert from String to
Object
Kindly anyone help with this issue
The constructor is asking you for an Object array, which is declared with additional braces. I suspect that you are using a String[] instead of a Object[][]:
Object[][] defaultValues={
{"content1"},
{"content2"}
};
It has worked for me when using the constructor new DefaultTableModel(Object[][] data,Object[] columnames);.
Related
JDBC, Prepared Statement getInt() returns 0
In my DB every question has a valid questionID (primary Key) and categoryID (foreign Key to category table). The problem is: in the Result Set for every question both IDs are 0 instead of what's written in the DB. All other arguments are filled out correctly. private ArrayList<Question> questions = new ArrayList<Question>(); private Connection connie; private PreparedStatement psShowQuestions; psShowQuestions= connie.prepareStatement("SELECT * FROM question"); ResultSet rs = psShowQuestions.executeQuery(); while (rs.next()) { questions.add(new Question(rs.getInt("questionID"), rs.getInt("categoryID"), rs.getString("question"), rs.getString("rightAns"), rs.getString("wrong1"), rs.getString("wrong2"), rs.getString("wrong3"), rs.getString("hint"))); } Collections.shuffle(questions); Edit 1 Here is the original code (in the post I changed the variables from German to English): The creation of my SQL table: CREATE TABLE `frage` ( `frageID` int(11) NOT NULL, `kategorieID` int(11) DEFAULT NULL, `frage` varchar(200) NOT NULL, `richtig` varchar(200) NOT NULL, `falsch1` varchar(200) NOT NULL, `falsch2` varchar(200) NOT NULL, `falsch3` varchar(200) NOT NULL, `hinweis` varchar(200) NOT NULL, `anzFalsch` int(11) DEFAULT NULL, `anzRichtig` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; private ArrayList<Frage> fragen = new ArrayList<Frage>(); private Connection connie; private PreparedStatement psGetFragen; ResultSet rs = psGetFragen.executeQuery(); while (rs.next()) { fragen.add(new Frage(rs.getInt("frageID"), rs.getInt("kategorieID"), rs.getString("frage"), rs.getString("richtig"), rs.getString("falsch1"), rs.getString("falsch2"), rs.getString("falsch3"), rs.getString("hinweis"))); } Collections.shuffle(fragen);
Most likely, there is a problem with the constructor. You might have not set questionID and categoryID in the constructor and therefore you are getting the default value of int as 0.
JDBI Inserting NULL into bit column causes java.sql.BatchUpdateException: Data truncation: Data too long for column
When running a batch update query using jdbi library with a query similar to below #SqlBatch("INSERT INTO <table> (<columns>) VALUES (<columnsBind>)" + " ON DUPLICATE KEY UPDATE <updateString>;") I get a java.sql.BatchUpdateException: Data truncation: Data too long for column bit_column error for a column of type bit(1). I'm attempting to insert a NULL value into this. I've confirmed that the column is nullable. In debugging I'm able to see that the binding for the named value is of type ObjectArgument rather than NullArgument though it's not a problem for other entries which can handle the null just fine. I tried to replace the ObjectArgument with NullArgument but that leads to a java.io.NotSerializableException Is this something anyone has run into before? EDITED: With an edited version of the ClientPreparedStatement object that is generated, I've renamed the columns and changed the ones with actual values to others of the same type. All nulls are the same, they were unquoted. INSERT INTO table (not_bit_column_null,bit_column,not_bit_column_null,varchar_column,varchar_column,not_bit_column_null,varchar_column,not_bit_column_null,not_bit_column_null,not_bit_column_null,varchar_column,varchar_column,varchar_column,not_bit_column_null,not_bit_column_null,varchar_column,not_bit_column_null,id,not_bit_column_null) VALUES (null,null,null,'text','text',null,'text',null,null,null,null,'text','text',null,null,'text',null,'22',null) ON DUPLICATE KEY UPDATE not_bit_column_null = null, bit_column = null, not_bit_column_null = null, varchar_column = 'text', varchar_column = 'text', not_bit_column_null = null, varchar_column = 'text', not_bit_column_null = null, not_bit_column_null = null, not_bit_column_null = null, not_bit_column_null = null, varchar_column = 'text', varchar_column = 'text', not_bit_column_null = null, not_bit_column_null = null, varchar_column = 'text', not_bit_column_null = null, id = '22', not_bit_column_null = null;
How to optimize a loop in java?
How can I optimize this following code. I want to display per colleges, departments, courses and students who are currently taking up such courses on my JTable. public void display(){ ... for(College co: collegeDao.getColleges().stream().sorted(Comparator.comparing(College::getName)).collect(Collectors.toList())){ dtm.addRow(new Object[]{co.getName()}); for(Department department: deptDao.getDepartments().stream().sorted(Comparator.comparing(Department::getName)).collect(Collectors.toList())){ if(Objects.equals(department.getCollege().getId(), co.getId())){ dtm.addRow(new Object[]{null, department.getName()}); for(Course c: courseDao.getCourses().stream().sorted(Comparator.comparing(Course::getName)).collect(Collectors.toList())){ if(Objects.equals(c.getDepartment().getId(), department.getId())){ dtm.addRow(new Object[]{null, null, c.getName()}); for(Student st: cTakenDao.getCoursesTaken(c).stream().sorted(Comparator.comparing(Student::getName)).collect(Collectors.toList())){ dtm.addRow(new Object[]{null, null, null, st.getName()}); counter++; } } } dtm.addRow(new Object[]{null, null, null, null, "Maxumim Population Allowed "+department.getPopulation()}); dtm.addRow(new Object[]{null, null, null, null, "Remaining Slot "+(department.getPopulation()-counter)}); counter = 0; } } } ... It actually works, but it takes time to load my data on the table. If I use LEFT JOIN on my sql query, all of my data were being repeated on upon display on my JTable. Hope someone can suggest better solution of it, thank you in advance.
HOW TO FIX Cannot add or update a child row: a foreign key constraint fails
I am having the table called eventUserRelationMapping in that table there is two foreign key Event_id and Ringee_User_id. this eventUserRelationMapping doesn't have a separate DO class its under the UserDO class. here I am trying to get the EventUserRelationMapping for front end use. if I get the method I got the error like this Cannot add or update a child row: a foreign key constraint fails (`ringeeapp_dev`.`event_user_relation`, CONSTRAINT `FK_EVT_RINGEE_USER_ID` FOREIGN KEY (`RINGEE_USER_ID`) REFERENCES `ringee_user` (`RINGEE_USER_ID`)) but the data inserted in that eventUserRelationMApping table this is my geteventUserMapping()method in DAOImpl Override public List<UserDO> getEventUserRelationMapping(UserDO userDO) throws UserDataException { JdbcTemplate jd = this.getJdbctemplate(); int isNotDeleted = IRingeeConstants.IS_NOT_DELETED; try { List<UserDO> userDOs = jd.query(GET_EVENT_USER_RELATION_MAPPING, new Object[] {userDO.getRingeeUserId() , isNotDeleted }, new RowMapper<UserDO>() { #Override public UserDO mapRow(ResultSet rs, int rowNum) throws SQLException { UserDO userDO = new UserDO(); userDO.setEventUserId(rs.getLong(1)); userDO.setEventId(rs.getLong(2)); userDO.setRingeeUserId(rs.getLong(3)); userDO.setAttending(rs.getInt(4)); userDO.setDeleted(rs.getInt(5)); return userDO; } }); return userDOs; }catch (DataAccessException dExp) { throw new UserDataException("Error while getting eventUserRelationMapping for user " + userDO.getRingeeUserId(), dExp); } } this is query for GET_EVENT_USER_RELATION_MAPPING private static final String GET_EVENT_USER_RELATION_MAPPING = "SELECT EVENT_USER_ID, EVENT_ID, RINGEE_USER_ID, IS_ATTENDING, IS_DELETE FROM EVENT_USER_RELATION WHERE RINGEE_USER_ID = ? AND IS_DELETE = ? "; this is the test case of getEventUserRelationMapping #Test #Rollback(false) public void testgetEventUserRelationMapping() { ArrayList<UserDO> userDOs = new ArrayList<>(); UserDO userDO = getUserDO(); userDOs.add(userDO); UserDO userDO1 = getUserDO1(); userDOs.add(userDO1); EventDO eventDO = getEventDO(); eventDO.setRingeeUserId(userDO.getRingeeUserId()); try { eventDAOImpl.addEvent(eventDO); userDAOImpl.addEventUserRelationMapping(userDOs, eventDO.getEventId()); List<UserDO> userDOs1 = userDAOImpl .getEventUserRelationMapping(userDO); Assert.assertEquals(1, userDOs1); } catch (UserDataException uExp) { uExp.printStackTrace(); Assert.fail(); } } please help me to fix this issue and why it happends THIS IS THE MYSQL QUERY FOR EVENT TABLE CREATE TABLE `event` ( `EVENT_ID` BIGINT(20) NOT NULL, `RINGEE_USER_ID` BIGINT(20) NOT NULL, `TEXT` VARCHAR(45) NOT NULL, `PLACE` VARCHAR(45) NOT NULL, `EVENT_DATE` DATETIME NOT NULL, `START_TIME` VARCHAR(10) NULL DEFAULT NULL, `END_TIME` VARCHAR(10) NULL DEFAULT NULL, `IS_DELETE` TINYINT(1) NULL DEFAULT '0', `CREATED_DTTM` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, `MODIFIED_DTTM` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`EVENT_ID`), INDEX `EVENT_ID` (`EVENT_ID`), INDEX `FK_EVENT_RINGEE_USER_ID` (`RINGEE_USER_ID`), CONSTRAINT `FK_EVENT_RINGEE_USER_ID` FOREIGN KEY (`RINGEE_USER_ID`) REFERENCES `ringee_user` (`RINGEE_USER_ID`) ON UPDATE NO ACTION ON DELETE NO ACTION ) THIS IS FOR EVENTUSERRELATION TABLE MYSQL QUERY CREATE TABLE `event_user_relation` ( `EVENT_USER_ID` BIGINT(20) NOT NULL DEFAULT '0', `EVENT_ID` BIGINT(20) NULL DEFAULT NULL, `USER_RELATION_ID` BIGINT(20) NULL DEFAULT NULL, `IS_ATTENDING` TINYINT(4) NULL DEFAULT NULL, `CREATED_DTTM` TIMESTAMP NULL DEFAULT NULL, `MODIFIED_DTTM` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`EVENT_USER_ID`), UNIQUE INDEX `EVENIT_ID_USER_RELATION_ID` (`EVENT_ID`, `USER_RELATION_ID`), INDEX `FK_EVT_USR_USR_REL_ID` (`USER_RELATION_ID`), CONSTRAINT `FK_EVT_USR_USR_REL_ID` FOREIGN KEY (`USER_RELATION_ID`) REFERENCES `user_relation` (`USER_RELATION_ID`), CONSTRAINT `FK_EVT_USR_EVT_ID` FOREIGN KEY (`EVENIT_ID`) REFERENCES `event` (`EVENT_ID`) )
First i see an error in your #Test method Assert.assertEquals(1, userDOs1); <==> Assert.assertEquals(1, userDOs1.size()); To avoid this SQL Error you need to insert the data in your table and the in the join table Exemple : (tab1, tab2, tab_12) Insert values into tab1 (commit) Insert values into tab2 (commit) Insert values into tab_12 (commit)
iBatis generates only 6 parameters (all null), other time generates 9 parameters
I have a good insert statement which has 9 parameters, but for some reason iBatis generates only 6 for a particular object. For all other it generates 9, as it should. Could it be the fact that all params are NULL ? ?,?,?,?,?,null,?,null,null,null,null,null,?,?,?,null,null OK: Parameters: [[B#132b63e, [B#5ac911, [B#468066, xxxxxxxxxxxxxxxx, null, null, 0, 0, 0] NOK: Parameters: [null, null, null, null, null, null] And the error is as you expected: Missing IN or OUT parameters at index 7 INSERT 17 COLUMNS INTO SOME_TABLE VALUES ( #id#, #someObj.id#, #someOtherObj.id#, #aProperty#, #anotherProperty#, null, #yetAnotherProperty#, null, null, null, null, null, #prop1#, #prop2#, #prop3#, null, null) someObj and someOtherObj are NULL. Also my app uses cglib for lazy loading, so some enhances might be present, don't know if it affects something.
You could do this: INSERT 17 COLUMNS INTO SOME_TABLE VALUES ( #id#, <isNotNull property="someObj"> #someObj.id#, </isNotNull> <isNull property="someObj"> NULL, </isNull> <isNotNull property="someOtherObj"> #someOtherObj.id#, </isNotNull> <isNull property="someObj"> NULL, </isNull> #aProperty#, #anotherProperty#, null, #yetAnotherProperty#, null, null, null, null, null, #prop1#, #prop2#, #prop3#, null, null)