Populating JTable with user input - java

so I've been having such a problem as for how to populate JTable with user input, i got table created but it just dosn't get the data from an object.
SportClub club = new SportClub();
String name = club.getName();
int points = club.getPoints();
int wins = club.getWins();
int defeats = club.getDefeats();
int draws = club.getDraws();
int goalsFor = club.getGoalsScored();
int goalsAgainst = club.getGoalsReceived();
int difference = goalsFor - goalsAgainst;
Object data[][] = {
{name, wins, draws, defeats, goalsFor, goalsAgainst,difference, points}
};
String column[] = {"Club Name", "Wins", "Draws", "Loses", "GF", "GA", "Goal Difference", "Total Points"};
JTable prTable = new JTable(data, column);
JFrame frame = new JFrame("Premier League Table");
JScrollPane scroll = new JScrollPane(prTable);
prTable.setFillsViewportHeight(true);
frame.add(scroll);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Feel like I should have used the for loop but just have a trouble where to place it.

Related

Storing hundreds of tables/models

I know this information is everywhere but its so vast its hard to choose the right method. So even pointing me to right place works as well.
I am developing software for a client where he inputs his stock trades and it outputs the various data into a table. There is no accessing stock data of any sort, it is all internal and just for his personal use.
What I am stuck on is he wants to be able to shuffle through Monday to Friday, or view inputted data from a year ago. So how would I store the daily table data.
Should I save the table's models to a file or a database? Perhaps there is a different method I am unaware of.
The tables are 10 columns wide have about a 900 rows long if that matters to anyone.
Edit*
To answer the request for more code here is what I have broken down.`
MainFrame() {
super("Stack Overflow Stock Software");
model.addColumn("Exchange");
model.addColumn("Inv/Sec");
model.addColumn("Name");
model.addColumn("Qty");
// model.addColumn("Fd");
model.addColumn("Average Cost");
model.addColumn("Market");
model.addColumn("Balance");
// model.addColumn("Interest");
model.addColumn("Today's PL");
model.addColumn("Total Pl");
// model.addColumn("Multiplier");
// model.addRow(data);
table = new JTable(model);
modelTotal.addColumn("Balance");
modelTotal.addColumn("Today PL");
modelTotal.addColumn("Total PL");
table2 = new JTable(modelTotal);
setLayout(new BorderLayout());
// JComboBox<String> comboBox = new JComboBox<>(exchangeStrings);
// sorter = new TableRowSorter<TableModel>(table.getModel());
JPanel panel1 = new JPanel();
text1 = new JTextField(5);
text1.setText("ABA");
text1.setHorizontalAlignment(SwingConstants.CENTER);
text2 = new JTextField(12);
text2.setText("1000");// quanity
text2.setHorizontalAlignment(SwingConstants.CENTER);
text3 = new JTextField(10);
text3.setText("10.00");// price
text3.setHorizontalAlignment(SwingConstants.CENTER);
button1 = new JButton("Buy");
button1.addActionListener(this);
button2 = new JButton("Sell");
button2.addActionListener(this);
JScrollPane scrollPane = new JScrollPane(table);
JScrollPane scrollPane2 = new JScrollPane(table2);
// sets table settings
table.setFillsViewportHeight(true);
table.getColumnModel().getColumn(0).setMaxWidth(80);
table.getColumnModel().getColumn(1).setPreferredWidth(80);
table.getColumnModel().getColumn(2).setPreferredWidth(180);
table.getColumnModel().getColumn(4).setPreferredWidth(24);
table.getColumnModel().getColumn(6).setPreferredWidth(24);
table.getColumnModel().getColumn(7).setPreferredWidth(24);
// table.getColumnModel().getColumn(9).setPreferredWidth(0);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
setCellsAlignment(table, SwingConstants.CENTER);
setCellsAlignment(table2, SwingConstants.CENTER);
// add panels/buttons/etc to page
add(panel1, BorderLayout.PAGE_START);
panel1.setPreferredSize(new Dimension(1280, 50));
add(scrollPane, BorderLayout.CENTER);
add(scrollPane2, BorderLayout.PAGE_END);
scrollPane2.setPreferredSize(new Dimension(1280, 50));
// add(scrollPane, BorderLayout.CENTER);
panel1.add(comboBox, BorderLayout.SOUTH);
panel1.add(text1, BorderLayout.SOUTH);
panel1.add(text3, BorderLayout.SOUTH);// price
panel1.add(text2, BorderLayout.SOUTH);
panel1.add(button1, BorderLayout.NORTH);
panel1.add(button2, BorderLayout.NORTH);
setMenuBar();
modelTotal.addRow(data2);
setExtendedState(MAXIMIZED_BOTH);
setMinimumSize(new Dimension(1280, 485));
setSize(640, 485);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void setMenuBar() {...}
/*Set the menu bar up*/
public static void setCellsAlignment(JTable table, int alignment) {
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(alignment);
TableModel tableModel = table.getModel();
for (int columnIndex = 0; columnIndex < tableModel.getColumnCount(); columnIndex++) {
table.getColumnModel().getColumn(columnIndex).setCellRenderer(rightRenderer);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {// if button 1 pressed to buy
purchaseMade = true;
// input data in data object for adding or combining.
String comboString = comboBox.getSelectedItem().toString();
String stringCombo = comboString;
data[0] = stringCombo;
data[1] = text1.getText();
data[2] = text1.getText(); // turn into long string
data[3] = text2.getText();// quanity
data[5] = text3.getText();// price
data[4] = text3.getText();// average market price
double String1 = Double.parseDouble(data[3].toString());
double String2 = Double.parseDouble(data[4].toString());
data[6] = String1 * String2;
double dataQuanity = Double.parseDouble(data[3].toString());
double dataPrice = Double.parseDouble(data[4].toString());
data[7] = dataQuanity * dataPrice * -1;
data[8] = dataQuanity * dataPrice * -1;
data[4] = Double.parseDouble(data[4].toString());
data[4] = df.format(data[4]);
data[5] = Double.parseDouble(data[5].toString());
data[5] = df.format(data[5]);
data[6] = Double.parseDouble(data[6].toString());
data[6] = df.format(data[6]);
data[7] = Double.parseDouble(data[7].toString());
data[7] = df.format(data[7]);
data[8] = Double.parseDouble(data[8].toString());
data[8] = df.format(data[8]);
// add data and continue on
model.addRow(data);
dataCount++;
combineData(model);
sortData(table);
}
if (e.getSource() == button2) {
purchaseMade = false;
// input data in data object for adding or combining.
data[0] = comboBox.getSelectedItem();// exchange
data[1] = text1.getText();// symbol
data[2] = text1.getText(); // turn into long string//name
data[3] = text2.getText();// quanity
data[4] = text3.getText();// average price
data[5] = text3.getText();// closing bid / market
data[9] = 1;
// data 5 can wait
double String1 = Double.parseDouble(data[3].toString());
double String2 = Double.parseDouble(data[4].toString());
data[6] = String1 * String2;
// pl
double dataQuanity = Double.parseDouble(data[3].toString());
double dataPrice = Double.parseDouble(data[4].toString());
data[7] = dataQuanity * dataPrice * -1;
data[8] = dataQuanity * dataPrice * -1;
// add data and continue on
dataCount++;
combineData(model);
sortData(table);
}
}
private void combineData(DefaultTableModel model2) {
/*This section of codes adds the new data to a table or combines it with a duplicate entry*/
}
private void sortData(JTable table) {...}
/*This is where I sort my table*/
private void calculateLowerData(DefaultTableModel lowerModel, DefaultTableModel dataModel) {...}
/* This is where I calculate a number not relevant to the question*/
private void printTable() {...}
/* This is where I print my data to a table */
}`
Chose a database that you're more familiar with, in preference Relational Database, and use the Date Time column as index for faster search
With a database is better because you will can get the data that you want specifying the parameters
If is to personal use only, you can choose a local database to the Operating System that you're using, like SQL Server, and make sure to perform backups
Hugs

Insert values from ArrayList into a JTable

public void populateJTable() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Object[] rowData = new Object[4];
TrackService ts = new TrackService();
ArrayList<Track> tracks = ts.jsonToTracks();
for (int i = 0; i < tracks.size(); i++) {
rowData[0] = tracks.get(i).getTrackName();
rowData[1] = tracks.get(i).getArtist();
model.addRow(rowData);
}
jTable1 = new JTable(model);
}
In my json file I have stored metadata of an mp3 file which stores 5 values. My 'jsonToTracks' method stores them in an ArrayList.
I'm trying to get 2 of the values (trackName and artist) from inside my ArrayList and display them in my JTable.
My JTable has 4 columns - Name, Artist, Key, Mood. I'm trying to store the trackName and Artist in their corresponding columns. The Key and Mood column should be blank and the Name and Artist fields should be populated.
I can't see what I'm doing wrong, can anyone help?
Maybe you should try, moving your rowData initialization inside for loop.
public void populateJTable() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
TrackService ts = new TrackService();
ArrayList<Track> tracks = ts.jsonToTracks();
for (int i = 0; i < tracks.size(); i++) {
Object[] rowData = new Object[4];
rowData[0] = tracks.get(i).getTrackName();
rowData[1] = tracks.get(i).getArtist();
model.addRow(rowData);
}
jTable1 = new JTable(model);
}
jTable1 = new JTable(model);
I suspect the problem is that you are creating a new JTable but you never add the table to the frame.
Instead you should use:
jTable1.setModel( model );
This will replace the data in the existing JTable was I assume you have already added to a JScrollpane that has been added to the frame.

This is my code to print the jtable on frame

I added MouseListener to select a particular row from table,the content of row is getting printed on console but I want to print this content on new frame what should I do for this.
I attached my code along with the screenshot of the table.
thanks for help.
This is my code.
final JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
cp.add(scrollPane,BorderLayout.CENTER);
frame.add(cp);
frame.setSize(300,300);
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==1){
JTable target = (JTable)e.getSource();
System.out.println(target);
int row = target.getSelectedRow();
System.out.println(row);
Object [] rowData = new Object[table.getColumnCount()];
Object [] colData = new Object[table.getRowCount()];
for(int j = 0;j < table.getRowCount();j++)
for(int i = 0;i < table.getColumnCount();i++)
{
rowData[i] = table.getValueAt(j, i);
System.out.println(rowData[i]);
}
}
}
});
}
First of all, if you make a graphical interface with swing, you can't use System.out.print.
You need to set every row in a Label and print it out that way. If it is a Label then you can select it with your mouse
In the Mouse Listener method, Call the new JFrame,
in that JFrame , put the Contents of selected Row to Constructor Parameters.
JFrame newframe=new JFrame("Selected Contents);
When you output the result (System.out.println(rowData[i]);) just create a new JFrame and place the text you want to output here :
...
JFrame secondFrame = new JFrame();
JPanel myPanel = new JPanel();
for(int j = 0;j < table.getRowCount();j++){
for(int i = 0;i < table.getColumnCount();i++){
rowData[i] = table.getValueAt(j, i);
JLabel label = new JLabel(rowData[i]);
myPanel.add(label);
}
}
secondFrame.add(myPanel);
secondFrame.setVisible(true);
....

How do you change Vector to ArrayList?

I am developing an application in Java and since Vector is obsolete I am required to change this to using ArrayList.
This is the relevant code that needs to be changed to ArrayList:
This is the "House" Class.
public Vector<Vector> getItems() {
Vector<Vector> data = new Vector<Vector>();
for (int i = 0; i < _itemList.size(); i++) {
Vector<String> row = new Vector<String>();
row.add(_itemList.get(i).getDecription());
row.add(String.valueOf(_itemList.get(i).getprice()));
data.add(row);
}
return data;
}
This is the GUI Class:
private void updateView() {
//Gets Rows and Columns from the House.class
Vector<Vector> rowData = _listener.getHouse().getItems();
Vector<String> columnNames = new Vector<String>();
columnNames.add("Product Name");
columnNames.add("Product Price(€)");
//Creates Shopping Cart and sets size + properties
table1 = new JTable(rowData, columnNames);
table1.setPreferredScrollableViewportSize(new Dimension(375, 325));
table1.setFillsViewportHeight(true);
//Adds ScrollPane to the container and sets the component position to center
JScrollPane scrollPane = new JScrollPane(table1);
centerPanel.add(scrollPane, BorderLayout.CENTER);
}
I need to entirely stop the usage of VECTOR and use ArrayList instead. Is there a simple way out? Any ways on how to replace this?
Vector<String> vector = new Vector<String>();
// (... Populate vector here...)
ArrayList<String> list = new ArrayList<String>(vector);
This is from here java vector to arraylist
This should do for the first one.
public List<List<String>> getItems() {
List<List<String>> data = new ArrayList<ArrayList<String>>();
for (int i = 0; i < _itemList.size(); i++) {
List<String> row = new ArrayList<String>();
row.add(_itemList.get(i).getDecription());
row.add(String.valueOf(_itemList.get(i).getprice()));
data.add(row);
}
return data;
}
The second is a little less trivial. You could start with something like this but I suspect using a TableModel would be a good step forward.
private void updateView() {
//Gets Rows and Columns from the House.class
List<List<String>> rowData = _listener.getHouse().getItems();
List<String> columnNames = new ArrayList<String>();
columnNames.add("Product Name");
columnNames.add("Product Price(€)");
//Creates Shopping Cart and sets size + properties
// **** Will not work - Probably better to use a TableModel.
table1 = new JTable(rowData, columnNames);
table1.setPreferredScrollableViewportSize(new Dimension(375, 325));
table1.setFillsViewportHeight(true);
//Adds ScrollPane to the container and sets the component position to center
JScrollPane scrollPane = new JScrollPane(table1);
centerPanel.add(scrollPane, BorderLayout.CENTER);
}

table with buttons

I want to create a column and install a button in this last column in this table.
public JPanel pinakas(String[] pinaka) {
int sr = 0;
//int ari8mos =0;
String[] COLUMN_NAMES = {"Κωδικός", "Ποσότητα", "Τιμή", "Περιγραφή", "Μέγεθος", "Ράτσα"};
//pio panw mporoume na pros8esoume ws prwto column to "#", wste na deixnei ton ari8mo ths ka8e kataxwrhshs
DefaultTableModel modelM = new DefaultTableModel(COLUMN_NAMES, 0);
JTable tableM = new JTable(modelM);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new JScrollPane(tableM), BorderLayout.CENTER);
Display disp = new Display();
while (pinaka[sr] != null) // !!!!tha ektupwsei kai mia parapanw "/n" logo ths kataxwrhshs prwtou h teleytaiou mahmatos
{
String[] temp5 = disp.lineDelimiter(pinaka[sr],6, "#");
Object[] doge = { temp5[0], temp5[1], temp5[2], temp5[3], temp5[4], temp5[5]};//edw mporoume sthn arxh na valoume to ari8mos gia na fainetai o ari8mos twn kataxwrhsewn
modelM.addRow(doge);
sr++;
//ari8mos++;
}
return mainPanel;
}
Table Button Column shows one possible solution.

Categories