I am currently in the process of making a slots game.
I have a history feature implemented as such. In my class I have the following static variable
static String[][] figureHistoryArray = new String [1000][4];
Everytime a user presses a "spin" button in the GUI a method called slotSpin() is activated.
Within this method I have got
figureHistoryArray[turnCounter][0]= rollOne.getFigureName();
figureHistoryArray[turnCounter][1]= rollTwo.getFigureName();
figureHistoryArray[turnCounter][2]= rollThree.getFigureName();
In which each slot spin gets saved.
After that I display the data in the GUI
private JTable historyTable;
And in the method:
historyPanel = new JPanel();
historyPanel.setLayout( new BorderLayout() );
getContentPane().add(historyPanel );
// Create columns names
String columnNames[] = { "Slot 1", "Slot 2", "Slot 3", "Win/Loss" };
String[][] dataValues= TheBigA.figureHistoryArray;
// Create a new historyTable instance
historyTable = new JTable( dataValues, columnNames );
// Add the historyTable to a scrolling pane
this.scrollPanel = new JScrollPane( historyTable );
historyPanel.add(this.scrollPanel, BorderLayout.CENTER );
add(historyPanel);
Now my issue is whenever the user presses "New Game" the history from the previous game is still being displayed. How would I go about fixing this
Now my issue is whenever the user presses "New Game" the history from the previous game is still being displayed. How would I go about fixing this
Don't create any new Swing components.
Instead, when you start a new game you load the table with an empty TableModel:
table.setModel( new DefaultTableModel(columnNames, 0) );
Edit:
so how would I update my table model to refer to this new array?
So then you do something like:
historyArray = new String[1000, 4];
table.setModel( new DefaultTableModel(historyArray, columnNames);
However, you should NOT really do this. The data should be stored in the TableModel. You can dynamically add data to the model using
model.addRow(...);
When you want to save the data you can iterate through the TableModel to save the data.
Or if you read the JTable API, it suggests you use an XMLEncoder to save data. Check out this posting for a generic solution that you can use to save/load the data: How to write a JTable state with data in xml file using XMLEndcoder in java
Related
I was trying to write the GUI for my program. I have a Product class in which I store price and names of the products in an arraylist. I also have an Order arraylist which consists of the orders given to each waiter.I put all my products in a JComboBox and added an action listener to each to show the price of each product when clicked by updating the text of a JLable. Then there is a JSpinner to get the quantity of the products selected. And lastly there is an "Add" button that I wanted to use to update the Jtable with product name and its quantity and its total price while also adding that product to the arraylist of Orders. I have no idea how populate JTable and couldn't understand much from other answers because they were using netbeans. I thought of just using a simple JLabe but also I couldn't understand how to update the text and add a new line to the label after I select and add each product. Can you explain how I can achieve this? part of my code looks like this
box1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Product prod = (Product) box1.getSelectedItem();
price.setText(String.valueOf(prod.getSellingPrice()));
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int numbs = (Integer) spinner.getValue();
for (int i = 0; i <= numbs; i++) {
order.addProduct(prod);
}
JLabel label = new JLabel();
lists.add(label);
label.setText(prod.getName() + " " + numbs + " " + numbs * prod.getSellingPrice());
}
});
}
});
If I understand your question correctly, you want a JTable in your gui, which shows the orders (or other data possibly) if a button is clicked.
Firstable, I would advise you to check out
https://docs.oracle.com/javase/tutorial/uiswing/components/table.html
as they explain the use of the JTable very well.
Anyway, to answer your question:
Firstable, you have to create a table and add it to your gui:
//creating a new JTable without any data and one column 'Orders'
//you might wanna declare the JTable before that, since it will be referred to in the refresh() method
JTable table = new JTable(new String[][]{{""}}, new String[]{"Orders"});
//creating a scrollpane to put the table in, in case the table data exeeds the table
JScrollPane scrollPane = new JScrollPane();
//here you would e.g. set the bounds of the scrollpane etc
scrollPane.setBounds(x,y,w,h)
//setting the table in the scrollpane
scrollPane.setViewportView(table);
//adding the scrollpane to your contentPane
contentPane.add(scrollPane);
Now you want to refresh the table, if a button is pressed, so I would put a reference to the following method in the actionlistener of the button:
//the method to refresh the table containing the orders (or possibly other data)
void refresh(List<String> orders) {
//creating a new TableModel for the table
DefaultTableModel model = new DefaultTableModel();
//set the data in the model to the data that was given, new Object[]{0} points to the 1st column
model.setDataVector(getDataVector(data), new Object[]{"Orders});
//set the model of the table to the model we just created
table.setModel(model);
}
Since model.setDataVecor() takes rows and not columns as its first parameter, you have to make the list of data fitting as a data vector, for example with the following method:
Object[][] getDataVector(List<String> data){
Object[][] vector = new Object[data.size()][1];
for(int i=0; i<data.size(); i++){
vector[i][0] = data.get(i);
}
return vector;
}
Im using a JTable , loading on it a different data depending on the button pressed.
The problem is : when one of the data is loaded, if i try to load the other one, and pass ther mouse over the header or a cell, it updates the header/cell with the data from the first input, if there is data on the header/cell selected.
Any ideas on how to solve it? That's the code im using.
private static void setCompromissosTable(Object[][] data, Object[] header){
try{
compromissosTable.removeAll();
} catch(Exception e){
e.printStackTrace();
}
compromissosTable = new JTable(data, header);
compromissosTable.setRowSelectionAllowed(true);
// Make the entire row selectable, but not editable
int columnMax = compromissosTable.getColumnCount();
for(int column = 0; column < columnMax; column++){
Class<?> col_class = compromissosTable.getColumnClass(column);
compromissosTable.setDefaultEditor(col_class, null);
}
scrollPane = new JScrollPane(compromissosTable);
pane.add(scrollPane);
scrollPane.setBounds(btnAddCompromisso.getX(),
btnAddCompromisso.getHeight() + btnAddCompromisso.getY() + 5
, frame1.getWidth() - 20
, frame1.getHeight() - 20);
compromissosTable.revalidate();
compromissosTable.repaint();
compromissosTable.addMouseListener(new MouseAdapter() {}
//Change mouse behavior.
);
}
This is suspicious...
compromissosTable = new JTable(data, header);
//...
scrollPane = new JScrollPane(compromissosTable);
pane.add(scrollPane);
Basically, assuming that each time you want to switch data sets, you are calling this method, you are creating a new JTable and JScrollPane each time and then are adding it onto the UI...
What about the previous JTable?
Next is this...
scrollPane.setBounds(btnAddCompromisso.getX(),
btnAddCompromisso.getHeight() + btnAddCompromisso.getY() + 5
, frame1.getWidth() - 20
, frame1.getHeight() - 20);
This looks like you're using a null layout. Basically what it "looks" like is happening, is you're just stacking the JScrollPanes ontop of each other, which would explain, in part, the graphics glitches, as the components are actually been added at the same z-deepthness (essentially) and are competing with each other then they are updated.
Two simple answers...
Don't use null layouts. Sure they "seem" like a good idea, but they have a tendency to turn around and bite you in strange and wonderful ways which are hard to diagnose and fix. Use the layout management API which Swing was designed around
Update the JTables model instead of creating a new JTable/JScrollPane each time
See How to use tables and Laying Out Components Within a Container
I am developing an Inventory managemant System using Java Swing and Oracle. In that I have an Internal frame called Purchase.In this, when a user press ENTER button after filling up the form, data get inserted into actual table. But I want the data to be stored in a temporary table or temporarily in JTable until user press SAVE button. After pressing the SAVE button, the data from JTable or temporary table(may contain multiple rows) should get inserted into actual table. Please share your experience or idea on this.
"After pressing the SAVE button, the data from JTable or temporary table(may contain multiple rows) should get inserted into actual table. Please share your experience or idea on this."
Use a DefaultTableModel for adding the information into the JTable
String[] columnNames = { "Data 1", "Data 2", "Data 3 };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
Then you can gather the info from the form and add it as a row to the model
String data1 = textField1.getText();
String data2 = textField2.getText();
String data3 = textField3.getText();
model.addRow( new Object[] { data1, data2, data3 } );
When you want to save the data, just use DefualtTableModels
public Vector getDataVector() - Returns the Vector of Vectors that contains the table's data values. The vectors contained in the outer vector are each a single row of values.
Vector<Vector<String>> data = model.getDataVector();
Just iterate through the Vector using PreparedStatement and use of transaction
See DefaultTableModel API and How to Use Tables and Using PreparedStatement*
Store them as a List of data objects in memory. Once the user presses save, then write out that List of objects to the database.
I have a JFrame Form which has JTextFields, JCombobox etc. and I am able to receive those values to variables and now I want to add the received data to JTable in new row when user clicks Add or something like that.
I have created JTable using net-beans the problem is what would be the code to add data from those variable to the rows of table. A basic example would be appreciated. I have tried numerous example and have added the code to ActionListener of the JButton but nothing Happens.
The Examples I tried are. How to add row in JTable? and How to add rows to JTable with AbstractTableModel method?
Any Help would be appreciated.
Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder
Set the table column headers
Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
Click on the ... button to the right of the property model. A dialog should appear.
Set rows to 0, set the number of columns you want, and their names.
Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row
Right-click on the button and select Events -> Action -> actionPerformed
You should see code like the following auto-generated
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
The jTable1 will have a DefaultTableModel. You can add rows to the model with your data
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
String data1 = something1.getSomething();
String data2 = something2.getSomething();
String data3 = something3.getSomething();
String data4 = something4.getSomething();
Object[] row = { data1, data2, data3, data4 };
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
// clear the entries.
}
So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.
you can use this code as template please customize it as per your requirement.
DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();
list.add(textField.getText());
list.add(comboBox.getSelectedItem());
model.addRow(list.toArray());
table.setModel(model);
here DefaultTableModel is used to add rows in JTable,
you can get more info here.
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.
I am working on a project and I am stuck on this area. I am reading text from a file and I am saving it into an arraylist. the problem is the content from the file appears in one line of text in the jtable but i want each line to be displayed in rows. I am passing the data from another class and I know this is working because I can see the contents printed out in the console row after row . I have tried a few different ways but I've run out of ideas. Any help appreciated.
Below is the code I have wrote.
for (String item : helper.getItems() )
{
System.out.println(item);
storage.add(item);
}
JTable t1 = new JTable();
t1.setModel(new DefaultTableModel(
new Object[][]{
{storage.toString()}
},
new String[]{
"Tool Equipment"
}
));
storage.toString() will give you string representation of your ArrayList. What you want is probably List#toArray
The best way to add items to a JTable using the DefaultTableModel object is to utilize the .addRow method of the DefaulTableModel. You'll need to parse the storage string to deliminate the values you want placed into each row/col
For Example:
DefaultTableModel model=new DefaultTableModel();
// parsing of the storage obj, to get individual values for each col/row
// depending on the structure of storage a looping construct would be beneficial here
String col1= storage.substring(startindex, endindex);
String col2=storage.substring(startindex, endindex);
//add items to the model in a new row
model.addRow(new Object[] {col1, col2});
// if you used a loop to parse the data in storage, end it here
// add model to the table
t1.setModel(model);