Related
I was changing the LookAndFeel of a JTable populated of Custom Class extended of JPanel , But I can't to do it.
I edited to simply my code, but still it's long.
public class LAF_TableCustomContainer extends JFrame {
public LAF_TableCustomContainer() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
setLocationRelativeTo(null);
}
public static void changeLAF(Container container, String laf) {
try {
UIManager.setLookAndFeel(laf);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
}
SwingUtilities.updateComponentTreeUI(container);
}
static final JFrame frame = new JFrame();
public JComponent makeUI() {
String[] hdrsObjects = {"PanelSpinnerRadioButton Class Column"};
Object[][] objectMatrix = new Object[3][1];
objectMatrix[0][0] = new PanelSpinnerRadioButtonData(false, 10, 40);
objectMatrix[1][0] = new PanelSpinnerRadioButtonData(true, 20, 40);
objectMatrix[2][0] = new PanelSpinnerRadioButtonData(false, 30, 40);
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setRowHeight(30);
TableColumn tc = table.getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
JPanel pH = new JPanel();
pH.setLayout(new BoxLayout(pH, BoxLayout.LINE_AXIS));
JButton bMetal = new JButton("Metal");
bMetal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF(table, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF(scrollPane, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.metal.MetalLookAndFeel");
}
});
JButton bMotif = new JButton("Motif");
bMotif.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF(table, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF(scrollPane, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
});
JButton bNimbus = new JButton("Nimbus");
bNimbus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF(table, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF(scrollPane, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
});
pH.add(bMetal);
pH.add(bMotif);
pH.add(bNimbus);
JPanel pV = new JPanel();
pV.setLayout(new BoxLayout(pV, BoxLayout.PAGE_AXIS));
pV.add(pH);
pV.add(scrollPane);
return pV;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
LAF_TableCustomContainer f = new LAF_TableCustomContainer();
f.getContentPane().add(f.makeUI());
});
}
}
class PanelSpinnerRadioButtonData {
private boolean opt02 = false;
private Integer from = 0;
private Integer size = 1;
PanelSpinnerRadioButtonData() {
this(false, 5, 10);
}
PanelSpinnerRadioButtonData(boolean opt02, Integer from, Integer size) {
this.opt02 = opt02;
this.from = from;
this.size = size;
}
public boolean getOption() {
return opt02;
}
public Integer getFrom() {
return from;
}
public Integer getSize() {
return size;
}
}
class PanelSpinnerRadioButton extends JPanel {
public final JRadioButton jrbOption01 = new JRadioButton("01");
public final JRadioButton jrbOption02 = new JRadioButton("12");
public final JSpinner jspnValues = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
private final JPanel panel = new JPanel();
PanelSpinnerRadioButton() {
this(new PanelSpinnerRadioButtonData(false, 20, 40));
}
PanelSpinnerRadioButton(PanelSpinnerRadioButtonData data) {
super();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(jrbOption01);
panel.add(jrbOption02);
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(new JSeparator(JSeparator.VERTICAL));
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(jspnValues);
ButtonGroup bg = new ButtonGroup();
bg.add(jrbOption01);
bg.add(jrbOption02);
((SpinnerNumberModel) jspnValues.getModel()).setMaximum(data.getSize());
setData(data);
init();
}
private void init() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
setBackground(new Color(0, 0, 0, 0));
add(panel);
}
public void setData(PanelSpinnerRadioButtonData data) {
if (data.getOption()) {
jrbOption02.setSelected(true);
} else {
jrbOption01.setSelected(true);
}
((SpinnerNumberModel) jspnValues.getModel()).setValue(data.getFrom());
}
// Used in PSRBTableCellEditor.getCellEditorValue()
public PanelSpinnerRadioButtonData getData() {
return new PanelSpinnerRadioButtonData(
jrbOption02.isSelected(),
(Integer) ((SpinnerNumberModel) jspnValues.getModel()).getValue(),
(Integer) ((SpinnerNumberModel) jspnValues.getModel()).getMaximum());
}
}
class PSRBTableCellRenderer implements TableCellRenderer {
private final PanelSpinnerRadioButton renderer = new PanelSpinnerRadioButton();
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
renderer.setData((PanelSpinnerRadioButtonData) value);
}
return renderer;
}
}
class PSRBTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private final PanelSpinnerRadioButton editor = new PanelSpinnerRadioButton();
#Override public Object getCellEditorValue() {
return editor.getData();
}
#Override public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
editor.setData((PanelSpinnerRadioButtonData) value);
}
return editor;
}
}
When I press some button all JFrame changes except the cells of JTable, containing my custom JPanel.
I tried forcing only the first cell...
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.metal.MetalLookAndFeel");
But I got Exception:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: PanelSpinnerRadioButtonData cannot be cast to javax.swing.JPanel
The limitation of the SwingUtilities#updateComponentTreeUI(...) method is that the cell renderer LookAndFeel can not change
Since PSRBTableCellRenderer does not extends JComponent, it is not subject to LookAndFeel update in the SwingUtilities # updateComponentTreeUI (...) method
// #see javax/swing/SwingUtilities.java
public static void updateComponentTreeUI(Component c) {
updateComponentTreeUI0(c);
c.invalidate();
c.validate();
c.repaint();
}
private static void updateComponentTreeUI0(Component c) {
if (c instanceof JComponent) {
JComponent jc = (JComponent) c;
jc.updateUI();
JPopupMenu jpm =jc.getComponentPopupMenu();
if(jpm != null) {
updateComponentTreeUI(jpm);
}
}
Component[] children = null;
if (c instanceof JMenu) {
children = ((JMenu)c).getMenuComponents();
}
else if (c instanceof Container) {
children = ((Container)c).getComponents();
}
if (children != null) {
for (Component child : children) {
updateComponentTreeUI0(child);
}
}
}
You can avoid this by overriding the JTable#updateUI() method and recreating the cell renderer and editor.
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects)) {
#Override public void updateUI() {
super.updateUI();
setRowHeight(30);
TableColumn tc = getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
}
};
LAF_TableCustomContainer2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class LAF_TableCustomContainer2 extends JFrame {
public LAF_TableCustomContainer2() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
setLocationRelativeTo(null);
}
public static void changeLAF(Container container, String laf) {
try {
UIManager.setLookAndFeel(laf);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
}
SwingUtilities.updateComponentTreeUI(container);
}
static final JFrame frame = new JFrame();
public JComponent makeUI() {
JPanel pV = new JPanel();
pV.setLayout(new BoxLayout(pV, BoxLayout.PAGE_AXIS));
String[] hdrsObjects = {"PanelSpinnerRadioButton Class Column"};
Object[][] objectMatrix = new Object[3][1];
objectMatrix[0][0] = new PanelSpinnerRadioButtonData(false, 10, 40);
objectMatrix[1][0] = new PanelSpinnerRadioButtonData(true, 20, 40);
objectMatrix[2][0] = new PanelSpinnerRadioButtonData(false, 30, 40);
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects)) {
#Override public void updateUI() {
super.updateUI();
setRowHeight(30);
TableColumn tc = getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
}
};
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
// table.setRowHeight(30);
// TableColumn tc = table.getColumn("PanelSpinnerRadioButton Class Column");
// tc.setCellRenderer(new PSRBTableCellRenderer());
// tc.setCellEditor(new PSRBTableCellEditor());
JPanel pH = new JPanel();
pH.setLayout(new BoxLayout(pH, BoxLayout.LINE_AXIS));
JButton bMetal = new JButton("Metal");
bMetal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "javax.swing.plaf.metal.MetalLookAndFeel");
}
});
JButton bMotif = new JButton("Motif");
bMotif.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
});
JButton bNimbus = new JButton("Nimbus");
bNimbus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
});
pH.add(bMetal);
pH.add(bMotif);
pH.add(bNimbus);
pV.add(pH);
pV.add(scrollPane);
return pV;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
LAF_TableCustomContainer2 f = new LAF_TableCustomContainer2();
f.getContentPane().add(f.makeUI());
});
}
}
class PanelSpinnerRadioButtonData {
private boolean opt02 = false;
private Integer from = 0;
private Integer size = 1;
PanelSpinnerRadioButtonData() {
this(false, 5, 10);
}
PanelSpinnerRadioButtonData(boolean opt02, Integer from, Integer size) {
this.opt02 = opt02;
this.from = from;
this.size = size;
}
public boolean getOption() {
return opt02;
}
public Integer getFrom() {
return from;
}
public Integer getSize() {
return size;
}
}
class PanelSpinnerRadioButton extends JPanel {
public final JRadioButton jrbOption01 = new JRadioButton("01");
public final JRadioButton jrbOption02 = new JRadioButton("12");
public final JSpinner jspnValues = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
private final JPanel panel = new JPanel();
PanelSpinnerRadioButton() {
this(new PanelSpinnerRadioButtonData(false, 20, 40));
}
PanelSpinnerRadioButton(PanelSpinnerRadioButtonData data) {
super();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(jrbOption01);
panel.add(jrbOption02);
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(new JSeparator(JSeparator.VERTICAL));
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(jspnValues);
ButtonGroup bg = new ButtonGroup();
bg.add(jrbOption01);
bg.add(jrbOption02);
((SpinnerNumberModel) jspnValues.getModel()).setMaximum(data.getSize());
setData(data);
init();
}
private void init() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
setBackground(new Color(0, 0, 0, 0));
add(panel);
}
public void setData(PanelSpinnerRadioButtonData data) {
if (data.getOption()) {
jrbOption02.setSelected(true);
} else {
jrbOption01.setSelected(true);
}
((SpinnerNumberModel) jspnValues.getModel()).setValue(data.getFrom());
}
// Used in PSRBTableCellEditor.getCellEditorValue()
public PanelSpinnerRadioButtonData getData() {
return new PanelSpinnerRadioButtonData(
jrbOption02.isSelected(),
(Integer)((SpinnerNumberModel) jspnValues.getModel()).getValue(),
(Integer)((SpinnerNumberModel) jspnValues.getModel()).getMaximum());
}
}
class PSRBTableCellRenderer implements TableCellRenderer {
private final PanelSpinnerRadioButton renderer = new PanelSpinnerRadioButton();
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
renderer.setData((PanelSpinnerRadioButtonData) value);
}
return renderer;
}
}
class PSRBTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private final PanelSpinnerRadioButton editor = new PanelSpinnerRadioButton();
#Override public Object getCellEditorValue() {
return editor.getData();
}
#Override public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
editor.setData((PanelSpinnerRadioButtonData) value);
}
return editor;
}
}
I've removed most of my GUI to keep the code short.
I have a buttongroup of 3 JRadioButtons to select the table schema i want to display in my JTable, which is contained in a JScrollPane
I have tried to use fireTableStructureChanged() andfireTableDataChanged() as well as JTable.repaint() to no avail. Can anyone help me?
Here is a simple example that runs a window with my configuration but does not update the table.
public class test1 implements ActionListener {
private boolean payrollActive = false;
private JPanel mainPanel = new JPanel();
private JTable dataTable;
private Vector<String> courseColumns = new Vector<String>();
private Vector<String> courseColumnsPay = new Vector<String>();
private Vector<String> profsColumns = new Vector<String>();
private Vector<String> offSpaceColumns = new Vector<String>();
public test1() {
//Add columns for tables
String[] courseColsPay = {"Year", "Program", "Course", "Code", "CCCode",
"Weight", "Session", "Section", "Day", "STime", "FTime",
"BookedRM", "EnrolCap", "Description", "ProfFName",
"ProfLName", "ProfEmail", "Notes", "Syllabus", "Exam",
"CrossList", "PreReqs", "EnrolCtrls", "Shared",
"TrackChanges", "Address", "WageType", "BasePay",
"BenefitRate", "Budgeted", "PayAmount",
"MthAmount", "Term", "AccNumber", "PayAdmin", "PayableTo"};
for (String col : courseColsPay) {
courseColumnsPay.add(col);
}
for (int i = 0; i < 25; i++) {
courseColumns.add(courseColsPay[i]);
}
String[] profCols = {"FName", "LName", "Email", "UTEmail", "Birthdate",
"OfficeBC", "OfficeRM", "Department", "Status",
"Fellowship", "OfficeStat", "PhoneNum", "HomeAddr",
"HomePhoneNum", "Notes"};
for (String col : profCols) {
profsColumns.add(col);
}
String[] offSpaceCols = {"Building", "DeptID", "DivisionName", "BldgID", "RoomID",
"Category", "Description", "ShareType", "DeptName",
"Status", "SharePerc", "ShareOccupancy", "Area",
"Fellow", "Commments", "Name", "Position",
"Dept", "FTE", "CrossApp", "CrossPos", "CrossDept",
"CrossFTE", "OtherOffice"};
for (String col : offSpaceCols) {
offSpaceColumns.add(col);
}
mainPanel.setSize(1260, 630);
mainPanel.setLayout(null);
JRadioButton coursesBtn = new JRadioButton("Courses");
coursesBtn.setMnemonic(KeyEvent.VK_C);
coursesBtn.setActionCommand("Course");
coursesBtn.setSelected(true);
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
profsBtn.setMnemonic(KeyEvent.VK_P);
profsBtn.setActionCommand("Professors");
coursesBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
officeSpBtn.setMnemonic(KeyEvent.VK_O);
officeSpBtn.setActionCommand("Office Spaces");
coursesBtn.addActionListener(this);
ButtonGroup tablesBtns = new ButtonGroup();
tablesBtns.add(coursesBtn);
tablesBtns.add(profsBtn);
tablesBtns.add(officeSpBtn);
JPanel tableRadioPanel = new JPanel(new GridLayout(0, 1));
tableRadioPanel.setOpaque(true);
tableRadioPanel.setBounds(0, 0, 150, 70);
tableRadioPanel.add(coursesBtn);
tableRadioPanel.add(profsBtn);
tableRadioPanel.add(officeSpBtn);
//table start
DefaultTableModel coursesModel = new DefaultTableModel(courseColumns, 200);
dataTable = new JTable(coursesModel);
dataTable.setFillsViewportHeight(true);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(160, 0, 1016, 558);
//table code end
mainPanel.add(tableRadioPanel);
mainPanel.add(scrollPane);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTable getDataTable() {
return dataTable;
}
/**
* Returns the list of columns for the given table
* #param identifier the name of the table
* #return a Vector<String> of column names
*/
public Vector<String> getColumns(String identifier) {
switch (identifier) {
case "Courses":
if (payrollActive) {
return courseColumnsPay;
} else {
return courseColumns;
}
case "Professors":
return profsColumns;
case "Office Spaces":
return offSpaceColumns;
default:
return null;
}
}
public static void createAndShowGui() {
test1 vicu = new test1();
JFrame frame = new JFrame("Victoria University Database Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1260, 630);
frame.setLocationRelativeTo(null);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.getContentPane().add(vicu.getMainPanel());
frame.getContentPane().setLayout(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton targetBtn = (JRadioButton) e.getSource();
((DefaultTableModel) dataTable.getModel()).
setColumnIdentifiers(getColumns(targetBtn.getText()));
}
}
In your example, you are not registering an ActionListener to profsBtn or officeSpBtn, you keep registering to coursesBtn
JRadioButton coursesBtn = new JRadioButton("Courses");
//...
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
//...
coursesBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
//...
coursesBtn.addActionListener(this);
Once I register the ActionListener to the correct buttons, it works fine
The problem seems to be that the code adds the listener 3 times to a single button, rather than once each to each of the 3 buttons!
..my application is for a very limited scope and can do without a layout manager for my purposes, unless you think this is affecting the table's behaviour?
No, not the table. It was however causing the emptyLabel to be assigned no space in the layout. Here is a robust, resizable version of the GUI.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.util.*;
public class test1 implements ActionListener {
private boolean payrollActive = false;
private JPanel mainPanel = new JPanel(new BorderLayout(5,5));
private JTable dataTable;
private Vector<String> courseColumns = new Vector<String>();
private Vector<String> courseColumnsPay = new Vector<String>();
private Vector<String> profsColumns = new Vector<String>();
private Vector<String> offSpaceColumns = new Vector<String>();
public test1() {
mainPanel.setBorder(new EmptyBorder(5,5,5,5));
//Add columns for tables
String[] courseColsPay = {"Year", "Program", "Course", "Code", "CCCode",
"Weight", "Session", "Section", "Day", "STime", "FTime",
"BookedRM", "EnrolCap", "Description", "ProfFName",
"ProfLName", "ProfEmail", "Notes", "Syllabus", "Exam",
"CrossList", "PreReqs", "EnrolCtrls", "Shared",
"TrackChanges", "Address", "WageType", "BasePay",
"BenefitRate", "Budgeted", "PayAmount",
"MthAmount", "Term", "AccNumber", "PayAdmin", "PayableTo"};
for (String col : courseColsPay) {
courseColumnsPay.add(col);
}
for (int i = 0; i < 25; i++) {
courseColumns.add(courseColsPay[i]);
}
String[] profCols = {"FName", "LName", "Email", "UTEmail", "Birthdate",
"OfficeBC", "OfficeRM", "Department", "Status",
"Fellowship", "OfficeStat", "PhoneNum", "HomeAddr",
"HomePhoneNum", "Notes"};
for (String col : profCols) {
profsColumns.add(col);
}
String[] offSpaceCols = {"Building", "DeptID", "DivisionName", "BldgID", "RoomID",
"Category", "Description", "ShareType", "DeptName",
"Status", "SharePerc", "ShareOccupancy", "Area",
"Fellow", "Commments", "Name", "Position",
"Dept", "FTE", "CrossApp", "CrossPos", "CrossDept",
"CrossFTE", "OtherOffice"};
for (String col : offSpaceCols) {
offSpaceColumns.add(col);
}
//mainPanel.setSize(1260, 630);
//mainPanel.setLayout(null);
JRadioButton coursesBtn = new JRadioButton("Courses");
coursesBtn.setMnemonic(KeyEvent.VK_C);
coursesBtn.setActionCommand("Course");
coursesBtn.setSelected(true);
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
profsBtn.setMnemonic(KeyEvent.VK_P);
profsBtn.setActionCommand("Professors");
profsBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
officeSpBtn.setMnemonic(KeyEvent.VK_O);
officeSpBtn.setActionCommand("Office Spaces");
officeSpBtn.addActionListener(this);
ButtonGroup tablesBtns = new ButtonGroup();
tablesBtns.add(coursesBtn);
tablesBtns.add(profsBtn);
tablesBtns.add(officeSpBtn);
JPanel tableRadioPanel = new JPanel(new GridLayout(0, 1));
tableRadioPanel.add(coursesBtn);
tableRadioPanel.add(profsBtn);
tableRadioPanel.add(officeSpBtn);
//table start
DefaultTableModel coursesModel = new DefaultTableModel(courseColumns, 200);
dataTable = new JTable(coursesModel);
dataTable.setFillsViewportHeight(true);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scrollPane.setBounds(160, 0, 1016, 558);
//table code end
JPanel gridConstrain = new JPanel();
gridConstrain.add(tableRadioPanel);
mainPanel.add(gridConstrain, BorderLayout.LINE_START);
mainPanel.add(scrollPane);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTable getDataTable() {
return dataTable;
}
/**
* Returns the list of columns for the given table
* #param identifier the name of the table
* #return a Vector<String> of column names
*/
public Vector<String> getColumns(String identifier) {
switch (identifier) {
case "Courses":
if (payrollActive) {
return courseColumnsPay;
} else {
return courseColumns;
}
case "Professors":
return profsColumns;
case "Office Spaces":
return offSpaceColumns;
default:
return null;
}
}
public static void createAndShowGui() {
test1 vicu = new test1();
JFrame frame = new JFrame("Victoria University Database Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JLabel emptyLabel = new JLabel("Empty Label");
emptyLabel.setFont(emptyLabel.getFont().deriveFont(80f));
//emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.PAGE_START);
frame.getContentPane().add(vicu.getMainPanel());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Event: " + e);
JRadioButton targetBtn = (JRadioButton) e.getSource();
((DefaultTableModel) dataTable.getModel()).
setColumnIdentifiers(getColumns(targetBtn.getText()));
}
}
There are a lot of time, that I'm trying to make the Cell Renderer in the JavaOne 2007's talk maked by Shanon Hickey, Romain Guy and Chris Campbell, in the pages 38 and 39 (that you can find here : http://docs.huihoo.com/javaone/2007/desktop/TS-3548.pdf).
I asked Romain Guy, and Chris campbell, but without success, they say that they cannot pulish the source code.
So, any one can, give an idea, or even a source code on how to make this complex cell renderer ?
I learned this slides of many times, they say :
1)Cell Renderer: Column Spanning
Viewport clips column contents
and
2) Viewport moves to
expose the right text
for each column
I don't understand that, please can you give more in depth explanations ?
Cheers
Windows 7
JDK 1.7.0_21
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class ComplexCellRendererTest {
private static boolean DEBUG = true;
private JRadioButton r1 = new JRadioButton("scrollRectToVisible");
private JRadioButton r2 = new JRadioButton("setViewPosition");
public JComponent makeUI() {
String[] columnNames = {"AAA", "BBB"};
Object[][] data = {
{new Test("1", "aaaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), "4"},
{new Test("2", "1234567890\nabcdefghijklmdopqrstuvwxyz"), "5"},
{new Test("3", "ccccccccccccccccccccccccccccccccccc\ndddddddddddd"), "6"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
#Override public boolean isCellEditable(int row, int column) {
return false;
}
};
final JTable table = new JTable(model);
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setShowVerticalLines(false);
table.setIntercellSpacing(new Dimension(0,1));
table.setRowHeight(56);
for(int i=0; i<table.getColumnModel().getColumnCount(); i++) {
TableColumn c = table.getColumnModel().getColumn(i);
c.setCellRenderer(new ComplexCellRenderer());
c.setMinWidth(50);
}
ActionListener al = new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
DEBUG = (e.getSource()==r1);
table.repaint();
}
};
Box box = Box.createHorizontalBox();
ButtonGroup bg = new ButtonGroup();
box.add(r1); bg.add(r1); r1.addActionListener(al);
box.add(r2); bg.add(r2); r2.addActionListener(al);
r1.setSelected(true);
JPanel p = new JPanel(new BorderLayout());
p.add(box, BorderLayout.NORTH);
p.add(new JScrollPane(table));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ComplexCellRendererTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
static class ComplexCellRenderer extends JPanel implements TableCellRenderer {
private final JTextArea textArea = new JTextArea(2, 999999);
private final JLabel label = new JLabel();
private final JScrollPane scroll = new JScrollPane();
public ComplexCellRenderer() {
super(new BorderLayout(0,0));
scroll.setViewportView(textArea);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setBorder(BorderFactory.createEmptyBorder());
scroll.setViewportBorder(BorderFactory.createEmptyBorder());
scroll.setOpaque(false);
scroll.getViewport().setOpaque(false);
textArea.setBorder(BorderFactory.createEmptyBorder());
//textArea.setMargin(new Insets(0,0,0,0));
textArea.setForeground(Color.RED);
textArea.setOpaque(false);
label.setBorder(BorderFactory.createMatteBorder(0,0,1,1,Color.GRAY));
setBackground(Color.WHITE);
setOpaque(true);
add(label, BorderLayout.NORTH);
add(scroll);
}
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Test test;
if(value instanceof Test) {
test = (Test)value;
} else {
String title = value.toString();
Test t = (Test)table.getModel().getValueAt(row, 0);
test = new Test(title, t.text);
}
label.setText(test.title);
textArea.setText(test.text);
Rectangle cr = table.getCellRect(row, column, false);
if(DEBUG) {
//Unexplained flickering on first row?
textArea.scrollRectToVisible(cr);
} else {
//Work fine for me (JDK 1.7.0_21, Windows 7 64bit):
scroll.getViewport().setViewPosition(cr.getLocation());
}
if(isSelected) {
setBackground(Color.ORANGE);
} else {
setBackground(Color.WHITE);
}
return this;
}
}
}
class Test {
public final String title;
public final String text;
//public final Icon icon;
public Test(String title, String text) {
this.title = title;
this.text = text;
}
}
I need a Jtable having Add Button on the header.When add is clicked..then it must add a row containing 4 columns of 3 textfields and delete button. When delete button is clicked, then the corresponding row should deleted.. Thanks in advance..
public class UserTableInfo {
private JFrame frame;
private JTable CompTable = null;
private PanelTableModel CompModel = null;
private JButton delButton=null;
private JButton button=null;
public static void main(String args[]) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception fail) {
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UserTableInfo().makeUI();
}
}); }
public void makeUI() {
CompTable = CreateCompTable();
JScrollPane CompTableScrollpane = new JScrollPane(CompTable,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JPanel bottomPanel = CreateBottomPanel();
frame = new JFrame("Comp Table Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(CompTableScrollpane, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
frame.setPreferredSize(new Dimension(800, 400));
frame.setLocation(150, 150);
frame.pack();
frame.setVisible(true);
}public JTable CreateCompTable() {
CompModel = new PanelTableModel();
button=new JButton("Add Row");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CompModel.addRow();
}
});
JTable table = new JTable(CompModel);
table.setRowHeight(new CompCellPanel().getPreferredSize().height);
JTableHeader header = table.getTableHeader();
header.setLayout(new FlowLayout(FlowLayout.TRAILING, 5, 0));
header.add(button);
PanelCellEditorRenderer PanelCellEditorRenderer = new
PanelCellEditorRenderer();
table.setDefaultRenderer(Object.class, PanelCellEditorRenderer);
table.setDefaultEditor(Object.class, PanelCellEditorRenderer);
return table;
} public JPanel CreateBottomPanel() {
delButton=new JButton("Exit");
delButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source == delButton) {
System.exit(1);
}
}
}); JPanel panel = new JPanel(new GridBagLayout());
panel.add(delButton);
return panel;
}
}
class PanelCellEditorRenderer extends AbstractCellEditor implements
TableCellRenderer, TableCellEditor {
private static final long serialVersionUID = 1L;
private CompCellPanel renderer = new CompCellPanel();
private CompCellPanel editor = new CompCellPanel();
#Override
public Component getTableCellRendererComponent(JTable table, Object
value, boolean isSelected, boolean hasFocus, int row, int column) {
renderer.setComp((Comp) value);
return renderer;
}
#Override
public Component getTableCellEditorComponent(JTable table, Object
value, boolean isSelected, int row, int column) {
editor.setComp((Comp) value);
return editor;
}
#Override
public Object getCellEditorValue() {
return null;
}
#Override
public boolean isCellEditable(EventObject anEvent) {
return true;
}
#Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
}
class PanelTableModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
#Override
public int getColumnCount() {
return 1;
}
public void addRow() {
super.addRow(new Object[]{new Comp("")});
}
}
class Comp {
public String upper;
public Comp(String upper) {
this.upper = upper;
}
}
class CompCellPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JLabel label = new JLabel();
private JTextField upperField = new JTextField();
private JButton removeButton = new JButton("remove");
CompCellPanel() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTable table = (JTable)
SwingUtilities.getAncestorOfClass(JTable.class, (Component) e.getSource());
int row = table.getEditingRow();
table.getCellEditor().stopCellEditing();
((DefaultTableModel) table.getModel()).removeRow(row);
} });
upperField.setMaximumSize(new Dimension(Integer.MAX_VALUE, upperField.getPreferredSize().height) );
add(upperField);
label.setMaximumSize(getMaximumSize());
add(label);
add(Box.createHorizontalStrut(10));
add(removeButton);
}
public void setComp(Comp Comp) {
upperField.setText(Comp.upper);
} }
This is much easier if you extend a AbstractTableModel and use that to display your data. You can make an ArrayList of your data and add/remove from that. The TableModel will update the Table automatically when the ArrayList is changed. The ArrayList contains a class which has all the data that you would have in a row. See the Java Tutorials example from Oracle: http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableDemoProject/src/components/TableDemo.java
For custom cells, you can detect from the TableModel which column the cell is in and update its content accordingly.
For initialization:
Vector<Vector> rowdata = new Vector<Vector>();
Vector columnname = new Vector();
JTabel result = new JTable(rowdata, columnname);
JScrollPane sqlresult = new JScrollPane(result);
In the later part, I assign values in rowdata and columnname vector. How to show new values in JTable on GUI?
In addition..
result.repaint();
..and..
((DefaultTableModel)result.getModel()).fireTabelDataChanged()
..seem to do nothing.
1) use DefaultTableModel for JTable
2) define Column Class
3) add row(s) DefaultTableModel.addRow(myVector);
for example
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class DefaultTableModelDemo {
public static final String[] COLUMN_NAMES = {
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
};
private DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);
private JTable table = new JTable(model);
private JPanel mainPanel = new JPanel(new BorderLayout());
private Random random = new Random();
public DefaultTableModelDemo() {
JButton addDataButton = new JButton("Add Data");
JPanel buttonPanel = new JPanel();
buttonPanel.add(addDataButton);
addDataButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addDataActionPerformed();
}
});
model = new DefaultTableModel(COLUMN_NAMES, 0) {
private static final long serialVersionUID = 1L;
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model) {
private static final long serialVersionUID = 1L;
#Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
if (isRowSelected(row) && isColumnSelected(column)) {
((JComponent) c).setBorder(new LineBorder(Color.red));
}
return c;
}
};
mainPanel.add(new JScrollPane(table), BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void addDataActionPerformed() {
for (int i = 0; i < 5; i++) {
Object[] row = new Object[COLUMN_NAMES.length];
for (int j = 0; j < row.length; j++) {
row[j] = random.nextInt(5);
}
model.addRow(row);
}
}
public JComponent getComponent() {
return mainPanel;
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("DefaultTableModelDemo");
frame.getContentPane().add(new DefaultTableModelDemo().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
rowdata and columnname are used for the initialization of JTable, after the component JTable exists you need to use JTable.getColumnModel() and JTable.getModel() to add columns or rows.
Or JTable.addColumn(TableColumn aColumn) if you only wants to add a column.
Look here if you want to know how to add a row following an example.