Extending JTable and displaying in a JFrame - java

My code is still heavily in progress but my problem is that my class that extends JTable will not display in a JFrame. Here is my class that extends JTable. Secondly, I would like to know if the design option of making my LotteryTable an entirely new class a good idea.
At first, my LotteryDisplay contained a JTable which then was adjusted through a method tableSetup() which is now in LotteryTable.
public class LotteryTable extends JTable
{
private final String[] columnNames = {"Powerball Combos", "Odds of Winning", "Payout", "Number of Wins", "Win Frequency"};
JTable table;
public LotteryTable()
{
DefaultTableModel model = new DefaultTableModel(columnNames, 9);
table = new JTable(model)
{
public Class getColumnClass(int column)
{
if(column == 0)
return ImageIcon.class;
else
return String.class;
}
};
tableSetup();
setVisible(true);
}
public void tableSetup()
{
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
table.setDefaultRenderer(String.class, dtcr);
ImageIcon p = new ImageIcon("Icons/Powerball.png"); //Not important to my problem
ImageIcon w1p = new ImageIcon("Icons/WhiteplusPowerball.png");
ImageIcon w2P = new ImageIcon("Icons/2WhitePlusPowerball.png");
ImageIcon w3P = new ImageIcon("Icons/3WhitePlusPowerball.png");
ImageIcon w4P = new ImageIcon("Icons/4WhitePlusPowerball.png");
ImageIcon w5P = new ImageIcon("Icons/5WhitePlusPowerball.png");
ImageIcon w3 = new ImageIcon("Icons/3White.png");
ImageIcon w4 = new ImageIcon("Icons/4White.png");
ImageIcon w5 = new ImageIcon("Icons/5White.png");
table.setValueAt(p, 0, 0);
table.setValueAt(w1p, 1, 0);
table.setValueAt(w2P, 2, 0);
table.setValueAt(w3, 3, 0);
table.setValueAt(w3P, 4, 0);
table.setValueAt(w4, 5, 0);
table.setValueAt(w4P, 6, 0);
table.setValueAt(w5, 7, 0);
table.setValueAt(w5P, 8, 0);
table.setValueAt("1 in 55", 0, 1);
table.setValueAt("1 in 111", 1, 1);
table.setValueAt("1 in 706", 2, 1);
table.setValueAt("1 in 360", 3, 1);
table.setValueAt("1 in 12,245", 4, 1);
table.setValueAt("1 in 19,088", 5, 1);
table.setValueAt("1 in 648,976", 6,1);
table.setValueAt("1 in 5,153,633", 7, 1);
table.setValueAt("1 in 175,223,510", 8, 1);
for(int i = 0; i < 10; i++)
{
table.setRowHeight(i, table.getRowHeight(i) + 10);
}
for(int i = 0; i < columnNames.length; i++)
{
TableColumn column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(column.getPreferredWidth() + 80);
}
}
Here is the main class with the JPanel that is attempting to display my LotteryTable.
public class LotteryDisplay
{
private JFrame display;
private JPanel panel;
private LotteryTable table;
private static JCheckBox powerPlay;
public LotteryDisplay()
{
display = new JFrame("Powerball");
panel = new JPanel();
table = new LotteryTable();
powerPlay = new JCheckBox("Power Play");
panel.setPreferredSize(new Dimension(800, 300));
panel.add(powerPlay);
//JTableHeader header = table.getTableHeader(); //Not important to problem
//panel.add(header);
panel.add(table);
display.getContentPane().add(panel, BorderLayout.CENTER);
display.pack();
display.setVisible(true);
}

LotteryTable extends JTable, but then creates another JTable internally to itself which is never added to the any component capable of displaying it.
As to your second question...this arguable. I see no particular benefit in extending a JTable for the functionality you are adding. This could just as easily be achieved using a static configuration method which is passed a JTable
Working Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class LotteryTable {
public static void main(String[] args) {
new LotteryTable();
}
public LotteryTable() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTable table = new JTable();
configureLotteryTable(table);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static final String[] COLUMN_NAMES = {"Powerball Combos", "Odds of Winning", "Payout", "Number of Wins", "Win Frequency"};
public static void configureLotteryTable(JTable table) {
DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0) {
#Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 0:
clazz = ImageIcon.class;
break;
default:
clazz = String.class;
break;
}
return clazz;
}
};
table.setModel(model);
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 55"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 111"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 706"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 360"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 12,245"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 19,088"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 648,976"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 5,153,633"});
model.addRow(new Object[]{new ImageIcon(LotteryTable.class.getResource("/icons/Powerball.png")), "1 in 175,223,510"});
}
}
I would spend some more time reading through How to use Tables to freshen up on some of the concepts ;)

Whatever you're trying to do with the inner
JTable, you should be doing on the parent LotteryTable.
For illustration purposes, I replaced the reference to table with this:
public class LotteryTable extends JTable {
private static final String[] COLUMN_NAMES = {
"Powerball Combos",
"Odds of Winning",
"Payout",
"Number of Wins",
"Win Frequency" };
public LotteryTable() {
super(new DefaultTableModel(COLUMN_NAMES, 9));
tableSetup();
setVisible(true);
}
#Override
public Class<?> getColumnClass(int column) {
if (column == 0)
return ImageIcon.class;
else
return String.class;
}
private void tableSetup() {
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
this.setDefaultRenderer(String.class, dtcr);
ImageIcon p = new ImageIcon("Icons/Powerball.png");
ImageIcon w1p = new ImageIcon("Icons/WhiteplusPowerball.png");
ImageIcon w2P = new ImageIcon("Icons/2WhitePlusPowerball.png");
ImageIcon w3P = new ImageIcon("Icons/3WhitePlusPowerball.png");
ImageIcon w4P = new ImageIcon("Icons/4WhitePlusPowerball.png");
ImageIcon w5P = new ImageIcon("Icons/5WhitePlusPowerball.png");
ImageIcon w3 = new ImageIcon("Icons/3White.png");
ImageIcon w4 = new ImageIcon("Icons/4White.png");
ImageIcon w5 = new ImageIcon("Icons/5White.png");
this.setValueAt(p, 0, 0);
this.setValueAt(w1p, 1, 0);
this.setValueAt(w2P, 2, 0);
this.setValueAt(w3, 3, 0);
this.setValueAt(w3P, 4, 0);
this.setValueAt(w4, 5, 0);
this.setValueAt(w4P, 6, 0);
this.setValueAt(w5, 7, 0);
this.setValueAt(w5P, 8, 0);
this.setValueAt("1 in 55", 0, 1);
this.setValueAt("1 in 111", 1, 1);
this.setValueAt("1 in 706", 2, 1);
this.setValueAt("1 in 360", 3, 1);
this.setValueAt("1 in 12,245", 4, 1);
this.setValueAt("1 in 19,088", 5, 1);
this.setValueAt("1 in 648,976", 6, 1);
this.setValueAt("1 in 5,153,633", 7, 1);
this.setValueAt("1 in 175,223,510", 8, 1);
for (int i = 0; i < 10; i++) {
this.setRowHeight(i, this.getRowHeight(i) + 10);
}
for (int i = 0; i < COLUMN_NAMES.length; i++) {
TableColumn column = this.getColumnModel().getColumn(i);
column.setPreferredWidth(column.getPreferredWidth() + 80);
}
}
}

I'd rather use a JFrame or JDialogand place a JPanel to display your JTable.

Related

How to change the contents of JComboBox based on a condition?

I'm relatively new to OOP and learning. I'm stuck in figuring out how do I possibly change the contents of my pane.
What I want to happen is If I click a different unit, the contents of the two pane would be changed according to the unit I chose.
Like this:
1 2 3
Here's a gist of my code:
private Container c;
private JTextField t1;
private JTextField t2;
private JButton b1;
String[] choicelen = {"meter", "kilometer", "centimeter", "millimeter", "mile", "yard", "foot"};
private JComboBox clen;
String[] choicelen1 = {"meter", "kilometer", "centimeter", "millimeter", "mile", "yard", "foot"};
private JComboBox clen1;
String[] choicetem = {"celsius", "kelvin", "fahrenheit"};
String[] choicetem1 = {"celsius", "kelvin", "fahrenheit"};
String[] choicearea = {"acre", "hectare", "sq mile", "sq yard", "sq foot", "sq inch"};
String[] choicearea1 = {"acre", "hectare"};
String[] choicevol = {"liter", "milliliter", "gallon", "quart", "pint", "cup", "fluid ounce"};
String[] choicevol1 = {"liter", "milliliter", "gallon", "quart", "pint", "cup", "fluid ounce"};
String[] choicewt = {"gram", "kilogram", "milligram", "metric ton", "pound", "ounce", "carrat"};
String[] choicewt1 = {"gram", "kilogram", "milligram", "metric ton", "pound", "ounce", "carrat"};
String[] choicetime = {"second", "millisecond", "minute", "hour", "day", "week", "month", "year"};
String[] choicetime1 = {"second", "millisecond", "minute", "hour", "day", "week", "month", "year"};
String[] choices = {"Length", "Temperature", "Area", "Volume", "Weight", "Time"};
private JComboBox c3;
Introduction
The OP's code is not a minimal reproducible example.
So, I went ahead and created the following GUI.
I only coded the conversions for length and temperature. I'm leaving the rest as an exercise for the OP.
Explanation
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
When I create a Swing GUI, I use the model-view-controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time.
The model is the most important part of any Swing application. A good model makes coding the view and the controllers so much easier.
A Swing model is made up of one or more plain Java getter/setter classes.
A Swing view is made up of one JFrame and as many JPanels and JDialogs as necessary.
A Swing controller is an Action or Listener that modifies the model and updates the view.
A Swing application usually has multiple controller classes.
Model
I created two model classes for this application.
The Measurement class holds a text String, a multiplier, and an adder.
Let's take the formulas for temperature conversion.
f = (c * 9/5) + 32
c = (f - 32) / 9/5
The general formula for any measurement conversion is
to value = (from value * multiplier) + adder
So, for the lengths, I converted the from value to millimeters and converted millimeters to the to value. I did a similar thing for the temperatures, where I converted the from value to celsius and converted celsius to the to value.
This way, I cut down on the code necessary to do the conversions. All the OP has to do is plug in the rest of the multipliers and adders in the UnitConversionModel class.
The UnitConversionModel class holds a Map with a String key and a List<Measurement> object. This Map allows me to easily fill the JComboBoxes and gives me the values for the conversions.
View
I generated a view based loosely on the OP's pictures. The model made constructing the view simpler.
Controller
I coded two controller classes.
The ComboBoxListener class fills in the from conversion units and the to conversion units in the conversion units JComboBoxes.
The ButtonListener class does the unit conversion.
Code
Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class UnitConversionTool implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new UnitConversionTool());
}
private JComboBox<Measurement> fromMeasurementComboBox,
toMeasurementComboBox;
private JComboBox<String> measurementTypeComboBox;
private JTextField fromMeasurementField, toMeasurementField;
private UnitConversionModel model;
public UnitConversionTool() {
this.model = new UnitConversionModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Unit Conversion Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(0, 5, 5, 5);
String[] measurementTypes = model.getMeasurementTypes();
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 0;
measurementTypeComboBox = new JComboBox<>(measurementTypes);
String measurementType = measurementTypes[measurementTypes.length - 1];
measurementTypeComboBox.setSelectedItem(measurementType);
measurementTypeComboBox
.addActionListener(new ComboBoxListener(this, model));
panel.add(measurementTypeComboBox, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.gridy++;
gbc.weightx = 1.0;
panel.add(new JLabel("From"), gbc);
Measurement[] measurementUnits = model
.getMeasurementList(measurementType);
gbc.gridx++;
fromMeasurementComboBox = new JComboBox<>(measurementUnits);
panel.add(fromMeasurementComboBox, gbc);
gbc.gridx++;
fromMeasurementField = new JTextField(10);
panel.add(fromMeasurementField, gbc);
gbc.gridx++;
panel.add(new JLabel("to"), gbc);
gbc.gridx++;
toMeasurementComboBox = new JComboBox<>(measurementUnits);
panel.add(toMeasurementComboBox, gbc);
gbc.gridx++;
toMeasurementField = new JTextField(10);
toMeasurementField.setEditable(false);
panel.add(toMeasurementField, gbc);
gbc.gridwidth = 6;
gbc.gridx = 0;
gbc.gridy++;
JButton button = new JButton("Convert");
button.addActionListener(new ButtonListener(this, model));
panel.add(button, gbc);
return panel;
}
public JComboBox<Measurement> getFromMeasurementComboBox() {
return fromMeasurementComboBox;
}
public JComboBox<Measurement> getToMeasurementComboBox() {
return toMeasurementComboBox;
}
public JComboBox<String> getMeasurementTypeComboBox() {
return measurementTypeComboBox;
}
public JTextField getFromMeasurementField() {
return fromMeasurementField;
}
public JTextField getToMeasurementField() {
return toMeasurementField;
}
public class ComboBoxListener implements ActionListener {
private final UnitConversionTool view;
private final UnitConversionModel model;
public ComboBoxListener(UnitConversionTool view,
UnitConversionModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
String selectedMeasurementType = (String) view
.getMeasurementTypeComboBox().getSelectedItem();
Measurement[] measurementUnits = model
.getMeasurementList(selectedMeasurementType);
int count = view.getFromMeasurementComboBox().getItemCount();
for (int index = count - 1; index >= 0; index--) {
view.getFromMeasurementComboBox().removeItemAt(index);
view.getToMeasurementComboBox().removeItemAt(index);
}
for (Measurement m : measurementUnits) {
view.getFromMeasurementComboBox().addItem(m);
view.getToMeasurementComboBox().addItem(m);
}
}
}
public class ButtonListener implements ActionListener {
private final UnitConversionTool view;
private final UnitConversionModel model;
public ButtonListener(UnitConversionTool view,
UnitConversionModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
Measurement fromMeasurement = (Measurement) view
.getFromMeasurementComboBox().getSelectedItem();
Measurement toMeasurement = (Measurement) view
.getToMeasurementComboBox().getSelectedItem();
double fromValue = Double
.valueOf(view.getFromMeasurementField().getText());
double toValue = (fromValue + fromMeasurement.getAdder())
* fromMeasurement.getMultiplier();
toValue = toValue / toMeasurement.getMultiplier()
- toMeasurement.getAdder();
String text = String.format("%.2f", toValue);
view.getToMeasurementField().setText(text);
}
}
public class UnitConversionModel {
private final Map<String, List<Measurement>> measurementMap;
private final Measurement[] lengthMeasurements = {
new Measurement("meter", 1000, 0),
new Measurement("kilometer", 1_000_000, 0),
new Measurement("centimeter", 10, 0),
new Measurement("millimeter", 1, 0),
new Measurement("mile", 1.609344e+6, 0),
new Measurement("yard", 914.4, 0),
new Measurement("foot", 304.8, 0) };
private final Measurement[] temperatureMeasurements = {
new Measurement("celsius", 1, 0),
new Measurement("kelvin", 1, -273.15),
new Measurement("fahrenheit", 5.0 / 9.0, -32) };
private final Measurement[] areaMeasurements = {
new Measurement("acre", 0, 0), new Measurement("hectare", 0, 0),
new Measurement("sq mile", 0, 0),
new Measurement("sq yard", 0, 0),
new Measurement("sq foot", 0, 0),
new Measurement("sq inch", 0, 0) };
private final Measurement[] volumeMeasurements = {
new Measurement("liter", 0, 0),
new Measurement("milliliter", 0, 0),
new Measurement("gallon", 0, 0), new Measurement("quart", 0, 0),
new Measurement("pint", 0, 0), new Measurement("cup", 0, 0),
new Measurement("fluid ounce", 0, 0) };
private final Measurement[] weightMeasurements = {
new Measurement("gram", 0, 0),
new Measurement("kilogram", 0, 0),
new Measurement("milligram", 0, 0),
new Measurement("metric ton", 0, 0),
new Measurement("pound", 0, 0), new Measurement("ounce", 0, 0),
new Measurement("carat", 0, 0) };
private final Measurement[] timeMeasurements = {
new Measurement("second", 0, 0),
new Measurement("millisecond", 0, 0),
new Measurement("minute", 0, 0), new Measurement("hour", 0, 0),
new Measurement("day", 0, 0), new Measurement("week", 0, 0),
new Measurement("month", 0, 0), new Measurement("year", 0, 0) };
private final String[] measurementTypes = { "Length", "Temperature",
"Area", "Volume", "Weight", "Time" };
private final Measurement[][] measurements = { lengthMeasurements,
temperatureMeasurements, areaMeasurements, volumeMeasurements,
weightMeasurements, timeMeasurements };
public UnitConversionModel() {
this.measurementMap = new LinkedHashMap<>();
for (int index = 0; index < measurementTypes.length; index++) {
String s = measurementTypes[index];
Measurement[] measurementUnits = measurements[index];
List<Measurement> measurementList = new ArrayList<>();
for (Measurement m : measurementUnits) {
measurementList.add(m);
}
measurementMap.put(s, measurementList);
}
}
public String[] getMeasurementTypes() {
return measurementTypes;
}
public Measurement[] getMeasurementList(String measurement) {
List<Measurement> measurementList = measurementMap.get(measurement);
return measurementList
.toArray(new Measurement[measurementList.size()]);
}
}
public class Measurement {
private final double adder, multiplier;
private final String text;
public Measurement(String text, double multiplier, double adder) {
this.text = text;
this.multiplier = multiplier;
this.adder = adder;
}
public double getAdder() {
return adder;
}
public double getMultiplier() {
return multiplier;
}
#Override
public String toString() {
return text;
}
}
}
I got it working by adding this code I found from a similar post:
c3 = new JComboBox<>(choices);
c.add(c3);
choose = new JComboBox<>(choicelen);
c.add(choose);
choose1 = new JComboBox<>(choicelen1);
c.add(choose1);
c3.addActionListener(new Listener());
class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (c3.getSelectedItem().equals("Length")) {
choose.setModel(new JComboBox<>(choicelen).getModel());
choose1.setModel(new JComboBox<>(choicelen1).getModel());
}
else if (c3.getSelectedItem().equals("Temperature")) {
choose.setModel(new JComboBox<>(choicetem).getModel());
choose1.setModel(new JComboBox<>(choicetem1).getModel());
}
else if (c3.getSelectedItem().equals("Area")) {
choose.setModel(new JComboBox<>(choicearea).getModel());
choose1.setModel(new JComboBox<>(choicearea1).getModel());
}
else if (c3.getSelectedItem().equals("Volume")) {
choose.setModel(new JComboBox<>(choicevol).getModel());
choose1.setModel(new JComboBox<>(choicevol1).getModel());
}
else if (c3.getSelectedItem().equals("Weight")) {
choose.setModel(new JComboBox<>(choicewt).getModel());
choose1.setModel(new JComboBox<>(choicewt1).getModel());
}
else if (c3.getSelectedItem().equals("Time")) {
choose.setModel(new JComboBox<>(choicetime).getModel());
choose1.setModel(new JComboBox<>(choicetime1).getModel());
}
}
}
Thank you guys!

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.

Error in removeRow in JButton [duplicate]

I want to delete all the rows of DefaultTable. I found two common ways to delete them on internet, but none of them works in my case because those methods does not exist in my DefaultTableModel. I wonder why. My code for using DefaultTableModel is
DefaultTableModel Table = (DefaultTableModel) Table.getModel();
One way to delete is
Table.removeRow(Table.getRowCount() - 1);
but this removerow method does not exist in my DefaultTableModel.
You can set the row count to 0.
setRowCount(0)
Quote from documentation:
public void setRowCount(int rowCount)
Sets the number of rows in the model. If the new size is greater than
the current size, new rows are added to the end of the model If the
new size is less than the current size, all rows at index rowCount and
greater are discarded.
But as you can't find removeRow either I suspect you haven't typed you model variable as DefaultTableModel perhaps, maybe just TableModel?
In that case cast your TableModel to DefaultTableModel like this:
DefaultTableModel model = (DefaultTableModel) table.getModel();
Why complicating simple things, but removes must be iterative,
if (myTableModel.getRowCount() > 0) {
for (int i = myTableModel.getRowCount() - 1; i > -1; i--) {
myTableModel.removeRow(i);
}
}
Code example
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.*;
public class RemoveAddRows extends JFrame {
private static final long serialVersionUID = 1L;
private Object[] columnNames = {"Type", "Company", "Shares", "Price"};
private Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50)},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
{"Sell", "Apple", new Integer(3000), new Double(7.35)},
{"Buy", "Nortel", new Integer(4000), new Double(20.00)}
};
private JTable table;
private DefaultTableModel model;
public RemoveAddRows() {
model = new DefaultTableModel(data, columnNames) {
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);
int firstRow = 0;
int lastRow = table.getRowCount() - 1;
int width = 0;
if (row == lastRow) {
((JComponent) c).setBackground(Color.red);
} else if (row == firstRow) {
((JComponent) c).setBackground(Color.blue);
} else {
((JComponent) c).setBackground(table.getBackground());
}
/*if (!isRowSelected(row)) {
String type = (String) getModel().getValueAt(row, 0);
c.setBackground("Buy".equals(type) ? Color.GREEN : Color.YELLOW);
}
if (isRowSelected(row) && isColumnSelected(column)) {
((JComponent) c).setBorder(new LineBorder(Color.red));
}*/
return c;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
JButton button1 = new JButton("Remove all rows");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (model.getRowCount() > 0) {
for (int i = model.getRowCount() - 1; i > -1; i--) {
model.removeRow(i);
}
}
System.out.println("model.getRowCount() --->" + model.getRowCount());
}
});
JButton button2 = new JButton("Add new rows");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Object[] data0 = {"Buy", "IBM", new Integer(1000), new Double(80.50)};
model.addRow(data0);
Object[] data1 = {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)};
model.addRow(data1);
Object[] data2 = {"Sell", "Apple", new Integer(3000), new Double(7.35)};
model.addRow(data2);
Object[] data3 = {"Buy", "Nortel", new Integer(4000), new Double(20.00)};
model.addRow(data3);
System.out.println("model.getRowCount() --->" + model.getRowCount());
}
});
JPanel southPanel = new JPanel();
southPanel.add(button1);
southPanel.add(button2);
add(southPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
RemoveAddRows frame = new RemoveAddRows();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Have you tried this
This works for me..
defaultTableModel.setRowCount(0);
Why don't you read the javadoc of DefaultTableModel?
public void removeRow(int row)
Removes the row at row from the model. Notification of the row being
removed will be sent to all the listeners.
public void setDataVector(Vector dataVector,
Vector columnIdentifiers)
Replaces the current dataVector instance variable with the new
Vector of rows, dataVector.
public void setRowCount(int rowCount)
Sets the number of rows in the model. If the new size is greater than
the current size, new rows are added to the end of the model If the
new size is less than the current size, all rows at index rowCount and
greater are discarded.
Simply keep removing the table model's first row until there are no more rows left.
// clean table
DefaultTableModel myTableModel = (DefaultTableModel) this.myjTable.getModel();
while (myTableModel.getRowCount() > 0) {
myTableModel.removeRow(0);
}
Ypu can write a method
public void clearTable()
{
getTableModel().setRowCount(0);
}
then call this method from the place that you need to clear the table

JLabel will not update/ display. Initialization Issue?

I know there are already many topics on this issue but I promise you I have exhausted the search.
At the opening of my application, the "ExampleGUI" window should display, when a Calendar button is clicked a Calendar Frame pops up and the user chooses a date, which is represented as a String. This string, along with some other information, is passed back to the ExampleGUI, as a new ExampleGUI. It will then go to the method updateDate, which should display the date that the user chose on the current frame, as a JLabel. However, no matter what I try, the JLabel will not display or will not update. I know about SetText, it's not currently included in my code but I have tried it and it doesn't work. I know it is passing the date correctly because System.out.println will work fine. If you have any help I will be forever grateful I am officially stumped.
UPDATE
Added the most pared down code I could make -- sorry the Calendar is so long, I couldn't take much out but I promise it is not the problem you just need it to run the GUI where the problem resides.
Thanks!
CODE:
Runner Class:
import java.awt.EventQueue;
public class Runner {
public Runner() {
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
GUI frame = new GUI();
frame.setVisible(true);
}
});
}
}
GUI Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame {
private JPanel contentPane;
public String newDate;
public String myStartEnd;
public String StartDate;
public JLabel lblFinalStartDate;
public JLabel lblFinalEndDate;
public JPanel panelSearchCriteria = new JPanel();
public GUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
GridBagConstraints gbc_panelSearchCriteria = new GridBagConstraints();
gbc_panelSearchCriteria.gridx = 0;
gbc_panelSearchCriteria.gridy = 0;
contentPane.add(panelSearchCriteria, gbc_panelSearchCriteria);
GridBagLayout gbl_panelSearchCriteria = new GridBagLayout();
panelSearchCriteria.setLayout(gbl_panelSearchCriteria);
JButton btnChooseSDate = new JButton("Choose Date");
btnChooseSDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String source = new String("Start");
Calndar startCal = new Calndar(source);
}
});
GridBagConstraints gbc_btnChooseSDate = new GridBagConstraints();
gbc_btnChooseSDate.gridx = 1;
gbc_btnChooseSDate.gridy = 1;
panelSearchCriteria.add(btnChooseSDate, gbc_btnChooseSDate);
}
public GUI(String str, String soE) {
this();
updateDate(str, soE);
}
public void updateDate(String d, String se) {
String tempdate = new String(d + "");
String answer = new String(se + "");
if (answer.equals("Start")) {
StartDate = new String(tempdate + "");
lblFinalStartDate = new JLabel(StartDate);
GridBagConstraints gbc_lblFinalStartDate = new GridBagConstraints();
gbc_lblFinalStartDate.insets = new Insets(0, 0, 0, 5);
gbc_lblFinalStartDate.gridx = 2;
gbc_lblFinalStartDate.gridy = 1;
this.panelSearchCriteria.add(lblFinalStartDate, gbc_lblFinalStartDate);
System.out.println(lblFinalStartDate.getText());
}else{
}
}
}
Calendar Class:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class Calndar extends JFrame {
private JPanel contentPane;
private JTable table;
public int realDay, realMonth, realYear, currentMonth, currentYear;
public JButton btnPrev = new JButton("<<");
public JButton btnNext = new JButton(">>");
public JLabel Monthlabel = new JLabel("");
public int returnedDAY, returnedMONTH, returnedYEAR;
public String FinalDate;
public Calndar(String SoE) {
setBounds(100, 100, 330, 430);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
GregorianCalendar cal = new GregorianCalendar();
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH);
realMonth = cal.get(GregorianCalendar.MONTH);
realYear = cal.get(GregorianCalendar.YEAR);
currentMonth = realMonth;
currentYear = realYear;
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.insets = new Insets(0, 0, 5, 5);
gbc_label.gridx = 1;
gbc_label.gridy = 0;
panel.add(Monthlabel, gbc_label);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 3;
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
panel.add(scrollPane, gbc_scrollPane);
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowHeight(35);
table.setCellSelectionEnabled(true);
table.setModel(new DefaultTableModel(
new Object[][] { { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, },
new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }));
scrollPane.setViewportView(table);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnChoose = new JButton("Select");
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date", "Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
GUI DS1 = new GUI(getFinalDate(), SoE);
dispose();
}
}
});
btnChoose.setMargin(new Insets(5, 20, 5, 20));
panel_1.add(btnChoose);
refreshCalendar(realMonth, realYear);
setVisible(true);
}
public void refreshCalendar(int M, int Y) {
int nod, som;
Monthlabel.setText("July");
GregorianCalendar cal = new GregorianCalendar(Y, M, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
table.setValueAt(null, i, j);
}
}
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = ((i + som - 2) % 7);
table.setValueAt(i, row, column);
}
}
public String returnDate(int r, int c) {
returnedYEAR = 2015;
returnedMONTH = 7;
returnedDAY = (int) table.getValueAt(r, c);
FinalDate = new String("" + returnedYEAR + "-" + returnedMONTH + "-" + returnedDAY);
return FinalDate;
}
public String getFinalDate(){
if(FinalDate.equals(null)){
String str = new String("None");
return str;
}else{
return FinalDate;
}
}
}
Your problem is here:
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date",
"Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
GUI DS1 = new GUI(getFinalDate(), SoE); // *****************
dispose();
}
}
});
You are creating a new GUI object, one completely distinct from the currently displayed GUI instance.
suggestions:
The new window should not be a JFrame but should be a modal JDialog. If it is a modal dialog, it will freeze the calling code from the point that it is set visible, and then that code will resume flow once the dialog is no longer visible.
Set this dialog visible from the original class, the GUI's ActionListener.
Don't have Calndar object change anything in GUI. Rather in its action listener store the selected date (if anything is selected) in a field, and dispose of the dialog.
Then the calling class, here GUI can query the Calndar object once it is no Calndar is longer visible, within GUI's select ActionListener, but after Calndar is set visible, and extract the selected date by calling a public getter method on the Calndar object.
Then GUI can use this information to update its visualized data.
Call revalidate and repaint after adding or removing components from a running GUI.
In the future, try to use only 1 file for your example program.
For example. Note in the code below major changes are commented with // !!:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.GregorianCalendar;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class GUI extends JFrame {
private JPanel contentPane;
public String newDate;
public String myStartEnd;
public String StartDate;
public JLabel lblFinalStartDate;
public JLabel lblFinalEndDate;
public JPanel panelSearchCriteria = new JPanel();
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
GridBagConstraints gbc_panelSearchCriteria = new GridBagConstraints();
gbc_panelSearchCriteria.gridx = 0;
gbc_panelSearchCriteria.gridy = 0;
contentPane.add(panelSearchCriteria, gbc_panelSearchCriteria);
GridBagLayout gbl_panelSearchCriteria = new GridBagLayout();
panelSearchCriteria.setLayout(gbl_panelSearchCriteria);
JButton btnChooseSDate = new JButton("Choose Date");
btnChooseSDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String source = new String("Start");
Calndar startCal = new Calndar(GUI.this, source); // !!
startCal.setVisible(true); // !!
String finalDate = startCal.getFinalDate();
updateDate(finalDate, source); // !!
}
});
GridBagConstraints gbc_btnChooseSDate = new GridBagConstraints();
gbc_btnChooseSDate.gridx = 1;
gbc_btnChooseSDate.gridy = 1;
panelSearchCriteria.add(btnChooseSDate, gbc_btnChooseSDate);
}
public GUI(String str, String soE) {
this();
updateDate(str, soE);
}
public void updateDate(String d, String se) {
String tempdate = new String(d + "");
String answer = new String(se + "");
if (answer.equals("Start")) {
StartDate = new String(tempdate + "");
lblFinalStartDate = new JLabel(StartDate);
GridBagConstraints gbc_lblFinalStartDate = new GridBagConstraints();
gbc_lblFinalStartDate.insets = new Insets(0, 0, 0, 5);
gbc_lblFinalStartDate.gridx = 2;
gbc_lblFinalStartDate.gridy = 1;
this.panelSearchCriteria.add(lblFinalStartDate, gbc_lblFinalStartDate);
System.out.println(lblFinalStartDate.getText());
revalidate(); // !!
repaint(); // !!
} else {
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
GUI frame = new GUI();
frame.setVisible(true);
}
});
}
}
class Calndar extends JDialog { // !!
private JPanel contentPane;
private JTable table;
public int realDay, realMonth, realYear, currentMonth, currentYear;
public JButton btnPrev = new JButton("<<");
public JButton btnNext = new JButton(">>");
public JLabel Monthlabel = new JLabel("");
public int returnedDAY, returnedMONTH, returnedYEAR;
public String FinalDate;
public Calndar(GUI gui, final String SoE) { // !!
super(gui, "Calndar Title", ModalityType.APPLICATION_MODAL); // !!
setBounds(100, 100, 330, 430);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
GregorianCalendar cal = new GregorianCalendar();
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH);
realMonth = cal.get(GregorianCalendar.MONTH);
realYear = cal.get(GregorianCalendar.YEAR);
currentMonth = realMonth;
currentYear = realYear;
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.insets = new Insets(0, 0, 5, 5);
gbc_label.gridx = 1;
gbc_label.gridy = 0;
panel.add(Monthlabel, gbc_label);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 3;
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
panel.add(scrollPane, gbc_scrollPane);
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowHeight(35);
table.setCellSelectionEnabled(true);
table.setModel(new DefaultTableModel(new Object[][] {
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, }, new String[] {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }));
scrollPane.setViewportView(table);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnChoose = new JButton("Select");
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date",
"Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
// !! GUI DS1 = new GUI(getFinalDate(), SoE);
dispose();
}
}
});
btnChoose.setMargin(new Insets(5, 20, 5, 20));
panel_1.add(btnChoose);
refreshCalendar(realMonth, realYear);
// setVisible(true);
}
public void refreshCalendar(int M, int Y) {
int nod, som;
Monthlabel.setText("July");
GregorianCalendar cal = new GregorianCalendar(Y, M, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
table.setValueAt(null, i, j);
}
}
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = ((i + som - 2) % 7);
table.setValueAt(i, row, column);
}
}
public String returnDate(int r, int c) {
returnedYEAR = 2015;
returnedMONTH = 7;
returnedDAY = (int) table.getValueAt(r, c);
FinalDate = new String("" + returnedYEAR + "-" + returnedMONTH + "-"
+ returnedDAY);
return FinalDate;
}
public String getFinalDate() {
if (FinalDate.equals(null)) {
String str = new String("None");
return str;
} else {
return FinalDate;
}
}
}
Also:
I wouldn't add a JLabel when adding the date in the main GUI. Rather I'd create a JLabel field, add it to the GUI initially, and then simply set its text when the need arises.

How to reset the JComboBox in JTable to the first value of the JComboBox

I'm working on a code in Java Swing. I have created a JComboBox in JTable. It's working :). But once I select a value and click on the save or cancel button, it has to reset to the default value (1st value in the combo box). I tried a lot of ways like combobox.setSelectedIndex(0). This isn't working.
Code:
String[] manTimeHr = { "00","01", "02", "03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
String[] manTimeMin = {"00","01", "02", "03","04","05","06","07","08","09","10","11","12","13", "14", "15","16","17","18","19","20","21","22","23","24","25", "26", "27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
String[][] data = {{"-select-","-select-"}};
String[] cols = {"Hrs","Mins"};
String[][] data1 = {{"-select-","-select-"}};
String[] cols1 = {"Hrs","Mins"};
JLabel manTimeStart = new JLabel("Start From",JLabel.LEFT);
STimeTbl = new JTable(data,cols);
hrsColumn=STimeTbl.getColumnModel().getColumn(0);
minsColumn=STimeTbl.getColumnModel().getColumn(1);
manSiteStimeHrCBx = new JComboBox(manTimeHr);
manSiteStimeHrCBx.setSelectedIndex(0);
hrsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeHrCBx));
manSiteStimeMinCBx = new JComboBox(manTimeMin);
manSiteStimeMinCBx.setSelectedIndex(0);
minsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeMinCBx));
JLabel manTimeEnd = new JLabel("End To",JLabel.LEFT);
ETimeTbl = new JTable(data1,cols1);
hrsColumn1=ETimeTbl.getColumnModel().getColumn(0);
minsColumn1=ETimeTbl.getColumnModel().getColumn(1);
manSiteEtimeHrCBx = new JComboBox(manTimeHr);
manSiteEtimeHrCBx.setSelectedIndex(0);
hrsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeHrCBx));
manSiteEtimeMinCBx = new JComboBox(manTimeMin);
manSiteEtimeMinCBx.setSelectedIndex(0);
minsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeMinCBx));
.
.
.
.
if("Save".equals(e.getActionCommand())) {
try{
mSHr = Integer.parseInt((String)manSiteStimeHrCBx.getSelectedItem());
mEHr=Integer.parseInt((String)manSiteEtimeHrCBx.getSelectedItem());
mSMin=Integer.parseInt((String)manSiteStimeMinCBx.getSelectedItem());
mEMin=Integer.parseInt((String)manServEtimeMinCBx.getSelectedItem());
}catch (Exception en){
System.out.println("Main Exception : "+ en);
return;
}
if(validateBlockTime(mSHr,mEHr,mSMin,mEMin) != true)
{
System.out.println("Enter valid Time");
return;
}
manSiteStimeHrCBx.setSelectedIndex(0);
manSiteStimeMinCBx.setSelectedIndex(0);
manSiteEtimeHrCBx.setSelectedIndex(0);
manSiteEtimeMinCBx.setSelectedIndex(0);
.
.
.
private static boolean validateBlockTime(int val3, int val4, int val5, int val6){
if(val4 > val3)
return true;
else if((val4 == val3) && (val6 > val5))
return true;
else
return false;
}
JTable tutorial contains description about Combo Box as an Editor
all data are stored in the XxxTableModel
all changes in the JTable view are described in Concepts: Editors and Renderers
then you have to know that in the XxxTableModel is stored only String value (or Double or Long or Integer or Icon, depends of value stored in ComboBoxModel) for Combo Box as an Editor
result is
quick code (sorry I'm so lazy) based on tutorial code
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class TableRenderDemo extends JPanel {
private static final long serialVersionUID = 1L;
private boolean DEBUG = false;
public TableRenderDemo() {
super(new BorderLayout(5, 5));
final JTable table = new JTable(new MyTableModel());
table.setRowHeight(18);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
initColumnSizes(table);
setUpSportColumn(table, table.getColumnModel().getColumn(2));
add(scrollPane);
JButton resetButton = new JButton("Reset to default");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.getModel().setValueAt("None of the above", i, 2);
}
}
});
add(resetButton, BorderLayout.SOUTH);
}
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel) table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
private void setUpSportColumn(JTable table, TableColumn sportColumn) {
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
private class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Object[][] data = {
{"Kathy", "Smith", "Snowboarding", new Integer(5), false},
{"John", "Doe", "Rowing", new Integer(3), true},
{"Sue", "Black", "Knitting", new Integer(2), false},
{"Jane", "White", "Speed reading", new Integer(20), true},
{"Joe", "Brown", "Pool", new Integer(10), false}
};
public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
#Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
System.out.println(getValueAt(row, col));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
output from AbstractTableModel, code line 135th.
run:
None of the above
None of the above
None of the above
None of the above
None of the above
BUILD SUCCESSFUL (total time: 37 seconds)

Categories