I have JTable which has few columns.In that I have JComboBox. At program start I want them to be empty.I have one JButton on click action of button i have the code to add row dynamically in table.
But after adding the row i get garbage value in the cell having JComboBox. As shown in below figure :
And here is the code :
Code to add JComboBox in table
// Create columns names
String columnNames[] = { "Item", "Sun Item", "Required Quantity","Price","Gross Amount" };
// Create some data
final String dataValues[][] =
{
{ "", "", "","","", },
};
tableModel = new DefaultTableModel(dataValues, columnNames);
// Create a new table instance
table = new JTable( tableModel );
updateItemCombo();
TableColumn itemColumn = table.getColumnModel().getColumn(0);
itemColumn.setCellEditor(new DefaultCellEditor(comboItem));
public void updateItemCombo(){
Vector<String> s = new Vector<String>();
try{
setConnectin();
String str = "select * from ItemTable";
stmt = conn.createStatement();
rs = stmt.executeQuery(str);
while(rs.next())
{
String nm = rs.getString("Item_Name");
s.add(nm);
}
conn.close();
}catch(Exception e2){
e2.printStackTrace();
}
DefaultComboBoxModel<String> modelData = new DefaultComboBoxModel<String>(s);
comboItem.setModel(modelData);
}
Code to add row dynamically on button click :
btnAddOrder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
tableModel.addRow(dataValues);
tableModel.fireTableDataChanged();
}
});
What should i do to remove this garbage value from table? Please help
The addRow(...) method takes a 1-Dimensional array as a parameter. You are attempting to add a 2-Dimensional array.
Also, do not use:
tableModel.fireTableDataChanged();
it is the job of the TableModel to invoke the appropriate fireXXX() method, which by the way in this case would be fireTableRowsInserted(...).
Related
I made a GUI using JTable(tableModel) and a JPanel where the user can add data through JTextFields to an Arraylist, but for some reason when I click the add JButton, the adding fails and points to the line where I want to add the arraylist row to the tableModel.
public final static ArrayList<Members> adat = new ArrayList<>();
DefaultTableModel tableModel;
String[][] dummy = new String[][]{{"001", "Jack Black", "London", "20"}};
String[] header = new String[]{"id", "Name", "City", "Age"};
tableModel = new DefaultTableModel(dummy, header);
JTable t = new JTable();
t.setModel(tableModel);
panel1.add(new JScrollPane(t));
frame.add(panel1);
JPanel jp = new EditPanel();
frame.add(jp);
public static void newData() { // the "add" button function
Members newMember = null;
try {
newMember = new Members(
Integer.parseInt(EditPanel.idEdit.getText()),
EditPanel.nameEdit.getText(),
EditPanel.cityEdit.getText(),
Integer.parseInt(EditPanel.ageEdit.getText())
);
adat.add(newMember);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error in modification", ERROR_MESSAGE);
}
toTable();
}
and the method toTable() gets the members data from the arraylist to the JTable
static void toTable() { // adding the users data to the table
if (adat.size() > 0) {
for (int i = 0; i < adat.size(); i++) {
int id = adat.get(i).id;
String name = adat.get(i).name;
String city = adat.get(i).city;
int age = adat.get(i).age;
Object[] data = new Object[4];
data[0] = id;
data[1] = name;
data[2] = city;
data[3] = age;
tableModel.addRow(data); // this is the line where the error points
}
}
}
You're encountering an error at tableModel.addRow(data); because tableModel does not have a method called addRow (docs).
You probably mixed up the DefaultTableModel tableModel with the actual JTable t.
It should be t.addRow(data), although you need to make t global first!
On load, my JTable has 2 columns - . So its a string in the first column and a checkbox in the second column. When I click on the checkbox tableChanged is fired and I can print the row data that was selected.
I need to change the table data when user selects a new category in the dropdown.
When the table data is updated, and I click on the checkbox the tableChanged is no longer fired.
This is what I have:
This is how I am updating the table data:
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String t = (String) comboBox.getSelectedItem();
if (t.equals("survey2")) {
String[] columnNames = { "Volume Name", "Select" };
Object[][] data = { { "pt1", false }, { "pt2", false },
{ "pt3", false }, { "pt4", false },
};
model = new DefaultTableModel(data, columnNames);
table.setModel(model);
}
}
});
This is my tableChanged:
table.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
if ((Boolean)table.getModel().getValueAt(table.getSelectedRow(), 1)) {
System.out.println(">\t"
+ table.getValueAt(table.getSelectedRow(), 0));
} else {
System.out.println(">\t"
+ table.getValueAt(table.getSelectedRow(), 0));
}
}
});
I do not understand why the event is not fired after updating the model. Am I updating the table incorrectly?
You area creating a new TableModel but you added the ChangeListener to the old TableModel.
Don't create a new TableModel!
You can clear the data by using setRowCount(0).
The you can add the new data back to the DefaultTableModel by using:
the setDataVector(...) method, or
by adding data back to the model one row at a time using the addRow(...) method.
So there is no need to create a new TableModel. If you want to create a new TableModel then you also need to add your ChangeListener to this new model.
I need delete deleted row from my arraylist...
private GuiIO guiIO;
private DefaultTableModel tableModel;
private List<Book> zoz;
public MyGui() {
initComponents();
this.setLocationRelativeTo(this.getRootPane());
this.guiIO = new GuiIO();
tableModel = new DefaultTableModel(new String[]{"Znacka", "Model", "Najazdene", "Rok vyroby", "Vykon", "Cena"}, 0);
this.tblTabulka.setModel(tableModel);
this.tblTabulka.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
tblTabulka.setAutoCreateRowSorter(true);
TableRowSorter rowSorter = new TableRowSorter(tableModel);
zoz = guiIO.getAllBook();
}
my function for delete row from model:
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
final int sectedRowIndex = this.tblTabulka.getSelectedRow();
this.tableModel.removeRow(sectedRowIndex);
zoz = guiIO.getAllBook();
}
public List getAllBook() {
List all_book = new ArrayList<Book>();
for (Containerable item = this.book.getFirst();
item!=null;
item = this.book.getNext())
all_book.add(item);
return all_book;
}
but i need delete it from my private List zoz;
how can i do it?
I need delete it from my private List zoz?
zoz.remove(sectedRowIndex); // if table is not sortable
Note:
Do not initialize the list again after deleting the selected row.
DefaultTableModel is not populating from the list
put a check tblTabulka.getSelectedRow() != -1 before deleting the row whether row is selected or not?
Use Map instead of List something like
Map<String,Book> books = new HashMap<String,Book>();
where you can make isbn or id as key.
Sample code:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// check for selected row first
if (tblTabulka.getSelectedRow() != -1) {
// get value of first cell of selected row
String isbn= (String)tableModel.getValueAt(tblTabulka.getSelectedRow(), 0);
books.remove(isbn);
// remove from the model also
model.removeRow(tblTabulka.getSelectedRow());
}
}
});
I have a JTable with the column names " Names " , " Quantity " and " Unit " .
I'm coding a program where you get the ingredients names.
So i need to get the whole row of one column and String it all up together,
because i need to store it in mySql and i have already set it all as String.
Any idea how i can do this ?
My code are as follows :
JTable Code:
DefaultTableModel model = (DefaultTableModel)table.getModel();
if(!txtQty.getText().trim().equals("")){
model.addRow(new Object[]{ingCB.getSelectedItem().toString(),txtQty.getText(),unitCB.getSelectedItem().toString()});
}else{
JOptionPane.showMessageDialog(null,"*Quantity field left blank");
}
Getting the values and for storing :
for(int i = 1; i<= i ; i++){
ingredients = table.getName();
}
This is for loop is wrong and it does not work because i have a constructor to take in Ingredients but because it is inside the loop, it cannot take it in.
Any suggestions please ? Thank you.
Constructor :
Food e2 = new Food(Name, Description, priceDbl, Image, Category, Ingredients, promotion );
e2.createFood();
I'm coding a program where you get the ingredients names. So i need to get the whole row of one column and String it all up together, because i need to store it in mySql and i have already set it all as String.
Want to do so, try this. Here I am getting result into ArrayList and String, as I am commented ArrayList you can avoid it.
public class TableValuePrint extends JFrame implements ActionListener{
private final JButton print;
private final JTable table;
private String str="";
public TableValuePrint() {
setSize(600, 300);
String[] columnNames = {"A", "B", "C"};
Object[][] data = {
{"Moni", "adsad", "Pass"},
{"Jhon", "ewrewr", "Fail"},
{"Max", "zxczxc", "Pass"}
};
table = new JTable(data, columnNames);
JScrollPane tableSP = new JScrollPane(table);
JPanel tablePanel = new JPanel();
tablePanel.add(tableSP);
tablePanel.setBackground(Color.red);
add(tablePanel);
setTitle("Result");
setSize(1000,700);
print=new JButton("Print");
JPanel jpi1 = new JPanel();
jpi1.add(print);
tablePanel.add(jpi1,BorderLayout.SOUTH);
print.addActionListener(this);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableValuePrint ex = new TableValuePrint();
ex.setVisible(true);
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==print){
// ArrayList list = new ArrayList();
for(int i = 0;i<table.getModel().getRowCount();i++)
{
//list.add(table.getModel().getValueAt(i, 0)); //get the all row values at column index 1
str=str+table.getModel().getValueAt(i,0).toString();
}
//System.out.println("List="+list);
System.out.println("String="+str);
}
}
}
Output
String=MoniJhonMax
I have jFrame2 which contains jTable with 4 columns (the jTable taking data from table in database which contain 20 columns)
Also I have jFrame1 which I have used it to fill database.
What I want to do that when I select row in jTable and click jButton, it must open jframe1 showing all data for that row.
i will clear what i want in points
*i want open jframe1 from jframe2 via jbutton(this task is done and this is the code)
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jButton2){
jframe2 regFace =new jframe2();
regFace.setVisible(true);
}}
*once jframe1 opened by jbutton in jframe2 it must show in it fields all data of selected row in jframe2>>this point mean
........-sql query executed once jfram1 opened by Jbutton in jframe2
.........-showing data in jtextfield taking from database by query i mentioned in line above (this task is done and this is the code but not completed)
try {
dbconnect = new myDbConnection();
ResultSet resultSet =null;
resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 FROM pledges where id='17'");
while (resultSet.next()){
id.setText(resultSet.getString(1));
area.setText(resultSet.getString(2));
location.setText(resultSet.getString(3));
status.setText(resultSet.getString(4));
// i = Long.parseLong(rs1.getString(1));
}
*in brief i want understand jframe1 that please if you opened by jframe2 execute a query and fill text fields by that query
*this is picture would clear better
here
It sounds like the part you are having trouble with is how to get the selected data from the table into the fields in jframe1.
A lot of this depends on the TableModel that is used in your JTable. Assuming you just used a DefaultTableModel, you can get the selected row data like this:
#Override
public void actionPerformed(ActionEvent e) {
int viewRow = myJTable.getSelectedRow();
int modelRow = myJTable.convertRowIndexToModel(viewRow);
DefaultTableModel model = (DefaultTableModel) myJTable.getModel();
// You will get a compiler warning on the following line, but there's not much you can do about it beside suppress it
Vector<Object> rowVector = (Vector<Object>) model.getDataVector().get(modelRow);
jframe2 regFace =new jframe2();
regFace.setSelectedRow(rowVector);
regFace.setVisible(true);
}
And you would have the following method in your jframe2 class:
public void setSelectedRow(Vector<Object> row ) {
id.setText(row.get(0).toString());
area.setText(row.get(1).toString());
location.setText(row.get(2).toString());
status.setText(row.get(3).toString());
// continue for all columns
}
before i put the answer i would thank #wolfcastle such a nice person.He almost answer the question and i'm just modify it to adapt it with sql query and database.
this is the code for jfrme2
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jButton2){
int viewRow = jTable1.getSelectedRow();
int modelRow = jTable1.convertRowIndexToModel(viewRow);
Object oc= jTable1.getModel().getValueAt(modelRow, 0);
String vv=oc.toString();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
jframe1 regFace =new jframe1();
try {
regFace.setSelectedRow(vv);
} catch (SQLException ex) {
Logger.getLogger(showp1.class.getName()).log(Level.SEVERE, null, ex);
}
regFace.setVisible(true);
}
}
and the the code for jframe1
public void setSelectedRow(String row ) throws SQLException {
dbconnect = new myDbConnection();
ResultSet resultSet =null;
System.out.print(row);
resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 ,date1,insname,oname,bname,street,junction,INSPSITION,recname1 FROM pledges where id='"+row+"'");
while (resultSet.next()){
id.setText(resultSet.getString(1));
area.setText(resultSet.getString(2));
location.setText(resultSet.getString(3));
status.setText(resultSet.getString(4));
date.setText(resultSet.getString(5));
insname.setText(resultSet.getString(6));
oname.setText(resultSet.getString(7));
bname.setText(resultSet.getString(8));
street.setText(resultSet.getString(9));
junction.setText(resultSet.getString(10));
insposition.setText(resultSet.getString(11));
recname.setText(resultSet.getString(12));
}
}