JTable does not display values - java

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

Related

jtable not update after fireTableDataChanged, revalidate and repaint

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();
}
}

How to add a scrollpane in the frame window

I want to add a scrollpane in the frame window or comboPanel.
Below code, the guiFrame.add(scrollpane) is not working, why it is not working?
How can I add the scrollpane to comboPanel or the guiFrame?
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ExtraComboBox {
private int maxFields = 4; // The max number of fields allowed in the dialog
JComboBox fruits[] = new JComboBox[maxFields];
JPanel comboPanel;
JFrame guiFrame;
String[] valOptions3 = { "&" };
String[] valOptions2 = { "|->", "|=>" };
String[] valOptions1 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] valOptions0 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] fruitOptions1 = { "", "Delay1", "Delay2", "Delay3" };
JButton addField;
int count1 = 0;
JLabel dudel[] = new JLabel[maxFields];
JComboBox dude2[] = new JComboBox[maxFields];
String[] valOptions = { "Unknown", "0", "1" };
String[] s = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
private JLabel comboLbl;
public static void main(String[] args) {
new ExtraComboBox();
}
public ExtraComboBox() {
guiFrame = new JFrame();
// make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("ComboBox GUI");
guiFrame.setSize(350, 350);
// The first JPanel contains a JLabel and JCombobox
comboPanel = new JPanel();
addField = new JButton("Add Field");
addField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource().equals(addField)) {
if (count1 < maxFields) {
comboLbl = new JLabel("Select a relation:");
fruits[count1] = new JComboBox<String>(fruitOptions1);
MyItemListener2 actionListener2 = new MyItemListener2(count1);
fruits[count1].addItemListener(actionListener2);
// System.out.println("HI: " + fruits[count1].getParent());
dude2[count1] = new JComboBox<String>();
System.out.println("ADD FIELDS: " + count1);
comboPanel.add(comboLbl);
comboPanel.add(fruits[count1]);
comboPanel.add(dude2[count1]);
guiFrame.validate();
guiFrame.repaint();
count1++;
} else {
System.out.println("You reached the maximum of 4 fields.");
}
}
}
});
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.add(addField);
// The JFrame uses the BorderLayout layout manager.
// Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
// make sure the JFrame is visible
guiFrame.setVisible(true);
}
class MyItemListener2 implements ItemListener {
private int index;
public MyItemListener2(int pIndex) {
super();
index = pIndex;
}
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
System.out.println("COUNTER: " + index);
System.out.println(evt.getItem());
dude2[index].removeAllItems();
switch ((String) evt.getItem()) {
case "Delay1":
for (int i = 0; i < valOptions1.length; i++) {
dude2[index].addItem(valOptions1[i]); // dude1 = new JComboBox(valOptions1);
System.out.println(valOptions1[i]);
}
break;
case "Delay2":
for (int j = 0; j < valOptions2.length; j++) {
System.out.println(valOptions2[j]);
dude2[index].addItem(valOptions2[j]); // dude1 = new JComboBox(valOptions1);
}
break;
case "Delay3":
for (int j = 0; j < valOptions3.length; j++) {
System.out.println(valOptions3[j]);
dude2[index].addItem(valOptions3[j]); // dude1 = new JComboBox(valOptions1);
}
}
}
}
}
}
How can I add the scrollpane to comboPanel or the guiFrame?
You add the comboPanel to the JViewport of the JScrollPane and then you add the scroll pane to the JFrame.
//guiFrame.add(comboPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane( comboPanel );
guiFrame.add(scrollPane, BorderLayout.CENTER);
It is better to add the scrollpane to the CENTER, then it will get all the space available to the frame.

Fetch from external file and display in a JTable

Can someone tell me how to modify below program? Program's data is passed by object[][] - instead of that will just give file name which is having data should be print in a table.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
public SimpleTableDemo() {
super(new GridLayout(1,0));
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
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();
}
});
}
}
If I understood question correct, you can replace Object[][] data with something like this:
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
File file = new File("\\file path");
try{
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
}catch (Exception ex){
ex.printStackTrace();
System.out.println("File not found");
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
In this exemple, it will work if data in file is formatted as:
name, surname, sportage, is Vegetarian. However you can change that easily, but remember to also change symbol in brackets in line.split().
EDIT:
I don't fully understand what you want to achieve, however I would do it like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class Project {
private JScrollPane scrollPane;
private JFrame frame;
private JTable table;
public static void main (String[] args){
Project project = new Project();
project.createGUI();
}
public void createGUI(){
frame = new JFrame();
scrollPane = new JScrollPane();
JPanel panel = new JPanel();
JButton open = new JButton("Open");
open.addActionListener(new OpenListener());
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitListener());
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new CancelListener());
panel.add(open);
panel.add(submit);
panel.add(cancel);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.getContentPane().add(BorderLayout.SOUTH,panel);
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void createAndDisplayList(String[][] data){
String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};
table = new JTable(data, columnNames);
frame.setVisible(false);
frame.remove(scrollPane);
scrollPane = new JScrollPane(table);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
private class OpenListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
fileChooser.showOpenDialog(frame);
try{
BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
reader.close();
}catch (Exception ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "File not found", "Error", JOptionPane.ERROR_MESSAGE);
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
createAndDisplayList(data);
}
}
private class CancelListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
frame.remove(scrollPane);
scrollPane = new JScrollPane();
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
}
private class SubmitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(frame);
try{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()));
for(int i = 0; i<table.getRowCount(); i++){
for(int j = 0; j<table.getColumnCount(); j++){
System.out.println(i + "," + table.getRowCount());
bufferedWriter.write(table.getValueAt(i, j).toString() + ",");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
}catch (IOException ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame,"File not found","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
However be aware it is a primitive and amateur written code, but it works to some extent. You can open, change content and save file(submit), but you cannot add rows in table, you need to do it in .txt file (but you cannot leave any empty space at the end of file).
Anyway, I hope you will find something usufull here.

trouble with creating JTable to display data [closed]

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);
}
}

How to retrieve the "user input from other file" to display as table in JAVA?

Below are the example of codes to display the table but how is it to be done when I want to retrieve the information from the user input from other file?
package components;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
public SimpleTableDemo() {
super(new GridLayout(1,0));
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Rather than manually inputting each information, how can I retrieve the information from other file?
**Object[][] data = {
{"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe","Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black","Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White","Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown","Pool", new Integer(10), new Boolean(false)} };**
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
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();
}
});
}
}
You can write the information about users in a file in csv(comma separated values) format and then use OpenCSV to parse that file and construct the matrix or array that you use for display.
So, basically your question is how to retrieve the contents of a file into an Object[][]?
Assuming that your file has lines and the lines look like:
Kathy,Smith,Snowboarding,5,false
John,Doe,Rowing,3,true
that is a CSV file. To read CSV files, your best bet is to download openCSV
However, if you still want to do it yourself and your data is in a file called "data.csv" I would use a Scanner. Also, assuming you do not know about ArrayLists and stuff like that, here's some code that can get you going.
Scanner s = new Scanner(new File("data.csv"));
int count = 0;
while (s.hasNext())
count++;
// now count has the number of lines in the file and you know
// there are 5 attributes.
Object[][] data = new Object[count][5]
Scanner s1 = new Scanner(new File("data.csv"));
count = 0;
while(s1.hasNext()){
String[] fields = s1.next().split(",");
data[count][0] = field[0];
data[count][1] = fields[1];
data[count][2] = fields[2];
data[count][3] = new Integer(Integer.parseInt(fields[3]));
data[count][4] = new Boolean(fields[4].equals("true");
count++;
}
Lastly, beware of an indexOutOfBounds error that may happen if you leave empty lines at the beginning, between lines or one line blank at the end (i.e. the last line of your file is empty)

Categories

Resources