[UPDATE!!!!]
This is the finish product:
: )
So I am working on a program that helps me organize and print seatings for dinner. I have a student class with instance variables of their FirstName, LastName, etc. I also have a DinnerTable Class that has List of Student and String teacherName. I have created a GUI that so that it is easier to assign different seats. I already have one tab on JTabbedPane that organizes student information(if they are available or not) and randomizes the tables they sit. Now, to better visualize the tables and to make it easier to assign each student to a specific seat, I need to make something like this:
I want to use the actual DinnerTable objects in the TableModel so that whenever I edit something on this Frame, the changes are translated to the objects. However, I am not really sure about what to do. Should I:
1.Create tables(one JTable for each DinnerTable) nested in the cells of a bigger JTable? But how can I perform actions such as swiping students between DinnerTable? Or
2.Align JTables in GridLayout or GridBagLayout? But again, how can I swap students?
Thank you!
package DinnerList;
public class Student
{
private String lastName;
private String firstName;
private int grade;
private int table;
private boolean gender;//Male=true, female=false;
private boolean available; //true=available;
public Student()
{
lastName="";
firstName="";
grade=0;
table=0;
gender=true;
available=true;
}
public Student(String l, String f, int i, boolean g, boolean a)
{
lastName=l;
firstName=f;
grade=i;
gender=g;
available=a;
//table is not written back to the txt.
table=0;
}
//Getters
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public int getGrade()
{
return grade;
}
public int getTable()
{
return table;
}
public boolean getGender()
{
return gender;
}
public boolean getAvailable()
{
return available;
}
//Setters
public void setLastName(String s)
{
this.lastName=s;
}
public void setFirstName(String s)
{
firstName=s;
}
public void setGrade(int i)
{
grade=i;
}
public void setTable(int hiahia)
{
table=hiahia;
}
public void setGender(boolean b)
{
gender=b;
}
public void setAvailable(boolean b)
{
available=b;
}
//Miscellaneous
public String toString()
{
String a="";
a=lastName+","+firstName+","+Integer.toString(grade)+","+Boolean.toString(gender)+","+Boolean.toString(available);
return a;
}
}
///////////////////////////////////
package DinnerList;
import java.util.ArrayList;
import java.util.List;
public class DinnerTable
{
private List<Student> members= new ArrayList<Student>();
private int tableNumber=0;
private int capacity=0;
private String teacherName="";
private boolean available=true;
public DinnerTable(int a, int b, String c, boolean d)
{
tableNumber=a;
capacity=b;
teacherName=c;
available=d;
}
public void setTableNumber(int a) {tableNumber=a;}
public void setCapacity(int a) {capacity=a;}
public void setTeacherName(String a) {teacherName=a;}
public void setAvailable(boolean b) {available=b;}
public void add(Student s)
{
if(available&&(members.size()<capacity))
{ this.members.add(s); }
else if(!available)
{ System.out.println("Adding Student failed, table "+tableNumber+" not available");}
else
{ System.out.println("Adding Student failed, table "+tableNumber+" is full");}
}
public int getTableNumber()
{return tableNumber;}
public int getCapacity() {return this.capacity;}
public String getTeacherName() {return teacherName;}
public boolean getAvailable() {return available;}
public List<Student> getMembers(){return members;}
public void remove(Student s)
{
if(members.contains(s))
{
members.remove(s);
}
else
{
System.out.println("Failed to remove student from table because it wasn't there");
}
}
}
/////////////////////
package DinnerList;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
public class DinnerTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
Object huahua =table.getModel().getValueAt(row, column);
String ppp="";
if(huahua!=null)
{
if(huahua instanceof Student)
{
ppp=((Student) huahua).getLastName()+", "+((Student)huahua).getFirstName();
}
else if(huahua instanceof String)
{
ppp=(String)huahua;
}
else
{
System.out.println("Error: DinnerTableCellRenderer intakes unknown data type");
}
}
else
{
ppp="";
}
JLabel label = (JLabel)super.getTableCellRendererComponent(table, ppp,isSelected, hasFocus,row, column);
return label;
}
}
//////////
package DinnerList;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
public class DinnerTableModel extends AbstractTableModel implements TableModel
{
private final String[] columnNames={"","","",""};
private List<DinnerTable> tableCollection= new ArrayList<DinnerTable>();
public DinnerTableModel(List<DinnerTable> huhu)
{
tableCollection.addAll(huhu);
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
if(tableCollection.size()%4==0)
{
return tableCollection.size()/4;
}
else
{
return (int)(tableCollection.size()/4)+1;
}
}
public String getColumnName(int col)
{
return columnNames[col];
}
public DinnerTable getTableAt(int row, int column)
{
if(tableCollection.size()>=(Integer)((row)/8)+column+1)
{
return tableCollection.get((Integer)((row)/8)+column);
}
else
{
return null;
}
}
public Object getValueAt(int rowIndex, int colIndex)
{
DinnerTable dd= this.getTableAt(rowIndex, colIndex);
String ss= "";
if(dd==null)
{
return "";
}
else if(rowIndex%8==0)
{
return (dd.getTableNumber()+". "+dd.getTeacherName());
}
else if(dd.getMembers().size()>=rowIndex%8)
{
return dd.getMembers().get(rowIndex%8);
}
else
{
return "";
}
}
public Class getColumnClass(int c)
{
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col)
{
if(this.getValueAt(row, col) instanceof Student)
{
return true;
}
else
{
return false;
}
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
if(aValue instanceof Student)
{
if(rowIndex%8!=0)
{
if(null!=this.getTableAt(rowIndex,columnIndex))
{
this.getTableAt(rowIndex,columnIndex).getMembers().set(rowIndex%8-1, (Student)aValue);
}
else
{
System.out.println("error: Attempting to put student in nonexistent table in table list gui");
}
}
else
{
System.out.println("error: Attempting to put student in a string in table list gui");
}
}
else if(aValue instanceof String)
{
System.out.println("error: Attempting to change teacher name in tablelist gui");
}
else
{
System.out.println("error: Attempting to set unknown object type in tablelist gui");
}
}
}
////****************////
JTable tableTable= new JTable(new DinnerTableModel(tables));
for(int hihihi=0;hihihi<tableTable.getColumnCount();hihihi++)
{
tableTable.getColumnModel().getColumn(hihihi).setCellRenderer(new DinnerTableCellRenderer());
}
JScrollPane scrollpaneB1= new JScrollPane();
scrollpaneB1.add(tableTable);
panelB.add(scrollpaneB1);
I am new to programming and have a lot of questions. It is very nice of you to be so patient! : ) However, I have another JTable that intakes another TableModel class. I ran tests and it seems that the model does change whenever the original objects change, even though I didn't use any propertychangelisteners. This is very confusing to me...
JTable is among one of the more complex components in the API (JTree and text components been the next), if you can become comfortable with it, you will be a long way to becoming comfortable with the overall API.
There are any number of ways you could notify the TableModel that an object has changed, but one of the best ways is to do it in a decoupled way, so you don't have to maintain a reference to the TableModel every where the Student object might change.
This suggests that the Student object itself should generate some kind of change event, which interested parties (like the TabelModel) can listen for and take action when they occur.
In this way, you can change the Student object anywhere in your code without caring about who might need to know that the object has changed.
Now, this basically boils down to an observer pattern, Swing implements this kind of functionality in it's listeners, ChangeListener springs to mind as a possible candidest, but PropertyChangeListener is a more powerful option, as it generates events based on the property that has changed.
In some cases, you probably won't care what property has changed, but in the case of TableModel, it's very useful.
This is a simple demonstration of the concept, using two tables. You can edit any value in either table and the opposing table will be updated when the value is committed. Now, you could also modify the instance of Student in your code and you'd get the same result, but this was a simple example to create.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Student student = new Student("Skywalker", "Luke", 0, true, true);
StudentTabelModel leftModel = new StudentTabelModel(student);
StudentTabelModel rightModel = new StudentTabelModel(student);
JTable leftTable = new JTable(leftModel);
leftTable.setGridColor(Color.GRAY);
JTable rightTable = new JTable(rightModel);
rightTable.setGridColor(Color.GRAY);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2));
frame.add(new JScrollPane(leftTable));
frame.add(new JScrollPane(rightTable));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class StudentTabelModel extends AbstractTableModel {
private List<Student> students = new ArrayList<>(25);
private PropertyChangeListener propertyChangeListener;
public StudentTabelModel(Student... students) {
propertyChangeListener = new StudentPropertyChangeListener();
add(students);
}
public void add(Student... students) {
if (students != null && students.length > 0) {
int startRow = this.students.size();
for (Student student : students) {
student.addPropertyChangeListener(propertyChangeListener);
this.students.add(student);
}
fireTableRowsInserted(startRow, this.students.size() - 1);
}
}
public void remove(Student ...students) {
if (students != null && students.length > 0) {
for (Student student : students) {
int index = this.students.indexOf(student);
if (index != -1) {
student.removePropertyChangeListener(propertyChangeListener);
this.students.remove(student);
fireTableRowsDeleted(index, index);
}
}
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
#Override
public int getRowCount() {
return students.size();
}
#Override
public int getColumnCount() {
return 6;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
case 1:
return String.class;
case 2:
case 3:
return Integer.class;
case 4:
case 5:
return Boolean.class;
}
return Object.class;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Student student = students.get(rowIndex);
switch (columnIndex) {
case 0:
return student.getLastName();
case 1:
return student.getFirstName();
case 2:
return student.getGrade();
case 3:
return student.getTable();
case 4:
return student.getGender();
case 5:
return student.getAvailable();
}
return "??";
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Student student = students.get(rowIndex);
switch (columnIndex) {
case 0:
student.setLastName(aValue == null ? null : aValue.toString());
break;
case 1:
student.setFirstName(aValue == null ? null : aValue.toString());
break;
case 2:
if (aValue instanceof Integer) {
student.setGrade((Integer) aValue);
}
break;
case 3:
if (aValue instanceof Integer) {
student.setTable((Integer) aValue);
}
break;
case 4:
if (aValue instanceof Boolean) {
student.setGender((Boolean) aValue);
}
break;
case 5:
if (aValue instanceof Boolean) {
student.setAvailable((Boolean) aValue);
}
break;
}
}
protected class StudentPropertyChangeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() instanceof Student) {
Student student = (Student) evt.getSource();
int row = students.indexOf(student);
if (row != -1) {
switch (evt.getPropertyName()) {
case "lastName":
fireTableCellUpdated(row, 0);
break;
case "firstName":
fireTableCellUpdated(row, 1);
break;
case "grade":
fireTableCellUpdated(row, 2);
break;
case "table":
fireTableCellUpdated(row, 3);
break;
case "gender":
fireTableCellUpdated(row, 4);
break;
case "avaliable":
fireTableCellUpdated(row, 5);
break;
}
}
}
}
}
}
public class Student {
private String lastName;
private String firstName;
private int grade;
private int table;
private boolean gender;//Male=true, female=false;
private boolean available; //true=available;
private PropertyChangeSupport propertyChangeSupport;
public Student() {
this("", "", 0, false, true);
}
public Student(String l, String f, int i, boolean g, boolean a) {
lastName = l;
firstName = f;
grade = i;
gender = g;
available = a;
//table is not written back to the txt.
table = 0;
propertyChangeSupport = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
//Getters
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public int getGrade() {
return grade;
}
public int getTable() {
return table;
}
public boolean getGender() {
return gender;
}
public boolean getAvailable() {
return available;
}
//Setters
public void setLastName(String s) {
String old = lastName;
this.lastName = s;
propertyChangeSupport.firePropertyChange("lastName", old, lastName);
}
public void setFirstName(String s) {
String old = firstName;
firstName = s;
propertyChangeSupport.firePropertyChange("firstName", old, firstName);
}
public void setGrade(int i) {
int old = grade;
grade = i;
propertyChangeSupport.firePropertyChange("grade", old, grade);
}
public void setTable(int hiahia) {
int old = table;
table = hiahia;
propertyChangeSupport.firePropertyChange("table", old, table);
}
public void setGender(boolean b) {
boolean old = gender;
gender = b;
propertyChangeSupport.firePropertyChange("gender", old, gender);
}
public void setAvailable(boolean b) {
boolean old = available;
available = b;
propertyChangeSupport.firePropertyChange("available", old, available);
}
//Miscellaneous
#Override
public String toString() {
String a = "";
a = lastName + "," + firstName + "," + Integer.toString(grade) + "," + Boolean.toString(gender) + "," + Boolean.toString(available);
return a;
}
}
}
Remember, this relies on the INSTANCE of the Student been shared, if you create two different instances of the Student object and expect that changes in one instance will be reflected in the other, then you will be disappointed
Related
I am developing a small application on Java. I created a custom model for jtable. The model is this:
package tienda.funcionalidad;
import java.awt.Component;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import tienda.funcionalidad.excepciones.NombreNoValidoException;
import tienda.funcionalidad.excepciones.PrecioNoValidoException;
import tienda.funcionalidad.excepciones.ProductoNoExisteException;
public class ProductTableModel extends AbstractTableModel implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
final String[] columns = { "Producto", "Serodys", "Ramírez", "Entrada", "MercaSur" };
final ArrayList registros = GestionTienda.getProductos();
#Override
public int getColumnCount() {
return columns.length;
}
#Override
public String getColumnName(int column) {
return columns[column];
}
#Override
public int getRowCount() {
if (registros.isEmpty())
return 0;
return registros.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Product product = (Product) registros.get(rowIndex);
switch (columnIndex) {
case 0:
return product.getName();
case 1:
return product.getPriceSerodys();
case 2:
return product.getPriceRamirez();
case 3:
return product.getPriceEntrada();
case 4:
return product.getPriceMercasur();
}
return null;
}
public boolean isCellEditable(int row, int col) {
return true;
}
public Class getColumnClass(int col) {
switch (col) {
case 0: // Name
return String.class;
case 1: // value
return Double.class;
case 2: // location
return Double.class;
case 3: // quantity
return Double.class;
case 4:
return Double.class;
}
return null;
}
public void setValueAt(Object value, int row, int col) {
try {
Product product = (Product) registros.get(row);
switch (col) {
case 0: // Name
product.setName(value.toString());
break;
case 1: // value
Double priceSerodys = (Double) value;
product.setPriceSerodys(priceSerodys);
break;
case 2: // location
Double priceRamirez = (Double) value;
product.setPriceRamirez(priceRamirez);
break;
case 3: // quantity
Double priceEntrada = (Double) value;
product.setPriceEntrada(priceEntrada);
break;
case 4: // quantity
Double priceMercasur = (Double) value;
product.setPriceMercasur(priceMercasur);
break;
}
} catch (NombreNoValidoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PrecioNoValidoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public Component getTableCellRendererComponent(JTable arg0, Object arg1, boolean arg2, boolean arg3, int arg4,
int arg5) {
return null;
}
}
And the class Product is this:
package tienda.funcionalidad;
import java.io.Serializable;
import tienda.funcionalidad.excepciones.NombreNoValidoException;
import tienda.funcionalidad.excepciones.PrecioNoValidoException;
public class Product implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private double priceSerodys;
private double priceRamirez;
private double priceEntrada;
private double priceMercasur;
private double priceAux = 0;
public Product(int id,String name, double priceSerodys, double priceRamirez, double priceEntrada, double priceMercasur) throws PrecioNoValidoException, NombreNoValidoException {
setName(name);
setPriceSerodys(priceSerodys);
setPriceRamirez(priceRamirez);
setPriceEntrada(priceEntrada);
setPriceMercasur(priceMercasur);
setId(id);
}
public Product(int id,String nombre) throws NombreNoValidoException {
setName(nombre);
setId(id);
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
protected void setPriceSerodys(Double priceSerodys) throws PrecioNoValidoException {
if(priceSerodys<0)
throw new PrecioNoValidoException("Debes introducir un precio superior a 0");
this.priceSerodys=priceSerodys;
}
public double getPriceSerodys() {
return priceSerodys;
}
protected void setPriceRamirez(Double priceRamirez) throws PrecioNoValidoException {
if(priceRamirez<0)
throw new PrecioNoValidoException("Debes introducir un precio superior a 0");
this.priceRamirez=priceRamirez;
}
public double getPriceRamirez() {
return priceRamirez;
}
protected void setPriceEntrada(Double priceEntrada) throws PrecioNoValidoException {
if(priceEntrada<0)
throw new PrecioNoValidoException("Debes introducir un precio superior a 0");
this.priceEntrada=priceEntrada;
}
public double getPriceEntrada() {
return priceEntrada;
}
protected void setPriceMercasur(Double priceMercasur) throws PrecioNoValidoException {
if(priceMercasur<0)
throw new PrecioNoValidoException("Debes introducir un precio superior a 0");
this.priceMercasur=priceMercasur;
}
public double getPriceMercasur() {
return priceMercasur;
}
protected void setName(String nombre) throws NombreNoValidoException {
if(nombre.equals("") || nombre==null)
throw new NombreNoValidoException("Debes introducir un nombre para el producto");
this.name=nombre;
}
public String getName() {
return name;
}
public double getPrecio() {
return priceSerodys;
}
#Override
public String toString() {
return getName();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Product other = (Product) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}
I need color the cell with the minimun value of each row with green and grey the other values. I am not idea how i have to codify the method getTableCellRendererComponent, can someone help me?
Sorry if my english is bad, i am spanish.
Thank you.
To achieve the result your are looking for, you can override the JTable prepareRenderer method.
Please refer the code below. This is just an example code and doesn't follow the java coding standard.
Left that work for you :)
JTable table = new JTable(new ProductTableModel()){
#Override
public Component prepareRenderer(TableCellRenderer renderer, int rowIndex,
int columnIndex) {
JComponent component = (JComponent) super.prepareRenderer(renderer, rowIndex, columnIndex);
int columnCount = getColumnCount();
if(columnIndex != 0){
double firstVal = Double.parseDouble(getValueAt(rowIndex, 1).toString());
for (int i = 2; i < columnCount; i++) {
Double cellValue = Double.valueOf(getValueAt(rowIndex, i).toString());
if(cellValue < firstVal ){
firstVal = cellValue;
}
}
if(firstVal == Double.valueOf(getValueAt(rowIndex, columnIndex).toString()).doubleValue()) {
component.setBackground(Color.GREEN);
} else{
component.setBackground(Color.GRAY);
}
}
return component;
}
};
I have a JTable that is used to capture user input which later will be printed upon hitting the Print button. I have an image that I would want to be the header and another one to be a footer.an image showing this can be found here. I have followed the example that I found from oracle documents here. I want it exactly the way it is done in TablePrintdemo3 here.
Allow me to post the classes here.
Here is my first class:
public class Product {
String productDescription;
Double productPrice;
//dummy properties
Integer productQuantity;
Double productTotalAmount;
public Product() {
this.productDescription = "";
this.productPrice = 0.0;
this.productTotalAmount = 0.0;
this.productQuantity = 0;
}//getters and setters here
}
The second class is a custom model as shown here:
public class ProductTableModel extends AbstractTableModel {
private final List<String> columnNames;
private final List<Product> products;
public ProductTableModel() {
String[] header = new String[] {
"Quantity",
"Description",
"Unity Price",
"Total Price"
};
this.columnNames = Arrays.asList(header);
this.products = new ArrayList<>();
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0: return Integer.class;
case 1: return String.class;
case 2: return Double.class;
case 3: return Double.class;
default: throw new ArrayIndexOutOfBoundsException(columnIndex);
}
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Product product = this.getProduct(rowIndex);
switch (columnIndex) {
case 0: return product.getProductQuantity();
case 1: return product.getProductDescription();
case 2: return product.getProductPrice();
case 3: return product.getProductTotalAmount();
default: throw new ArrayIndexOutOfBoundsException(columnIndex);
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex < 0 || columnIndex >= getColumnCount()) {
throw new ArrayIndexOutOfBoundsException(columnIndex);
} else {
Product product = this.getProduct(rowIndex);
switch (columnIndex) {
case 0: product.setProductQuantity((Integer)aValue); break;
case 1: product.setProductDescription((String)aValue); break;
case 2: product.setProductPrice((Double)aValue); break;
case 3: product.setProductTotalAmount((Double)aValue); break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
}
#Override
public int getRowCount() {
return this.products.size();
}
#Override
public int getColumnCount() {
return this.columnNames.size();
}
#Override
public String getColumnName(int columnIndex) {
return this.columnNames.get(columnIndex);
}
public void setColumnNames(List<String> columnNames) {
if (columnNames != null) {
this.columnNames.clear();
this.columnNames.addAll(columnNames);
fireTableStructureChanged();
}
}
public List<String> getColumnNames() {
return Collections.unmodifiableList(this.columnNames);
}
public void addProducts(Product product) {
int rowIndex = this.products.size();
this.products.add(product);
fireTableRowsInserted(rowIndex, rowIndex);
}
public void addProducts(List<Product> productList) {
if (!productList.isEmpty()) {
int firstRow = this.products.size();
this.products.addAll(productList);
int lastRow = this.products.size() - 1;
fireTableRowsInserted(firstRow, lastRow);
}
}
public void addEmptyRow(){
products.add(new Product());
this.fireTableRowsInserted(products.size()-1, products.size()-1);
}
public void insertProduct(Product product, int rowIndex) {
this.products.add(rowIndex, product);
fireTableRowsInserted(rowIndex, rowIndex);
}
public void deleteProduct(int rowIndex) {
if (this.products.remove(this.products.get(rowIndex))) {
fireTableRowsDeleted(rowIndex, rowIndex);
}
}
public Product getProduct(int rowIndex) {
return this.products.get(rowIndex);
}
public List<Product> getProducts() {
return Collections.unmodifiableList(this.products);
}
public void clearTableModelData() {
if (!this.products.isEmpty()) {
int lastRow = products.size() - 1;
this.products.clear();
fireTableRowsDeleted(0, lastRow);
}
}
}
The third class is my is as follows:
public class NiceTablePrinting extends MainClass{
#Override
protected JTable initializeTable(TableModel model) {
return new NicePrintingJTable(model);
}
private static class NicePrintingJTable extends JTable {
public NicePrintingJTable(TableModel model) {
super(model);
}
/**
* Overridden to return a fancier printable, that wraps the default.
* Ignores the given header and footer. Renders its own header.Always
* uses the page number as the footer.
*/
#Override
public Printable getPrintable(PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat) {
MessageFormat pageNumber = new MessageFormat("- {0} -");
/* Fetch the default printable */
Printable delegate = per.getPrintable(printMode,null,pageNumber);
/* Return a fancy printable that wraps the default */
return new NicePrintable(delegate);
}
}
private static class NicePrintable implements Printable {
Printable delegate;
//
BufferedImage header;
BufferedImage footer;
//
boolean imagesLoaded;
{
try{
header=ImageIO.read(getClass().getResource("images/header.PNG"));
footer=ImageIO.read(getClass().getResource("images/footer.PNG"));
imagesLoaded=true;
}
catch(IOException ex)
{
ex.printStackTrace();
}
imagesLoaded=false;
}
public NicePrintable(Printable delegate) {
this.delegate = delegate;
}
#Override
public int print(Graphicsg,PageFormatpf,intpi)throwsPrinterException
{
if(!imagesLoaded){
return delegate.print(g, pf, pi);
}
//top origin
int x=(int)pf.getImageableX();
int y=(int)pf.getImageableY();
//
int iw=(int)pf.getImageableWidth();
int ih=(int)pf.getImageableHeight();
//image header
int hh= header.getHeight();
int hw=header.getWidth();
//image footer
int fh=footer.getHeight();
int fw=footer.getWidth();
int fY=ih-fh-10;
int fX=x;
//calculating the area to print the table
int tableX=10;
int tableY=hh +10;
int tableW=iw-20;
int tableH=ih-hh-10-fh-10;
/* create a new page format representing the shrunken area to print the table into */
PageFormat format = new PageFormat() {
#Override
public double getImageableX() {return tableX;}
#Override
public double getImageableY() {return tableY;}
#Override
public double getImageableWidth() {return tableW;}
#Override
public double getImageableHeight() {return tableH;}
};
/*
* We'll use a copy of the graphics to print the table to. This protects
* us against changes that the delegate printable could make to the graphics
* object.
*/
Graphics gCopy = g.create();
/* print the table into the shrunken area */
int retVal = delegate.print(gCopy, format, pi);
/* if there's no pages left, return */
if (retVal == NO_SUCH_PAGE) {
return retVal;
}
/* dispose of the graphics copy */
gCopy.dispose();
//draw the images
g.drawImage(header, x, y, hw, hh, null);
g.drawImage(footer, fX, fY, fw, fh, null);
return Printable.PAGE_EXISTS;
}
}
}
The fourth class is as follows:
public class MainClass {
private JTable table;
JFrame frame;
JButton print;
JScrollPane sp;
ProductTableModel model;
public MainClass(){
frame= new JFrame("Test Printing");
frame.setLayout(new java.awt.BorderLayout());
frame.setVisible(true);
///create table
model=new ProductTableModel();
table=this.initializeTable(model);
model.addEmptyRow();
table.setPreferredScrollableViewportSize(newjava.awt.Dimension(300,300));
sp= new javax.swing.JScrollPane(table);
frame.add(sp);
//button
print= new JButton("Print");
frame.add(print,BorderLayout.SOUTH);
frame.pack();
print.addActionListener((ActionEvent e) -> {
try {
printTable();
} catch (PrinterException ex) {
Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
protected JTable initializeTable(TableModel model) {
return new JTable(model);
}
public void printTable() throws PrinterException {
table.print(JTable.PrintMode.NORMAL, null, null, true, null, true);
}
public static void main(String [] args){
MainClass cl= new MainClass();
}
}
I would want to set my things the way it is done in TablePrintdemo3. Now I cannot see where I have gone wrong. Please assist.
The problem is it is printing only the table -no header and footer images.
I have a JTable with some rows. How can i block edit row just when radiobutton unlock is selected? Below a small project to use as a working example
Update
ElencoPersoneFrame class
package test;
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class ElencoPersoneFrame extends JFrame {
private PersonaTableModel tableModel;
private JTable table;
private JScrollPane scrollPane;
JRadioButton rdbtnFilm = new JRadioButton("Editable");
JRadioButton rdbtnSerieTv = new JRadioButton("Not editable");
public ElencoPersoneFrame()
{
super ("Elenco Persone");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setSize(400, 250);
ArrayList<Persona> listaPersone = new ArrayList<Persona>();
listaPersone.add(new Persona("Mario", "Rossi", 1972, false));
listaPersone.add(new Persona("Giacomo", "Bianchi", 1946, false));
listaPersone.add(new Persona("Roberto", "Verdi", 1985, true));
tableModel = new PersonaTableModel(listaPersone);
table = new JTable(tableModel);
scrollPane = new JScrollPane(table);
JPanel rdpnl=new radioPanel();
getContentPane().add(rdpnl, BorderLayout.NORTH);
getContentPane().add(scrollPane, BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ElencoPersoneFrame f = new ElencoPersoneFrame();
f.setVisible(true);
}
});
}
}
Persona class
package test;
public class Persona
{
private String nome;
private String cognome;
private int annoNascita;
private boolean disoccupato;
/*costruttore*/
public Persona(String nome, String cognome, int annoNascita, boolean disoccupato) {
this.nome = nome;
this.cognome = cognome;
this.annoNascita = annoNascita;
this.disoccupato = disoccupato;
}
public String getNome() { return nome; }
public String getCognome() { return cognome; }
public int getAnnoNascita() { return annoNascita; }
public boolean isDisoccupato() { return disoccupato; }
public void setNome(String nome) { this.nome = nome; }
public void setCognome(String cognome) { this.cognome = cognome; }
public void setAnnoNascita(int annoNascita) { this.annoNascita = annoNascita; }
public void setDisoccupato(boolean disoccupato) { this.disoccupato = disoccupato; }
}
PersonaTableModel class
package test;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class PersonaTableModel extends AbstractTableModel
{
private ArrayList<Persona> listaPersone;
public PersonaTableModel(ArrayList<Persona> listaPersone) {
this.listaPersone = listaPersone;
}
public int getRowCount() {
return listaPersone.size();
}
public int getColumnCount() {
return 4;
}
public String getColumnName(int column) {
switch (column) {
case 0: return "Nome";
case 1: return "Cognome";
case 2: return "Anno nascita";
case 3: return "Disoccupato?";
}
return "";
}
public Class getColumnClass(int column) {
switch (column) {
case 0: return String.class;
case 1: return String.class;
case 2: return Number.class;
case 3: return Boolean.class;
}
return Object.class;
}
public boolean isCellEditable(int row, int column) {
return true;
}
public Object getValueAt(int row, int column) {
Persona p = listaPersone.get(row);
switch (column) {
case 0: return p.getNome();
case 1: return p.getCognome();
case 2: return p.getAnnoNascita();
case 3: return p.isDisoccupato();
}
return null;
}
public void setValueAt(Object value, int row, int column)
{
Persona p = listaPersone.get(row);
switch (column)
{
case 0: p.setNome((String) value); break;
case 1: p.setCognome((String) value); break;
case 2: p.setAnnoNascita((Integer) value); break;
case 3: p.setDisoccupato((Boolean) value); break;
}
}
public void aggiungiPersona(Persona p) {
listaPersone.add(p);
int row = listaPersone.size() - 1;
fireTableRowsInserted(row, row);
}
}
radioPanel class
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class radioPanel extends JPanel implements ActionListener
{
private JRadioButton unlock;
private JRadioButton lock;
private ButtonGroup rdgroup;
public radioPanel()
{
rdgroup=new ButtonGroup();
unlock = new JRadioButton("Editable");
lock = new JRadioButton("Not editable");
rdgroup.add(unlock);
rdgroup.add(lock);
rdgroup.setSelected(unlock.getModel(), true);
this.add(unlock);
this.add(lock);
lock.addActionListener(this);
unlock.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == this.lock)
{
}
if(e.getSource() == this.unlock)
{
}
}
}
So there doesn't seem to be (AFAIK) some magic method to set the table uneditable. What you can do though is create a method in your model, like setEditable(boolean), where you can set a class member boolean editable. Use the same field for isCellEditable. After you change the state, you should fire the table change. Something like
class PersonaTableModel extends AbstractTableModel {
...
private boolean editable = true;
public boolean isEditable() {
return editable;
}
public boolean isCellEditable(int row, int column) {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
fireTableDataChanged();
}
...
}
You'll also need to way for the ActionListener to get hold of the table model. So you can refactor your radio panel to something like
class radioPanel extends JPanel {
private JRadioButton unlock;
private JRadioButton lock;
private ButtonGroup rdgroup;
...
public ButtonGroup getButtonGroup() {
return rdgroup;
}
public AbstractButton getUnlock() {
return unlock;
}
public AbstractButton getLock() {
return lock;
}
}
This way you can just get the radio buttons from anywhere and add the ActionListener. So you can change you main class code to something like:
radioPanel rdpnl = new radioPanel();
rdpnl.getUnlock().addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tableModel.setEditable(true);
}
});
rdpnl.getLock().addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tableModel.setEditable(false);
}
});
getContentPane().add(rdpnl, BorderLayout.NORTH);
Tested, and seems to work as expected.
Aside: Please make note of Java naming convention. Class names should begin with upper case letters i.e. radioPanel → RadioPanel
You need to implement the isCellEditable method for your TableModel:
public boolean isCellEditable(int row, int col)
return false;
See also the tutorials.
My problem is:
I have a button that will add components to a JList when it is clicked. Each row of the list is composed by two jtextFields. The first is the ID of the row. Every time I press the "Add button", a new row appears, the ID is incremented, and the person who is using the application will write whatever he want on the second jTextField (forward the ID field).
Then it will have a scroll pane for when there are more than 4 rows.
And I want a Remove Button too. To be possible to remove some rows.
Can you help me with this? I don't know how to create a list like this...
Thanks!
Simply use JTable with two columns. This will allow you to establish two columns, one for the ID and one for the value. This will allow you make the second column editable.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class TestTable04 {
public static void main(String[] args) {
new TestTable04();
}
private int id = 0;
public TestTable04() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final RecordTableModel model = new RecordTableModel();
JTable table = new JTable(model);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.add(new Record(++id));
}
});
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(add, BorderLayout.SOUTH);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Record {
private int id;
private String value;
public Record(int id) {
this.id = id;
}
public int getID() {
return id;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class RecordTableModel extends AbstractTableModel {
private List<Record> lstRecords;
public RecordTableModel() {
lstRecords = new ArrayList<>(24);
}
public void add(Record record) {
lstRecords.add(record);
fireTableRowsInserted(lstRecords.size() - 1, lstRecords.size() - 1);
}
public void remove(Record record) {
if (lstRecords.contains(record)) {
int index = lstRecords.indexOf(record);
remove(index);
}
}
public void remove(int index) {
lstRecords.remove(index);
fireTableRowsDeleted(index, index);
}
#Override
public int getRowCount() {
return lstRecords.size();
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 0:
clazz = Integer.class;
break;
}
return clazz;
}
#Override
public String getColumnName(int column) {
String name = null;
switch (column) {
case 0:
name = "ID";
break;
case 1:
name = "Value";
break;
}
return name;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Record record = lstRecords.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = record.getID();
break;
case 1:
value = record.getValue();
break;
}
return value;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 1;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Record record = lstRecords.get(rowIndex);
switch (columnIndex) {
case 1:
record.setValue(aValue == null ? null : aValue.toString());
fireTableCellUpdated(rowIndex, columnIndex);
break;
}
}
}
}
Check out How to use tables for more details
You can try creating a custom ListCellRenderer and use JList's setRenderer method to assign it. Override the getListCellRenderer() method of ListCellRenderer to return a JPanel containing two components, a JLabel for the id, and a JTextfield for the user input. You may need to keep a reference to the JTextField elsewhere so that you can retrieve the user input.
To implement the add and remove methods, I would recommend backing the JList with a ListModel. Add and remove to the ListModel will also update the JList UI.
I have a jtable that show a text file contain on own.
Each line in text file is a user record.
I add a edit button to edit each selected row on table.
I use this code, But i don't understand how to do this:
public class AllUser extends AbstractTableModel {
UserInformation uiS = new UserInformation();
String[] col = {"ID", "Fname", "Lname", "Gender", "Date"};
List<UserInformation> Udata = new ArrayList<UserInformation>();
public AllUser() {
BufferedReader br = null;
try {
FileReader fr = new FileReader("xxx.txt");
br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
if (line.trim().length() == 0) {
continue;
}
Udata.add(initializeUserInfos(line));
}
} catch (IOException e) {
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ioe) {
}
}
}
}
private UserInformation initializeUserInfos(String str) {
UserInformation Uinit = new UserInformation();
String[] CellArray = str.split(" ");
Uinit.setID(CellArray[0]);
Uinit.setFname(CellArray[1]);
Uinit.setLname(CellArray[2]);
Uinit.setGender(CellArray[3]);
Uinit.setDate(CellArray[4]);
return Uinit;
}
#Override
public String getColumnName(int colu) {
return col[colu];
}
#Override
public int getRowCount() {
return Udata.size();
}
#Override
public int getColumnCount() {
return col.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
UserInformation uinfoS = Udata.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = uinfoS.getID();
break;
case 1:
value = uinfoS.getFname();
break;
case 2:
value = uinfoS.getLname();
break;
case 3:
value = uinfoS.getGender();
break;
case 4:
value = uinfoS.getDate();
break;
default:
value = "...";
}
return value;
}
#Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
UserInformation userInfo = new UserInformation();
switch (columnIndex) {
case 0:
userInfo.setID((String) value);
break;
case 1:
userInfo.setFname((String) value);
break;
case 2:
userInfo.setLname((String) value);
break;
case 3:
userInfo.setGender((String) value);
break;
case 4:
userInfo.setDate((String) value);
break;
}
}
public Object getSelectedMember(int row){
UserInformation userInf=new UserInformation();
Object fname=userInf.getFname();
Object lname=userInf.getLname();
Object gender=userInf.getGender();
Object date=userInf.getDate();
return // ?
}
}
I add This getSelectedMember(int row) method to do this, But incorrect!
public class UserPage extends JFrame implements ActionListener {
private AllUser userModel;
private JTable uTable;
private JButton editButton;
public UserPage() {
userModel = new AllUser();
uTable = new JTable(userModel);
add(new JScrollPane(uTable), BorderLayout.CENTER);
add(buttonPanels(), BorderLayout.PAGE_START);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800, 600);
}
public final JPanel buttonPanels() {
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
editButton=new JButton("Edit");
editButton.addActionListener(this);
buttonsPanel.add(editButton);
return buttonsPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()== editButton){
int selectedRow=uTable.getSelectedRow();
if(selectedRow>0){
editUser(selectedRow);
}
else{
JOptionPane.showMessageDialog(null, "Select a user");
}
}
}
public void editUser(int row){
userModel.getSelectedMember(row);
new NewUserFrame_Edit().setVisible(true);
}
}
UserInformation Class:
public class UserInformation {
private String Fname;
private String Lname;
private String ID;
private String Gender;
private String Date;
public String getFname() {
return Fname;
}
public void setFname(String fname) {
this.Fname = fname;
}
public String getLname() {
return Lname;
}
public void setLname(String lname) {
this.Lname = lname;
}
public String getID() {
return ID;
}
public void setID(String i_d) {
this.ID = i_d;
}
public String getGender() {
return Gender;
}
public void setGender(String gndr) {
this.Gender = gndr;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
this.Date = date;
}
#Override
public String toString() {
return ID + " " + Fname + " "
+ Lname + " " + Gender + " " + Date + "\n";
}
}
Sorry for long code.
It sould be like this: when user click a row in jtable and clicked a new page should open and then each old data should insert in own textfiled
Add a MouseListener to the table.
On a double click you create a JDialog that contains the text fields required to edit the data.
You then get the data from the table using the getValueAt(...) method.
the user then edits the data in the text fields.
When the user clicks the "Save" button on the dialog you get the data from each text field and update the table using the setValueAt(...) method.
if you want to save the data in your text file you then need to recreate the enitre file by writing out all the data from the table.
Create an extra column in table and fill the cell value with Edit. Then render the Edit cell with appropriate TableCellRenderer . Add MouseListener to table. Get the row and column number of the cell clicked on table. If the cell clicked contains value Edit , retrieve value at each column of that row and display it in a Panel containing JTextFields . Show that Panel using JOptionpane or in a JDialog. Here is the brief code demo for achieving this task:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Component;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.awt.Cursor;
import javax.swing.BorderFactory;
import javax.swing.border.BevelBorder;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.DefaultTableCellRenderer;
class TableRowEdit extends JFrame
{
private JTable table;
private JScrollPane jsPane;
private TableModel myModel;
private JPanel dialogPanel;
private JTextField tf[];
private JLabel lbl[];
public void prepareAndShowGUI()
{
myModel = new MyModel();
table = new JTable(myModel);
jsPane = new JScrollPane(table);
table.getColumnModel().getColumn(2).setCellRenderer(new LabelCellRenderer());
table.addMouseListener(new MyMouseAdapter());
getContentPane().add(jsPane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prepareDialogPanel();
pack();
setVisible(true);
}
private void prepareDialogPanel()
{
dialogPanel = new JPanel();
int col = table.getColumnCount() - 1;
dialogPanel.setLayout(new GridLayout(col,2));
tf = new JTextField[col];
lbl = new JLabel[col];
for (int i = 0; i < col; i++)
{
lbl[i] = new JLabel(table.getColumnName(i));
tf[i] = new JTextField(10);
dialogPanel.add(lbl[i]);
dialogPanel.add(tf[i]);
}
}
private void populateTextField(String[] s)
{
for (int i = 0 ; i < s.length ; i++ )
{
tf[i].setText(s[i]);
}
}
public class LabelCellRenderer extends DefaultTableCellRenderer
{
public Component getTableCellRendererComponent(JTable table,Object oValue, boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, oValue,isSelected, hasFocus,row, column);
String value = (String)oValue;
JLabel label =(JLabel)c;
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
label.setBackground(Color.lightGray);
label.setHorizontalTextPosition(SwingUtilities.CENTER);
label.setHorizontalAlignment(SwingUtilities.CENTER);
label.setText(value);
return label;
}
}
private class MyMouseAdapter extends MouseAdapter
{
#Override
public void mousePressed(MouseEvent evt)
{
int x = evt.getX();
int y = evt.getY();
int row = table.rowAtPoint(new Point(x,y));
int col = table.columnAtPoint(new Point(x,y));
if (col == 2)
{
String arr[] = new String[table.getColumnCount() - 1];
for (int i = 0 ; i < arr.length ; i++)
{
arr[i] = (String)table.getValueAt(row,i);
}
populateTextField(arr);
JOptionPane.showMessageDialog(TableRowEdit.this,dialogPanel,"Information",JOptionPane.INFORMATION_MESSAGE);
//Write here the code to save changed values to file and update to JTable also.
}
}
}
private class MyModel extends AbstractTableModel
{
String[] columns = {
"Roll No.",
"Name",
"Action"
};
String[][] inData = {
{"1","Huge Jackman","Edit"},
{"2","Thomas Andrews","Edit"},
{"3","Shiney","Edit"}
};
#Override
public void setValueAt(Object value, int row, int col)
{
inData[row][col] = (String)value;
}
#Override
public Object getValueAt(int row, int col)
{
return inData[row][col];
}
#Override
public int getColumnCount()
{
return columns.length;
}
#Override
public int getRowCount()
{
return inData.length;
}
#Override
public String getColumnName(int col)
{
return columns[col];
}
}
public static void main(String st[])
{
SwingUtilities.invokeLater( new Runnable()
{
#Override
public void run()
{
TableRowEdit td = new TableRowEdit();
td.prepareAndShowGUI();
}
});
}
}