setValueAt(...) jtable from combobox.selectedItem throws .ArrayIndexOutOfBoundsException: -1 - java

i have a panel that contains labels and textfields to complete with order infromations and an empty jtable so when i click over add button an empty row will be added in the jtable that contains a comboBox with articles references thats meen when i select an item in the combbox the second and the third column will be loaded with article name and price using setvalueAt method in DefaultTableModel.
My problem is when i choose a reference in the comboBox it throws ArrayIndexOutOfBoundsException: -1 at the setValueAt line, so can any one please here help me !??
this is my code :
package vues.panel;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Date;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerDateModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import model.ArticleTableModel;
import model.beans.Article;
import model.beans.Commande;
import model.persistence.PersistentArticle;
public class CommandePanel extends JPanel {
private static final long serialVersionUID = 1L;
private JLabel lblIdCmd, lblDate, lblClient, lblTotal;
private JTextField tfIdCmd, tfClient, tfTotal;
private JSpinner spnDateCmd;
private JButton btAdd, btDelete, btSave;
private JScrollPane scp;
private JTable tab;
private TableColumn refColumn;
private JComboBox<Integer> comboBox;
private ArticleCommandeTableModel cmdArtModel;
public CommandePanel(){
setLayout(null);
initComponents();
remplirComboBox();
setActions();
setVisible(true);
}
public void initComponents(){
lblIdCmd = new JLabel("Id Commande : ");
tfIdCmd = new JTextField(12);
lblDate = new JLabel("Date Commande : ");
spnDateCmd = new JSpinner(new SpinnerDateModel());
spnDateCmd.setValue(Calendar.getInstance().getTime());
spnDateCmd.setEditor(new JSpinner.DateEditor(spnDateCmd,"dd/MM/yyyy hh:mm"));
lblClient = new JLabel("Client : ");
tfClient = new JTextField(12);
btAdd = new JButton("Ajouter Article");
btDelete = new JButton("Supprimer Article");
tab=new JTable();
tab.setModel(cmdArtModel= new ArticleCommandeTableModel());
tab.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
refColumn = tab.getColumnModel().getColumn(0);
scp =new JScrollPane(tab);
tab = new JTable();
comboBox = new JComboBox<>();
lblTotal = new JLabel("Total : ");
lblTotal.setFont(new Font("Verdana", Font.BOLD, 14));
tfTotal = new JTextField(12);
btSave = new JButton("Sauvegarder Commande");
lblIdCmd.setBounds(50, 15, 300, 25);
tfIdCmd.setBounds(220, 20, 146, 22);
lblDate.setBounds(50, 45, 300, 25);
spnDateCmd.setBounds(220, 50, 146, 22);
lblClient.setBounds(50, 75, 300, 25);
tfClient.setBounds(220, 80, 146, 22);
btAdd.setBounds(30, 145, 150, 25);
btDelete.setBounds(240, 145, 150, 25);
scp.setBounds(20, 200, 550, 300);
lblTotal.setBounds(375, 515, 300, 25);
tfTotal.setBounds(440, 515, 130, 25);
btSave.setBounds(175, 560, 200, 25);
add(lblIdCmd);
add(tfIdCmd);
add(lblDate);
add(spnDateCmd);
add(lblClient);
add(tfClient);
add(btAdd);
add(btDelete);
add(scp);
add(lblTotal);
add(tfTotal);
add(btSave);
}
public void setActions(){
btAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
chargerTab();
cmdArtModel.setRowCount(ArticleCommandeTableModel.rowCount++);
}
});
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(comboBox.getSelectedItem()!=null && comboBox.getSelectedIndex()>=0){
int ref = Integer.valueOf(comboBox.getSelectedItem().toString());
tab.setValueAt(ref, tab.getSelectedRow(), tab.getSelectedColumn());
}
}
});
}
public Commande getCommandeFromView(){
Commande c = new Commande();
c.setIdComande(Integer.valueOf(tfIdCmd.getText()));
c.setDateCmd(Date.valueOf(spnDateCmd.getValue().toString()));
c.setClient(tfClient.getText());
return c;
}
public void chargerTab(){
refColumn.setCellEditor(new DefaultCellEditor(comboBox));
//ArticleCommandeTableModel.count=cmdArtModel.getRowCount()+1;
cmdArtModel.addRow(new Vector<>());
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
refColumn.setCellRenderer(renderer);
}
public void remplirComboBox(){
List<Article> l;
try {
l = PersistentArticle.getArticles();
for(int i= 0;i<l.size();i++){
comboBox.addItem(l.get(i).getRef());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void remplirLibPu(int ref){
//tab.setValueAt(arg0, arg1, arg2)
}
}
class ArticleCommandeTableModel extends DefaultTableModel{
private static final long serialVersionUID = 1L;
String[] title ={"Ref Article", "Libelle", "PU", "Qté", "Total"};
Object[][] data;
static int rowCount =0;
public ArticleCommandeTableModel(){ }
public int getColumnCount(){
return 5;
}
// public int getRowCount(){
// if(data==null) return 0;
// return data.length;
// }
public String getColumnName(int col){
return title[col];
}
public boolean isCellEditable(int row, int col){
if(col==0||col==3)return true;
return false;
}
#Override
public void setValueAt(Object value, int row, int col) {
int ref = (Integer)value;
Article a=ArticleTableModel.getArticleByRef(ref);
if(col==0){
super.setValueAt(a.getLibelle(), row, 1);
super.setValueAt(a.getPu(), row, 2);
}
else{
super.setValueAt(value, row, col);
}
fireTableDataChanged();
}
#Override
public Object getValueAt(int row, int column) {
return super.getValueAt(row, column);
}
#Override
public void addRow(Vector rowData) {
super.addRow(rowData);
}
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected , boolean hasFocus, int row, int column) {
if(value instanceof JComboBox){
return (JComboBox) value;
}
else{
return null;
}
}
}

Related

Can't update JComboBox in JTable when value is selected

I would like to have a JTable with JComboBoxes that is always visible. My problem is when I click on a JComboBox and select a value, my JComboBox is not updated.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class trial extends JFrame {
private ArrayList<JComboBox> comboslist= new ArrayList <JComboBox>();/*list of my
comboboxes*/
public static void main(String[] args) {
trial tr= new trial();
}
public trial(){
this.setSize(new Dimension(600,100));
String[] ColData={"Index","Field Name","Value","Range"};
Object[][] TrowData={ };
DefaultTableModel model = new DefaultTableModel(TrowData, ColData);
final List<TableCellEditor> editors = new ArrayList<TableCellEditor>();
JComboBox combo1= new JComboBox();
combo1.addItem("don");
combo1.addItem("mump");
combo1.setEditable(true);
combo1.setBackground(Color.WHITE);
Object[] rowdata = {"cars","books","chicken","soup"};
model.addRow(rowdata);
DefaultCellEditor dce1 = new DefaultCellEditor(combo1);
editors.add(dce1);
JComboBox combo2= new JComboBox();
combo2.addItem("sop");
combo2.addItem("act");
combo2.setEditable(true);
combo2.setBackground(Color.WHITE);
Object[] rowdata2 = {"goats","cats","salads","dogs"};
model.addRow(rowdata2);
DefaultCellEditor dce2= new DefaultCellEditor(combo2);
editors.add(dce2);
comboslist.add(combo1);
comboslist.add(combo2);
JTable table = new JTable(model)
{
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
if (modelColumn == 2)
return editors.get(row);
else
return super.getCellEditor(row, column);
}
};
table.setRowHeight(0, 30);
table.setRowHeight(1, 30);
table.setPreferredScrollableViewportSize(new Dimension(800, 150));
table.setFillsViewportHeight(true);
TableColumn valCol= table.getColumnModel().getColumn(2);
int x=0;
for(JComboBox cb: comboslist ){
valCol.setCellRenderer(new ComboBoxCellRenderer(cb,x++));
}
this.add(table);
this.setVisible(true);
}
private class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer {
private JComboBox combo;
private int idx=0;
private ComboBoxCellRenderer comboRenderer;
public ComboBoxCellRenderer(JComboBox com,int ind)
{
for (int i = 0; i < com.getItemCount(); i++)
{
addItem(com.getItemAt(i));
}
comboRenderer=this;
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(comboslist.get(row).getSelectedItem()!=null)
{
if(isSelected && row==idx)
{
setSelectedItem(comboslist.get(row).getSelectedItem().toString());
comboRenderer.setSelectedItem(comboslist.get(row).getSelectedItem().toString());
}
}else
{
setSelectedItem(value);
}
return this;
}
}
}
You've kinda got in backwards and twisted around. Instead of trying to have a number of combobox editors, you should have one, which is then configured based on the row.
Based on this idea, you could have a single class act as both the renderer and the editor, for example
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractCellEditor;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
public class Trial extends JFrame {
public static void main(String[] args) {
Trial tr = new Trial();
}
public Trial() {
this.setSize(new Dimension(600, 100));
String[] ColData = {"Index", "Field Name", "Value", "Range"};
Object[][] TrowData = {};
DefaultTableModel model = new DefaultTableModel(TrowData, ColData);
final List<TableCellEditor> editors = new ArrayList<TableCellEditor>();
model.addRow(new String[] {"cars", "books", "chicken", "soup"});
model.addRow(new String[] {"goats", "cats", "salads", "dogs"});
DefaultComboBoxModel model1 = new DefaultComboBoxModel();
model1.addElement("don");
model1.addElement("mump");
DefaultComboBoxModel model2 = new DefaultComboBoxModel();
model2.addElement("sop");
model2.addElement("act");
Map<Integer, ComboBoxModel<String>> models = new HashMap<>(2);
models.put(0, model1);
models.put(1, model2);
JTable table = new JTable(model);
table.setRowHeight(0, 30);
table.setRowHeight(1, 30);
table.setPreferredScrollableViewportSize(new Dimension(800, 150));
table.setFillsViewportHeight(true);
ComboBoxCellRendererEditor rendererEditor = new ComboBoxCellRendererEditor(models);
table.getColumnModel().getColumn(1).setCellRenderer(rendererEditor);
table.getColumnModel().getColumn(1).setCellEditor(rendererEditor);
this.add(table);
this.setVisible(true);
}
private static class ComboBoxCellRendererEditor extends AbstractCellEditor implements TableCellRenderer, TableCellEditor {
private JComboBox<String> comboBox;
private Map<Integer, ComboBoxModel<String>> models;
public ComboBoxCellRendererEditor(Map<Integer, ComboBoxModel<String>> models) {
comboBox = new JComboBox<>();
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stopCellEditing();
}
});
this.models = models;
}
protected void configure(Object value, int row) {
ComboBoxModel<String> model = models.get(row);
if (model == null) {
model = new DefaultComboBoxModel<>();
}
comboBox.setModel(model);
comboBox.setSelectedItem(value);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
configure(value, row);
return comboBox;
}
#Override
public Object getCellEditorValue() {
return comboBox.getSelectedItem();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
configure(value, row);
return comboBox;
}
}
}
adding this piece of code solved everything.
column.setCellRenderer(new TableCellRenderer() {
JComboBox box = new JComboBox();
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
box.removeAllItems();
box.addItem(value.toString());
return box;
}
});

JComboBox custom ListCellRenderer

I've a problem with JComboBox custom ListCellRenderer. I want to create a combobox that let choose between 4 colors. I want the combobox shows the color by a "list" of JPanel with desired color a background. I manage to obtain quite what I want, the only problem is that when I click on item, this change color to grey not displaying anymore the original color.
Here the code:
package custom_renderer_combobox;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.JComboBox;
public class gui extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private Color[] colors={Color.BLACK,Color.blue,Color.cyan,Color.GRAY,Color.green,Color.MAGENTA,Color.ORANGE,Color.RED};
gui(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(new Dimension(400,400));
getContentPane().setLayout(null);
JComboBox<JPanel> comboBox = new JComboBox<JPanel>();
comboBox.setRenderer(new myRenderer());
comboBox.setBounds(36, 59, 211, 20);
getContentPane().add(comboBox);
for(int i=0;i<colors.length;i++){
JPanel temp=new JPanel();
temp.setOpaque(true);
temp.setBackground(colors[i]);
comboBox.addItem(temp);
}
comboBox.repaint();
}
class myRenderer implements ListCellRenderer{
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
return ((JPanel) value);
}
}
}
Here some pic:
image
I think that the problem is in the custom renderer, can someone tell me what would I had to do?
Here is an example for you, how to use renderers and combo boxes
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
/**
* <code>ColorTest</code>.
*/
public class ColorTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ColorTest();
}
});
}
/**
*
*/
public ColorTest() {
JFrame frm = new JFrame("Test");
final JComboBox<ColorData> cmb = new JComboBox<>(ColorData.values());
cmb.setRenderer(new ColorRenderer());
final JPanel p = new JPanel();
p.setOpaque(true);
p.setPreferredSize(new Dimension(200, 100));
ActionListener l = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ColorData cd = (ColorData) cmb.getSelectedItem();
if (cd != null) {
p.setBackground(cd.getColor());
}
}
};
cmb.addActionListener(l);
l.actionPerformed(null); // update current background
frm.add(cmb, BorderLayout.NORTH);
frm.add(p);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private static class ColorRenderer extends BasicComboBoxRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof ColorData) {
BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.createGraphics();
g.setColor(((ColorData) value).getColor());
g.fillRect(0, 0, 15, 15);
g.dispose();
setIcon(new ImageIcon(img));
}
return this;
}
}
private static enum ColorData {
BLACK("Black", Color.BLACK),
BLUE("Blue", Color.BLUE),
GREEN("Green", Color.GREEN),
RED("Red", Color.RED);
private String name;
private Color color;
private ColorData(String aName, Color aColor) {
name = aName;
color = aColor;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
#Override
public String toString() {
return getName();
}
}
}
To add some new colors, you need to add the appropriate constants to the ColorData enum.
to make it a little bit quicker you can create your own JPanel that will take background color in constructor, and will block changing background:
public class ColorPanel extends JPanel {
public ColorPanel(Color color) {
super.setBackground(color);
}
#Override
public void setBackground(Color bg) {
//blocked changing
}
}
and in your code you have to change
JPanel temp = new ColorPanel(colors[i]);
temp.setOpaque(true);
comboBox.addItem(temp);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
class ComboTableCellRenderer implements ListCellRenderer, TableCellRenderer {
DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();
DefaultTableCellRenderer tableRenderer = new DefaultTableCellRenderer();
private void configureRenderer(JLabel renderer, Object value) {
if ((value != null) && (value instanceof Color)) {
if (value.equals(Color.red)) {
renderer.setText("0");
} else if(value.equals(Color.orange)) {
renderer.setText("10");
}
else if(value.equals(Color.yellow)) {
renderer.setText("20");
}
else if(value.equals(Color.green)) {
renderer.setText("30");
}
else if(value.equals(Color.white)) {
renderer.setText("N/A");
}
renderer.setBackground((Color)value);
} else {
renderer.setText((String) value);
}
}
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
listRenderer = (DefaultListCellRenderer) listRenderer.getListCellRendererComponent(list, value,
index, isSelected, cellHasFocus);
configureRenderer(listRenderer, value);
return listRenderer;
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
tableRenderer = (DefaultTableCellRenderer) tableRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
configureRenderer(tableRenderer, value);
return tableRenderer;
}
}
class ColorTableModel extends AbstractTableModel {
Object rowData[][] = {
{ "1","","","", Color.red, "30" },
{ "2","","","", Color.red, "30" },
{ "3","","","", Color.red, "30" },
{ "4","","","", Color.red, "30" },
{ "5","","","", Color.red, "30" }, };
String columnNames[] = { "Index","Item","Reason","Image","Marks","Allocated Marks" };
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return rowData.length;
}
public Object getValueAt(int row, int column) {
return rowData[row][column];
}
public Class getColumnClass(int column) {
return (getValueAt(0, column).getClass());
}
public void setValueAt(Object value, int row, int column) {
rowData[row][column] = value;
}
public boolean isCellEditable(int row, int column) {
return (column != 0);
}
}``
Main.java
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
Color choices[] = { Color.red, Color.yellow, Color.green, Color.white, Color.orange };
ComboTableCellRenderer renderer = new ComboTableCellRenderer();
JComboBox comboBox = new JComboBox(choices);
comboBox.setRenderer(renderer);
TableCellEditor editor = new DefaultCellEditor(comboBox);
JFrame frame = new JFrame("Editable Color Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableModel model = new ColorTableModel();
JTable table = new JTable(model);
TableColumn column = table.getColumnModel().getColumn(4);
column.setCellRenderer(renderer);
column.setCellEditor(editor);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
This code for jtable jcombobox color change according to value change.
This is working 100%
Hope it will work for you!

Get all column values from all JTable (ex: three tables)

Am struggling to get it working, have three tables trying to get all column values from all JTable(s) (Three tables) by clicking button "Read All Values".
When I use Vector data = tableModel.getDataVector();, returns only all columns values of the last table initiated.
Please give me directions, Thanks.
CODE:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class readAllJTableItem {
private JFrame frame;
private static JTextArea textAreaSD;
private static JTextArea textAreaPI;
private static JTextArea textAreaVL;
private TitledBorder textAreaTitleBorder = new TitledBorder(new EtchedBorder(), "Item(s)");
private static JCheckBox checkBoxTypeOne;
private static JCheckBox checkBoxTypeTwo;
private static JCheckBox checkBoxTypeThree;
//Table items
private JScrollPane scrollTableSD;
private JScrollPane scrollTablePI;
private JScrollPane scrollTableVL;
private JTable itemsTableSD;
private JTable itemsTablePI;
private JTable itemsTableVL;
private DefaultTableModel tableModel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
readAllJTableItem window = new readAllJTableItem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public readAllJTableItem() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 872, 587);
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ArrayList<String> addItems = new ArrayList<String>();
final int stedCntLpt_1[] = {0,1,2,3,4,5,6,7,8,9,10,11}; //total = 12
final int stedCntLpt_2[] = {0,1,2,3,4,5,6,7,8,9,10,12,13}; //total = 13
final int stedCntLpt_3[] = {0,1,3,7,14,15,16,17}; //total = 8
//Type-1 (0-11)
addItems.add(0, "Column-01"); addItems.add(1, "Column-02"); addItems.add(2, "Column-03"); addItems.add(3, "Column-04");
addItems.add(4, "Column-05"); addItems.add(5, "Column-06"); addItems.add(6, "Column-07"); addItems.add(7, "Column-08");
addItems.add(8, "Column-09"); addItems.add(9, "Column-10"); addItems.add(10, "Column-11"); addItems.add(11, "Column-12");
addItems.add(12, "Column-13"); addItems.add(13, "Column-14");
addItems.add(14, "Column-15"); addItems.add(15, "Column-16"); addItems.add(16, "Column-17"); addItems.add(17, "Column-18");
//1
JButton btnNewButton_1 = new JButton("Read All Values");
btnNewButton_1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//if (checkBoxTypeOne.isSelected() == true){
//This is were you get the cell values of each JTable
//#camickr's code...
DefaultTableModel model1 = (DefaultTableModel)itemsTableSD.getModel();
Vector data1 = model1.getDataVector();
System.out.println(data1.toString());
//}
}
});
btnNewButton_1.setBounds(281, 487, 125, 23);
frame.getContentPane().add(btnNewButton_1);
checkBoxTypeOne = new JCheckBox("SD");
checkBoxTypeOne.setBounds(685, 196, 87, 23);
frame.getContentPane().add(checkBoxTypeOne);
checkBoxTypeOne.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
callRenderTable(textAreaSD, scrollTableSD, itemsTableSD, addItems, stedCntLpt_1, 3, 12);
} else {
textAreaSD.setVisible(true);
scrollTableSD.setVisible(false);
};
}
});
checkBoxTypeTwo = new JCheckBox("PI");
checkBoxTypeTwo.setBounds(682, 288, 44, 23);
frame.getContentPane().add(checkBoxTypeTwo);
checkBoxTypeTwo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
callRenderTable(textAreaPI, scrollTablePI, itemsTablePI, addItems, stedCntLpt_2, 4, 13);
} else {
textAreaPI.setVisible(true);
scrollTablePI.setVisible(false);
};
}
});
checkBoxTypeThree = new JCheckBox("VL");
checkBoxTypeThree.setBounds(685, 374, 55, 23);
frame.getContentPane().add(checkBoxTypeThree);
checkBoxTypeThree.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
callRenderTable(textAreaVL, scrollTableVL, itemsTableVL, addItems, stedCntLpt_3, 2, 8);
} else {
textAreaVL.setVisible(true);
scrollTableVL.setVisible(false);
};
}
});
textAreaSD = new JTextArea();
textAreaSD.setBounds(43, 166, 608, 87);
textAreaSD.setBorder(textAreaTitleBorder);
textAreaSD.setBackground(new Color(240,240,240));
textAreaSD.setEditable(false);
textAreaSD.setVisible(true);
frame.getContentPane().add(textAreaSD);
scrollTableSD = new JScrollPane();
scrollTableSD.setBounds(43, 166, 608, 87);
scrollTableSD.setVisible(false);
frame.getContentPane().add(scrollTableSD);
textAreaPI = new JTextArea();
textAreaPI.setBounds(43, 256, 608, 103);
textAreaPI.setBorder(textAreaTitleBorder);
textAreaPI.setBackground(new Color(240,240,240));
textAreaPI.setEditable(false);
textAreaPI.setVisible(true);
frame.getContentPane().add(textAreaPI);
scrollTablePI = new JScrollPane();
scrollTablePI.setBounds(43, 256, 608, 103);
scrollTablePI.setVisible(false);
frame.getContentPane().add(scrollTablePI);
textAreaVL = new JTextArea();
textAreaVL.setBounds(43, 362, 608, 71);
textAreaVL.setBorder(textAreaTitleBorder);
textAreaVL.setBackground(new Color(240,240,240));
textAreaVL.setEditable(false);
textAreaVL.setVisible(true);
frame.getContentPane().add(textAreaVL);
scrollTableVL = new JScrollPane();
scrollTableVL.setBounds(43, 362, 608, 71);
scrollTableVL.setVisible(false);
frame.getContentPane().add(scrollTableVL);
itemsTableSD = new JTable();
scrollTableSD.setViewportView(itemsTableSD);
itemsTablePI = new JTable();
scrollTablePI.setViewportView(itemsTablePI);
itemsTableVL = new JTable();
scrollTableVL.setViewportView(itemsTableVL);
}
private void callRenderTable(JTextArea textArea, JScrollPane scrollTable, JTable itemsTable, ArrayList<String> addItems, int itemIndexNo[], int loopCount, int totCount){
textArea.setVisible(false);
scrollTable.setVisible(true);
//DefaultTableModel tableModel = new DefaultTableModel(){
tableModel = new DefaultTableModel(){
public Class<?> getColumnClass(int column){
switch(column){
case 0:
return String.class;
case 1:
return Boolean.class;
case 2:
return String.class;
case 3:
return Boolean.class;
case 4:
return String.class;
case 5:
return Boolean.class;
default:
return String.class;
}
}
int row = 0;
int column = 1;
boolean[] canEdit = new boolean[]{false, true, false, true, false, true};
#Override
public boolean isCellEditable(int row, int column) {
if (row == 0 && column == 1){
return false;}
return canEdit[column];
}
};
//Assign the model to table
itemsTable.setModel(tableModel);
tableModel.addColumn("Items");
tableModel.addColumn("Select");
tableModel.addColumn("Items");
tableModel.addColumn("Select");
tableModel.addColumn("Items");
tableModel.addColumn("Select");
//The row
int indIncr = 0;
for(int i = 0; i <= loopCount; i++){
tableModel.addRow(new Object[0]);
for(int j = 0; j <= 2; j++){
if (j == 0 && indIncr < totCount){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j);
tableModel.setValueAt(true, i, j+1);
indIncr = indIncr + 1;}
if (j == 1 && indIncr < totCount ){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j+1);
tableModel.setValueAt(true, i, j+2);
indIncr = indIncr + 1;}
if (j == 2 && indIncr < totCount){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j+2);
tableModel.setValueAt(true, i, j+3);
indIncr = indIncr + 1;}
}
}
}
}
You only have one variable "tableModel" so how do you expect that variable to reference 3 table models?
You have 3 variables to reference each of your 3 tables.
So you need code like:
DefaultTableModel model1 = (DefaultTableModel)itsTableSD.getModel();
DefaultTableModel model2 = (DefaultTableModel)itsTablePI.getModel();
DefaultTableModel model3 = (DefaultTableModel)itsTableVL.getModel();
Now you can use the getDataVector() method on each of the table models.
Also, get rid of your static variables. In general variables should not be static.

How do i change font of the buttons within a JTable

I have the following Code that Buttons are within cells
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
/**
* #version 1.0 11/09/98
*/
public class JButtonTableExample extends JFrame {
public JButtonTableExample() {
super("JButtonTable Example");
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][] { { "button 1", "foo" },
{ "button 2", "bar" } }, new Object[] { "Button", "String" });
JTable table = new JTable(dm);
table.setFont(new Font("Comic Sans MA",0,20));
table.setRowHeight(35);
table.getColumn("Button").setCellRenderer(new ButtonRenderer());
table.getColumn("Button").setCellEditor(
new ButtonEditor(new JCheckBox()));
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
JButtonTableExample frame = new JButtonTableExample();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
/**
* #version 1.0 11/09/98
*/
class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
}
setText((value == null) ? "" : value.toString());
return this;
}
}
/**
* #version 1.0 11/09/98
*/
class ButtonEditor extends DefaultCellEditor {
protected JButton button;
private String label;
private boolean isPushed;
public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton();
button.setFont(new Font("Comic Sans MS",0,25));
buttonButtonEditor
button.setOpaque(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(table.getSelectionBackground());
} else {
button.setForeground(table.getForeground());
button.setBackground(table.getBackground());
}
label = (value == null) ? "" : value.toString();
button.setText(label);
isPushed = true;
return button;
}
public Object getCellEditorValue() {
if (isPushed) {
//
//
JOptionPane.showMessageDialog(button, label + ": Ouch!");
// System.out.println(label + ": Ouch!");
}
isPushed = false;
return new String(label);
}
public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
I tried to change the font of the buttons by adding the following line of code to the ButtonEditor class
button.setFont(new Font("Comic Sans MS",0,25));
But it doesn't Work!!
What should I do to change the font of those buttons
Edit your ButtonRenderer class as follows:
class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
}
setText((value == null) ? "" : value.toString());
setFont(new Font("Times New Roman", 0, 10)); //Add this line
return this;
}
}
Font was always being reset to the table's model, so you were needing to add that line to force the model to respect the change.
And your output should be:

New line in jTable cell

This is how I am adding rows to my jTable, as you can see I tried using \n in zainteresowania but it is being ignored. How can I simple add new line after every record from my List?
for (Osoba a : osoby){
List zainteresowania1 = a.getZainteresowania();
for (Iterator iterator2 = zainteresowania1.iterator(); iterator2.hasNext();){
Zainteresowania nazwa = (Zainteresowania) iterator2.next();
zainteresowania = zainteresowania + (nazwa.getZainteresowanie() + ". " + "\n");
}
model.addRow(new Object[]{a.getImie(), a.getNazwisko(), a.getEmail(), a.getTelefon(), zainteresowania});
zainteresowania = "";
}
Refer Example
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class TestJTableMultiline extends JFrame {
public TestJTableMultiline() {
super("Multi-Line Cell Example");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
DefaultTableModel dm = new DefaultTableModel() {
public Class<String> getColumnClass(int columnIndex) {
return String.class;
}
public boolean isCellEditable(int row, int column) {
return false;
}
};
dm.setDataVector(
new Object[][]{
{"A0, Line1\nA0, Line2\nA0, Line3",
"B0, Line1\nB0, Line2",
"C0, Line1"},
{"A1, Line1",
"B1, Line1\nB1, Line2",
"C1, Line1"},
{"A2, Line1",
"B2, Line1",
"C2, Line1"}
},
new Object[] {"A", "B", "C"});
JTable table = new JTable(dm);
table.setDefaultRenderer(String.class, new MultiLineTableCellRenderer());
TableRowSorter<? extends TableModel> sort = new TableRowSorter<DefaultTableModel>(dm);
table.setRowSorter(sort);
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
setLocationByPlatform(true);
setSize(400, 430);
setVisible(true);
}
public static void main(String[] args) {
TestJTableMultiline frame = new TestJTableMultiline();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
public class MultiLineTableCellRenderer extends JTextArea
implements TableCellRenderer {
private List<List<Integer>> rowColHeight = new ArrayList<List<Integer>>();
public MultiLineTableCellRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
setOpaque(true);
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setFont(table.getFont());
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
if (table.isCellEditable(row, column)) {
setForeground(UIManager.getColor("Table.focusCellForeground"));
setBackground(UIManager.getColor("Table.focusCellBackground"));
}
} else {
setBorder(new EmptyBorder(1, 2, 1, 2));
}
if (value != null) {
setText(value.toString());
} else {
setText("");
}
adjustRowHeight(table, row, column);
return this;
}
/**
* Calculate the new preferred height for a given row, and sets the height on the table.
*/
private void adjustRowHeight(JTable table, int row, int column) {
//The trick to get this to work properly is to set the width of the column to the
//textarea. The reason for this is that getPreferredSize(), without a width tries
//to place all the text in one line. By setting the size with the with of the column,
//getPreferredSize() returnes the proper height which the row should have in
//order to make room for the text.
int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth();
setSize(new Dimension(cWidth, 1000));
int prefH = getPreferredSize().height;
while (rowColHeight.size() <= row) {
rowColHeight.add(new ArrayList<Integer>(column));
}
List<Integer> colHeights = rowColHeight.get(row);
while (colHeights.size() <= column) {
colHeights.add(0);
}
colHeights.set(column, prefH);
int maxH = prefH;
for (Integer colHeight : colHeights) {
if (colHeight > maxH) {
maxH = colHeight;
}
}
if (table.getRowHeight(row) != maxH) {
table.setRowHeight(row, maxH);
}
}
}

Categories