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);
Related
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
I have a vector of String type entries formed as:
Vector<String> nameLst = new Vector<String>();
nameLst.add("Jacob");
nameLst.add("Stacey");
[...etc]
I to not know the number of entries - hence the vector instead of array. I would like to be able to display those names in a tale (with possibility of editing). My problem is, that JTable uses only Vector but my implementation only uses a list (rather then a table)
I was trying to go through all the entries of nameLst and allocate then in a new vector:
Vector<Vector<String>> helper = new Vector<Vector<String>>
for (String nametmp : nameLst){
Vector<String> a = new Vector<String>();
a.add(nametmp);
helper.add((Vector<String>)a.clone())
}
However the table (while formated correct) remains empty. I would expect that the data should stay safe and not go out of scope since I'm cloning it into the helper vector.
Is there a way to get a Vector to populate a JTable?
EDIT: Example - I don't really have a minimum working example, but the relevant code is:
The Display (in the Gui class):
JPanel namPan;
JTable namTab
In the constructor:
namePan = new JPanel();
printNames() //method
public void printNames(){
Vector<String> label= new Vector<String>();
Vector<Vector<String>> helper = new Vector<Vector<String>>;
for(String nametmp :nameLst){
Vector<String> a = new Vector<String>();
a.add(nametmp);
helper.add((Vector<String>/*just a cast*/) a.clone());
}
label.add("Currently active:");
namTab = new JTable(helper, label);
namPan.add(new JScrollPane(namTab));
}
Afterwards I call the Gui Constructor, fill in the name list with some initial names and call the printNames() method.
I think the core problem is the mismatch of formats - The Vector looks like ['a' 'b' 'c'] wile it should be a column vector: [a] [b] [c]. or in other words be seen as 2d vector with one column and multiple rows.
EDIT2
Found it - Special thanks to Hovercraft Full Of Eels who pushed me to make a minimal working example. I could not find any critical differences between what He uploaded and what I made, however when I've made the minimum example - stripped all other gui elements and functionalities I saw the data!
What happened? I put some dimension restrictions on the window size and panel ratios (GridBagLayout) and the test strings were outside! When entire area was available to the table I could see the text. I decided to write that and look like a fool rather then shove it under the carpet and leave this post hanging.
i am trying to add an image that is in my database in a column in JTable
with a number and a code special to this image the problem is i got the number and the code but the image doesn't show i don't know why here is my code
String sql="SELECT id,chiffre,image FROM symbolique WHERE id BETWEEN 200 and 205";
try{
st=connexion.prepareStatement(sql);
res=st.executeQuery();
while(res.next()){
int j=0;
String [] code= new String[1000];
String [] chiffre1=new String[100];
code [j] = res.getString("id");
chiffre1[j] = Integer.toString(res.getInt("chiffre"));
Blob blob = res.getBlob("image");
is2 = new BufferedInputStream(blob.getBinaryStream());
Image raw = ImageIO.read(is2);
ImageIcon icon =new ImageIcon(raw);
Object [][] data = new Object[200][100];
data[j][1]= code [j];
data[j][2]= chiffre1[j];
data[j][3]=icon;
j++;
String title[] = {"image", "chiffre","code"};
DefaultTableModel model = new DefaultTableModel(data, title);
table.setModel(model);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);}
}
put Icon/ImageIcon to JTable better to the TableModel directly
you have to override getColumnClass for Icon/ImageIcon in XxxTableModel for showing this Object as image in the JTables view
for detailed informations (incl. working code examples) to read official Oracle tutorial - How to use Tables
This won't help solve the image problem but right now your code recreates the TableModel for every row in the ResultSet, which means you will only ever see one row of data.
Since you have looping code you need to create an empty DefaultTableModel before the loop starts.
Inside the loop you then use the addRow(...) method to add another row of data to the TableModel for every row in the ResultSet
When you finish the loop then you use the model to create the JTable.
Did you add any debug code? Did you attempt to display the width/height of the image to confirm that you are reading the image properly? Why don't you do a simple test that tries to read and display an image in a JLabel first since using a JTable is more complicated than using a JLabel. Then once you get that working you can apply the knowledge to using a JTable.
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.