It downloads data from ThingSpeak and show in jtable. I create a 'refresh' button which will download latest data and show in existing gui table.
get the latest data...work
store in List/arrays...work
update the jtable...Nop
I have tried fireTableDataChanged, setModel, revalidate, invalidate and repaint but still doesn't update the table. What am I missing?
public class Menu{
protected static List<String> list_name = new ArrayList<>();
// .....(10 more like above)
private JFrame frame = new JFrame("Temp");
private List<String[]> records_data = new ArrayList<String[]>();
private JTable table;
private DefaultTableModel model;
private String[][] data2 = new String[list_channel_ID.size()][11];
String[] columnNames_records = {"Location"}; // skip 10 more items
protected Menu(){
// Jframe > Jtabbedpane > jtable( I skip all these codes)
//- Table(Records)
for(int i = 0; i < list_channel_ID.size(); i++){
records_data.add(new String[]{ list_name.get(i) });} // Load data from List to jtable require format, skip 10 items
//table = new JTable(records_data.toArray(new Object[][] {}), columnNames_records); // when 'model' is not use
model = new DefaultTableModel(records_data.toArray(new Object[][] {}), columnNames_records);
//model = new DefaultTableModel(data2, columnNames);
table = new JTable(model);
JMenuItem process_refresh = new JMenuItem("Refresh");
process_refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// Update the list
for(int i = 0; i < list_channel_ID.size(); i++){
records_data.add(new String[]{ list_name.get(i) }); // load from list again, skiped 10 item
}
model = new DefaultTableModel(records_data.toArray(new Object[][] {}), columnNames_records);
model.fireTableDataChanged();
//table.setModel(model);
table.revalidate();
//table.invalidate();
table.repaint();
}
});
}
}
Problem solve, I forgot to clear the list 'records_data' :|
I will leave it here if someone face the same problem and mind blown for 2 days like me
Working code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
public class Menu{
protected static List<String> list_name = List.of("AAA", "BBB", "CCC");
// .....(10 more like above)
private JFrame frame = new JFrame("Temp");
private List<String[]> records_data = new ArrayList<String[]>();
private List<String[]> result_data = new ArrayList<String[]>();
private JTable table, table2, table3;
private DefaultTableModel model;
private String[][] data2 = new String[3][11];
String[] columnNames_records = {"item A", "item B", "item C"}; // 10 more items
protected Menu(){
frame.setSize(1000, 600);
frame.setLayout(new GridLayout(2, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//- Back Panel
JPanel panel = new JPanel(null);
frame.add(panel);
JPanel tab_panel = new JPanel(new GridLayout());
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBounds(5, 100, 975, 500);
tabbedPane.add("Records", tab_panel);
frame.add(tabbedPane);
//- Table(Records)
for(int i = 0; i < 3; i++){
records_data.add(new String[]{ list_name.get(i) });
} // Load data from List to jtable require format, skiped 10 item
//table = new JTable(records_data.toArray(new Object[][] {}), columnNames_records);
model = new DefaultTableModel(records_data.toArray(new Object[][] {}), columnNames_records);
//model = new DefaultTableModel(data2, columnNames);
table = new JTable(model);
table.setRowHeight(20);
//- ScrollPane, allow scrolling if table too long
JScrollPane scrollPane = new JScrollPane(table);
tab_panel.add(scrollPane);
// Menu bar
JMenu menu_process = new JMenu("Process");
JMenuItem process_refresh = new JMenuItem("Refresh");
process_refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
records_data.clear();
list_name = List.of("DDD", "EEE", "FFF"); // Update the list, hardcode for now
//list_name.add("KKK");
for(int i = 0; i < 3; i++){
records_data.add(new String[]{ list_name.get(i) }); // load from list again, skiped 10 item
}
model = new DefaultTableModel(records_data.toArray(new Object[][] {}), columnNames_records);
//model.fireTableDataChanged();
table.setModel(model);
//table.revalidate();
//table.invalidate();
//table.repaint();
}
});
menu_process.add(process_refresh);
JMenuBar menu_bar = new JMenuBar();
menu_bar.add(menu_process);
frame.setJMenuBar(menu_bar);
frame.setVisible(true);
}
public static void main(String[ ] args) {
new Menu();
}
}
Related
I have a JTable that includes items from an ArrayList, however whenever I try to remove the contents of deleted row from the ArrayList I get an IndexOutOfBoundsException depending on the amount of rows I wanted to delete and their location. How would I go about solving this issue?
Runnable Code: http://pastebin.com/Nnrnxzdg
remove.addActionListener( e -> {
int k = 0;
int[] rows = table.getSelectedRows();
TableModel tm= table.getModel();
while(rows.length>0)
{
while(k<rows.length)
{
al.remove(table.getSelectedRow() + k);
k++;
}
((DefaultTableModel)tm).removeRow(table.convertRowIndexToModel(rows[0]));
rows = table.getSelectedRows();
}
table.clearSelection();
});
Basically, the moment you remove a row, all the indices change. So what you need to do, is make a copy of all the selected rows, but NOT the index, but the actual row value...
JTable table = getTable();
if (table.getSelectedRowCount() > 0) {
List<Vector> selectedRows = new ArrayList<>(25);
DefaultTableModel model = getModel();
Vector rowData = model.getDataVector();
for (int row : table.getSelectedRows()) {
int modelRow = table.convertRowIndexToModel(row);
Vector rowValue = (Vector) rowData.get(modelRow);
selectedRows.add(rowValue);
}
Now with this, you can calculate the indexOf any given object with the model and remove it...
for (Vector rowValue : selectedRows) {
int rowIndex = rowData.indexOf(rowValue);
model.removeRow(rowIndex);
}
}
without caring what the index of the value was.
The indexes change if you remove the rows from the start of the model.
One solution is to remove one row at a time, ten all the selected indexes are reset so you are always removing the proper index:
Here is an example showing how you might do this for a JList and a JTable:
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
import javax.swing.table.*;
public class ItemDeletion extends JPanel
{
private JList<String> list;
private JTable table;
public ItemDeletion()
{
setLayout( new BorderLayout(5, 5) );
String[] items =
{
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten"
};
// Add the list
DefaultListModel<String> listModel = new DefaultListModel<String>();
for (String item: items)
listModel.addElement( item );
list = new JList<String>( listModel );
JButton listDelete = new JButton( "Delete From List" );
listDelete.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
DefaultListModel model = (DefaultListModel)list.getModel();
int row = list.getSelectedIndex();
while (row != -1)
{
model.removeElementAt( row );
row = list.getSelectedIndex();
}
}
});
JPanel listPanel = new JPanel( new BorderLayout(5, 5) );
listPanel.add(new JScrollPane( list ), BorderLayout.CENTER);
listPanel.add(listDelete, BorderLayout.PAGE_END);
// Add the table
DefaultTableModel tableModel = new DefaultTableModel(0, 1);
List<String> tableItems = Arrays.asList( items );
Collections.shuffle( tableItems );
for (String item: tableItems)
{
System.out.println( item );
tableModel.addRow( new String[]{item} );
}
table = new JTable( tableModel );
table.setAutoCreateRowSorter(true);
((DefaultRowSorter)table.getRowSorter()).toggleSortOrder(0);
JButton tableDelete = new JButton( "Delete From Table" );
tableDelete.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
DefaultTableModel model = (DefaultTableModel)table.getModel();
int row = table.getSelectedRow();
while (row != -1)
{
int modelRow = table.convertRowIndexToModel( row );
model.removeRow( modelRow );
row = table.getSelectedRow();
}
}
});
JPanel tablePanel = new JPanel( new BorderLayout(5, 5) );
tablePanel.add(new JScrollPane( table ), BorderLayout.CENTER);
tablePanel.add(tableDelete, BorderLayout.PAGE_END);
add(listPanel, BorderLayout.LINE_START);
add(tablePanel, BorderLayout.LINE_END);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Multiple Item Deletion");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ItemDeletion(), BorderLayout.NORTH);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am doing this payroll project for school.
The idea is for the user to input the employee's name, work hour, hourly rate, and select department from the ComboBox.
There will display 3 buttons, "Add More", "Display Result", and "exit".
"Add More" button will store the input into several arryalist and set the textfield to blank to allow more input.
"Display Result" will generate a JTable at the bottom JPanel to display the employee's name, department, and weekly salary.
I am running into the problem of nothing shows up after hitting the "Display Result" button. Maybe I have misunderstand the purpose of the button event, but I am really confused right now. Please help!
Here is a photobucket directURL PrtSc of the UI, hope it helps.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class PayrollFrame extends JFrame
{
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame()
{
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new GridLayout(3,1));
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel);
add(buttonPanel);
add(outputPanel);
setVisible(true);
}
private void buildInputPanel()
{
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel()
{
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel()
{
outputPanel = new JPanel();
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][2]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Add More")
{
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
}
else if(e.getActionCommand()=="Display Result")
{
printData();
}
else if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString)
{
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if(tempHour<=40)
{
salary.add(Double.toString(tempHour * tempRate));
}
else
{
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Let's start with...
if (e.getActionCommand() == "Add More") {
Is not how you compare Strings in Java, you need to use the equals method instead, something like...
if ("Add More".equals(e.getActionCommand())) {
for example
Next you do...
add(inputPanel);
add(buttonPanel);
add(outputPanel);
which, when using a BorderLayout, adds each of the components to the default position within the BorderLayout, you need to provide position constraints for each component, otherwise strange things begin to happen, for example...
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(outputPanel, BorderLayout.SOUTH);
I just realised that you're using a GridLayout, personally, I think you'll get a better result from BorderLayout, but that's me
And then you create a new instance of resultTable and outputPanel, but you never add outputPanel to anything...
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][1]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
A better idea would be to create resultTable, wrap in a JScrollPane and add it to your screen.
When you want to "print" the data, create a new TableModel and apply it to the JTable
For example...
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
Take a look at How to Use Tables and How to Use Scroll Panes for more details
Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class PayrollFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
PayrollFrame frame = new PayrollFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame() {
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel);
add(outputPanel, BorderLayout.SOUTH);
setVisible(true);
}
private void buildInputPanel() {
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel() {
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
TableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if ("Add More".equals(e.getActionCommand())) {
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
} else if ("Display Result".equals(e.getActionCommand())) {
printData();
} else if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString) {
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if (tempHour <= 40) {
salary.add(Double.toString(tempHour * tempRate));
} else {
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Thanks for #MadProgrammer 's help! His reply helps me to fix many problems I have, and really tried to explain things to me. After consulting with my instructor, I have successfully compile and run my program by editing the printData method.
private void printData()
{
DefaultTableModel model = new DefaultTableModel(columnNames,name.size());
resultTable.setModel(model);
for(int i=0; i<name.size(); i++)
{
resultTable.setValueAt(name.get(i),i,0);
resultTable.setValueAt(department.get(i),i,1);
resultTable.setValueAt(salary.get(i),i,2);
}
}
I have written this simple program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class JcomboboxJtableDemo extends JPanel
implements ActionListener {
private DefaultTableModel tableModel;
JTable table = new JTable (tableModel);
private JScrollPane scrollpaneTable = new JScrollPane( table );
private JPanel PaneBottoniTabella = new JPanel( );
public JcomboboxJtableDemo() {
super(new BorderLayout());
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setSelectedIndex(4);
tableModel = CreateTableModel();
tableModel.insertRow( 0, new Object[] {"Header col1", ""} );
tableModel.insertRow( 0, new Object[] {petStrings[0], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[1], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[2], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[3], ""} );
tableModel.setValueAt("Header col2", 0, 1);
DefaultCellEditor editor = new DefaultCellEditor(comboBox);
table.getColumnModel().getColumn(0).setCellEditor(editor);
table.getColumnModel().getColumn(1).setCellEditor(editor);
//Lay out the demo.
add(comboBox, BorderLayout.PAGE_START);
add(table, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
private final DefaultTableModel CreateTableModel () {
DefaultTableModel modello = new DefaultTableModel( new Object[] { "Col1","Col2" }, 0 ) {
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
table.setModel(modello);
return modello;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new JcomboboxJtableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I you try to run it you will see that there is a problem in showing correctly the JComboBox components in the second column, in the first column the are correctly shown and you can see each selected item as set in the code, instead in the second column there are some problems: none on the relative cell.
Could you tell me why? How can I solve the problem?
Thanks
You're using the same JComboBox component for both ColumnModel columns which in turn share the same ComboBoxModel. Any change in the selected item from one column will be reflected in the other column. Create a second combobox
JComboBox comboBox2 = new JComboBox(petStrings);
...
table.getColumnModel().getColumn(1).setCellEditor(editor2);
so that any changes can occur independently in either column.
I have a code that generates a truth table for a given Boolean Expression. For example, consider a user-input expression of (A+B)+(C+D). I have a string array headers[] that will store all necessary headers for the truth table.
In this case, it would contain: "A", "B", "C", "D", "A+B", "C+D", "(A+B)+(C+D)"
Then the generated truth table (a 2d int array TruthTable[][]) will contain the following data:
0000000
1000101
0100101
1100101
0010011
1010111
0110111
1110111
0001011
1001111
0101111
1101111
0011011
1011111
0111111
1111111
So the first element of the headers[] array will correspond to the first column of TruthTable[][]. How do I dynamically generate a truth table (using JTable) considering these data?
Create JTable with DefaultTableModel and insert new rows to table model.
Tutorial for it JTable and Model
Simple example for table:
public class Example extends JFrame{
private JTable table;
private DefaultTableModel modelTable;
public Example(){
init();
}
private void init() {
table = new JTable();
table.setGridColor(Color.BLACK);
table.setAutoResizeMode(2);
modelTable = new DefaultTableModel(new Object[][]{}, new String[] {"A", "B", "C"});
table.setModel(modelTable);
Object[][] data = new Object[][]{{"1","2","3"},{"4","5","6"}};
for(int i =0;i<data.length;i++){
modelTable.addRow(data[i]);
}
}
public static void main(String... s){
Example p = new Example();
p.add(new JScrollPane(p.table));
p.pack();
p.setVisible(true);
}
}
#alex2410 has a point when he says to use DefaultTableModel.
If you have some problem with FormLayout, download the JGoodies Form or simple change the layout =)
Maybe that's what You're looking for:
ThruthTablePanel
public class ThruthTablePanel extends JPanel {
private JScrollPane scrollPane;
private JTable table;
/**
* Create the panel.
*/
public ThruthTablePanel() {
initComponents();
}
private void initComponents() {
String columnsLayout = "3dlu, default:grow, 3dlu";
String rowsLayout = "3dlu, default:grow, 3dlu";
setLayout(new FormLayout(columnsLayout, rowsLayout));
scrollPane = new JScrollPane();
add(scrollPane, "2, 2, fill, fill");
Object[] headers = new Object[] { "A", "B", "C",
"D", "A+B", "C+D",
"(A+B)+(C+D)" };
String[] results = new String[] { "0000000", "1000101", "0100101",
"1100101", "0010011", "1010111", "0110111", "1110111",
"0001011", "1001111", "0101111", "1101111", "0011011",
"1011111", "0111111", "1111111" };
DefaultTableModel model = new DefaultTableModel(new Object[][] {}, headers);
model.setRowCount(results.length);
table = new JTable(model);
for (int j = 0; j < results.length; j++) {
for (int i = 0; i < results[j].length(); i++) {
model.setValueAt(results[j].charAt(i), j, i);
}
}
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
}
public static void main(String[] args) {
JFrame frm = new JFrame();
frm.setContentPane(new ThruthTablePanel());
frm.setSize(new Dimension(400, 400));
// frm.pack();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
But, if you have your ThruthTable[][] filled, you can just pass it as a parameter to the model.
Other Solution
DefaultTableModel model = new DefaultTableModel(/* Here you put your ThruthTable Vector */, headers);
table = new JTable(model);
I know spacing JTable cells are pretty straight forward as shown below;
int gapWidth = 10;
int gapHeight = 5;
table.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
Spacing like this doesn't seems to affect the tables header. Is there a way to space the header with the same dimension?
Easiest way could be to set EmptyBorders to the JTableHeader inside the TableCellRenderer
The code above does my spacing, but the alignment of header and the actual row cell values looks slighly off - as a result of spacing only placed on cells but not the header.
I added a SSCCE (3mins 27seconds inc. uploading here)
from code
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class IntercellSpacingTableHeader {
private JFrame frame = new JFrame("Table Demo");
private String[] columnNames = {"String", "Integer", "Float", "Double"};
private Object[][] data = {
{"aaa", new Integer(12), new Float(12.15), new Double(100.05)},
{"bbb", new Integer(5), new Float(7.154), new Double(6.1555)},
{"CCC", new Integer(92), new Float(0.1135), new Double(3.1455)},
{"ddd", new Integer(12), new Float(31.15), new Double(10.05)},
{"eee", new Integer(5), new Float(5.154), new Double(16.1555)},
{"fff", new Integer(92), new Float(4.1135), new Double(31.1455)}};
private TableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
private JTable table = new JTable(model);
public IntercellSpacingTableHeader() {
int gapWidth = 10;
int gapHeight = 5;
table.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
table.setRowHeight(20);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scroll = new JScrollPane(table);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scroll);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new IntercellSpacingTableHeader();
}
});
}
}