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);
Related
I am implementing a GUI using java in eclipse IDE. I want to display a table. This is how I implement the program
import java.awt.EventQueue;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.text.TabableView;
import com.model.FloorDetails;
public class ClientGUI {
private JFrame frame;
private ClientMain clientMain = new ClientMain();
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientGUI window = new ClientGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ClientGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
table = new JTable();
table.setBounds(67, 146, 1, 1);
frame.getContentPane().add(table);
executeTable();
}
public void executeTable() {
Object[] columns = new String[] {
"ID", "Room No", "Floor No", "CO2 Level", "Smoke Level", "Status"
};
ArrayList<FloorDetails> arrayList = clientMain.getSensors();
Object[][] data = new Object[arrayList.size()][6];
for(int i = 0; i < arrayList.size(); i++) {
data[i][0] = arrayList.get(i).getId();
data[i][1] = arrayList.get(i).getRoomNo();
data[i][2] = arrayList.get(i).getFloorNo();
data[i][3] = arrayList.get(i).getCo2Level();
data[i][4] = arrayList.get(i).getSmokeLevel();
data[i][5] = arrayList.get(i).getStatus();
}
table = new JTable(data,columns);
frame.setTitle("Sensor Details");
}
}
clientMain.getSensors() method retrieves all the data as expected(I tried printing on the console and everything printed). But when I run the program, it display an empty window.
I tried like this just to see if I am making a mistake when assigning the values to the 2D array but nothing changed
Object[][] data = {
{"a", "b", "c", "d", "e", "f"},
{"g", "h", "i", "j", "k", "l"}
};
Where I have done wrong in this program? Thanx in advance!
Well, one problem in your code is that, you are populating one table and adding another table to the frame. One approach to fix this would be
public JTable executeTable( ) { // Make this method return a JTable
Object[] columns = new String[] {
"ID", "Room No", "Floor No", "CO2 Level", "Smoke Level", "Status"
};
ArrayList<FloorDetails> arrayList = clientMain.getSensors();
Object[][] data = new Object[arrayList.size()][6];
for(int i = 0; i < arrayList.size(); i++) {
data[i][0] = arrayList.get(i).getId();
data[i][1] = arrayList.get(i).getRoomNo();
data[i][2] = arrayList.get(i).getFloorNo();
data[i][3] = arrayList.get(i).getCo2Level();
data[i][4] = arrayList.get(i).getSmokeLevel();
data[i][5] = arrayList.get(i).getStatus();
}
table = new JTable( data, columns);
return table;
}
And then change the initialize method to use this returned table
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = executeTable();
frame.add(table.getTableHeader(), BorderLayout.PAGE_START);
frame.add(table, BorderLayout.CENTER);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setTitle("Sensor Details");
frame.setVisible(true);
}
You don't need window.frame.setVisible(true); at the main method in this approach
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();
}
}
Hey I don't have enough knowledge on JTables, How to insert data in JTables by the way I entered the data in my table but I don't know why the column names not appear in my table.
Here's my code:
public class tab {
public tab() {
initComponents();
}
public void initComponents() {
JFrame fr = new JFrame("Score Card");
JScrollPane pane = new JScrollPane();
fr.setSize(500, 350);
JTable scoreTab = new JTable(5, 4);
DefaultTableModel model = new DefaultTableModel(1, 4);
// model.setColumnIdentifiers(new Object[]{"No","Name","Score","Date"});
scoreTab.setModel(new javax.swing.table.DefaultTableModel(
new Object[][] { { 1, 2, 2 },
}, new String[] { "Name", "Score", "Date" }));
pane.setViewportView(scoreTab);
fr.add(scoreTab);
fr.setLocationRelativeTo(null);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setVisible(true);
}
public static void main(String[] args) {
new tab();
}
}
add JScrollPane to the jframe
fr.add(pane);
you are directly adding jtable to the frame fr.add(scoreTab);
if you add a table without jscrollpane you have to add headers separately.
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();
}
});
}
}
I have a JTable with 5 rows at the time of design. Now i have to add more rows as i go dynamically. I am getting array out of bound exception error when i add more rows. How do i solve this issue ?
item_list = new javax.swing.JTable();
item_list.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"No.", "Description", "Cost"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.Float.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
item_list.getColumnModel().getColumn(0).setPreferredWidth(30);
item_list.getColumnModel().getColumn(1).setPreferredWidth(100);
item_list.getColumnModel().getColumn(2).setPreferredWidth(50);
jScrollPane2.setViewportView(item_list);
this works for me
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
public class Grow extends JFrame {
private static final Object[][] rowData = {{"Hello", "World"}};
private static final Object[] columnNames = {"A", "B"};
private JTable table;
private DefaultTableModel model;
public Grow() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
model = new DefaultTableModel(rowData, columnNames);
table = new JTable();
table.setModel(model);
c.add(new JScrollPane(table), BorderLayout.CENTER);
JButton add = new JButton("Add");
c.add(add, BorderLayout.SOUTH);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
model.addRow(rowData[0]);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
Grow g = new Grow();
g.setLocationRelativeTo(null);
g.setVisible(true);
}
}
I assume You have a table with six column.
Follow this code ,it will append a new row to already existing table
DefaultTableModel defaultModel = (DefaultTableModel) table.getModel();
Vector newRow = new Vector();
newRow.add("Total Amount Spend");
newRow.add(TotalAmt);
newRow.add(Apaid);
newRow.add(Bpaid);
newRow.add(Cpaid);
newRow.add(Dpaid);
defaultModel.addRow(newRow);
Where JTable table = new JTable(data, columnNames);
The DefaultTableModel has an addRow(...) method that you should be using.
If you need more help then post your SSCCE that demonstrates the problem.