How do i set text in rows of a JTable? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm trying to make a program in java JFrame with a table.
I want to save my text from the rows.
I put the text in a text file and that is working.
But i want to get my text from my text file into my table.
I have tried a lot of things but nothing is working.
can somebody help pls?

'Hypothetically' if you stored the text in your file line by line, for example like this:
tester.txt:
Star Wars
Star Trek
The Lord of The Rings
Then you could read it in line by line and when you have read enough lines add a row to the table. In order to add a row to an existing table I believe you do need to use the Model, or if creating from fresh prepare the data beforehand and then create. Below is a rough example using the above txt file:
public class SO {
public static void main(String[] args) {
//Desktop
Path path = Paths.get(System.getProperty("user.home"), "Desktop", "tester.txt");
//Reader
try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))){
Vector<String> row = new Vector<String>();
//Add lines of file
int numOfCellsInRow = 3; //Num of cells we want
int count = 0;
while (count < numOfCellsInRow){
row.addElement(reader.readLine());
count++;
}
//Column names
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Column One");
columnNames.addElement("Column Two");
columnNames.addElement("Column Three");
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
rowData.addElement(row);
//Make table
JTable table = new JTable(rowData, columnNames);
//How you could add another row by drawing more text from the file,
//here I have just used Strings
//Source: http://stackoverflow.com/questions/3549206/how-to-add-row-in-jtable
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Darth Vader", "Khan", "Sauron"});
//Make JFrame and add table to it, then display JFrame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Two things to note, firstly I have used Vectors, but these are discouraged due I believe to speed issues so you may want to look into varying on these. The second and main issue is the text in the file. Only by knowing how you intend to store the text can we know how to read it back successfully into the table. Hopefully though this example can point you in the right direction.
EDIT
Regarding your re-posted code, firstly I made this final:
final Path path = Paths.get(System.getProperty("user.home"), "Desktop", "File.txt");
Then altered your listener method to take the text input based of the file you make by clicking the save button:
btnGetFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//This prevents exception
if(!Files.exists(path)){//If no file
JOptionPane.showMessageDialog(null, "File does not exist!");//MSg
return;//End method
}
/*changed this bit so that it reads the data and
* should then add the rows
*/
try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))){
String line;
while((line = reader.readLine()) != null){//Chek for data, reafLine gets first line
Vector<String> row = new Vector<String>();//New Row
row.addElement(line);//Add first line
int numOfCellsInRow = 3; //Num of cells we want
int count = 0;
//We only want 2 because we got the first element at loop start
while (count < (numOfCellsInRow - 1)){
row.addElement(reader.readLine());
count++;
}
model.addRow(row);//Add rows from file
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
Added comments to try and explain what is going on.
It worked for my by adding the rows from the file to the JTable. Hopefully it works for you now also!

Related

Java GUI import textfile data to a JTable

I am writing a program, for my assignment, which should get some user input data from GUI(jtextfield) to a textfile and then retrive those data from the textfile to another GUI(JTable).
I have some basic knowledge about the file handling and JAVA swing, and I get some problems now.
First of all, please let me tell what I have done now (code below).
appending the data
public void actionPerformed(ActionEvent ae) {
//once clicked the button write the file
Object[] cols = new Object[]{
model.getText(),
make.getText(),
year.getText()
};
try {
FileOutputStream fstream = new FileOutputStream("words.txt", true);
ObjectOutputStream outputFile = new ObjectOutputStream(fstream);
outputFile.writeObject(cols);
//bw.close();
outputFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Reading the data from the word file to Jtable
public class read extends JFrame {
JTable table = new JTable();
JScrollPane pane;
Object[] cols = null;
public read() throws ClassNotFoundException, IOException {
cols = new String[]{"c1", "c2", "c3",};
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setColumnIdentifiers(cols);
File f = new File("words.txt");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Object[] data = (Object[]) ois.readObject();
model.addRow(data);
pane = new JScrollPane(table);
pane.setBounds(100, 150, 300, 300);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
setSize(500, 500);
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
new read();
}
}
It's working now but it only retrive one piece of data from the file, I want it to show all the data added to the file.
My questions are:
My words file looks like different:
and I am not sure if it just me or it just what it should be? Because I am expecting that it should be exact what I write, so even the addrow(object) method is not working I can add row using getline.
(Important) Because I write multible different data to the words file(and its shown in the image above), but it only shows one.
I assume that is because I should add an array of objects to the table in read.java instead of just addrow(object) but i dont know how, I mean I dont know how to let the array recognise that there are a lot of objects in the words file. also, is it okay to write the data as object to the file and retrive them in the read.java, is it a proper way?
Can someone tell me how, thanks fore your help.
Please don't hesitate to ask if I didn't state it properly.

Auto Refresh in Swing (Jtable)

I wrote a code which is get text from text area and save to file after that get data from file and show at jtable but I want to do that automatically when I add a new text to file it should be automatically show at the jtable does any one can help me?
try {
BufferedReader br = new BufferedReader(new FileReader(new File ("Member.txt")));
Object [] row = {id, firstname, lastname, age};
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
Object[] tableLines = br.lines().toArray();
for(int i = 0; i < tableLines.length; i++)
{
String line = tableLines[i].toString().trim();
String[] dataRow = line.split(" ");
dtm.addRow(dataRow);
}
} catch (Exception ex) {
System.out.println(ex);
}
this code help me to show data from file at jtable.
Your starting point is: using a watch service to determine when that file changed on disk.
Then you have to read the whole file and figure what changed (for example by keeping a "copy" of all lines of the file in memory).
Then you extract the newly added lines and add them to your table model.

Storing 1D arrays inside 2D array from text file to jTable java

Hi I need to import a text file into a Jtable. I have to store each column into a separate array so I was thinking to create a 2D array for the table, and 1D array for each column inside. (9 columns, 20 rows total)
All i've managed to do so far is import the text file and display it in the Jtable.
The data types i have to use are int, string and double(or float) as I have to create as student table where their I.D numbers (int )names, address ect (string) and grades (double) will be shown and ill have to be able to do calculations with the grades.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// When the window is opened, the information from the text file will be loaded into the table (tblStudentDetails)
try {
BufferedReader br = new BufferedReader(new FileReader ("C:\\Users\\XXX\\NetBeansProjects\\StudentDetailsJava\\lib\\StudentDetails.txt"));
//Get the first line
//Get the columns name from the first line
// Set columns name to the tblStudentDetails model
String firstLine = br.readLine().trim(); // Reading the file line (row) of the text file
// while(firstLine !=null) {
String[] columnsName = firstLine.split("\t"); // The coloums are split by tab
DefaultTableModel model = (DefaultTableModel)tblStudentDetails.getModel();
model.setColumnIdentifiers(columnsName);
// Get lines from txt file
Object[] tableLines = br.lines().toArray();
// Extract data from lines
// Set data to tblStudentsData model
for (Object tableLine : tableLines) {
String line = tableLine.toString().trim();
String[] dataRow = line.split("\t");
{
model.addRow(dataRow);
}
}
br.close();
} catch (Exception ex) {
Logger.getLogger(StudentTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here's what I have so far, and before you all kill me, i've spent the past 3 days trying to get this to work and i've tried nearly every solution I can find on this site to no avail.
I've been able to create a 2D array but I haven't been able to actually make it work when reading the text file, or importing it to the Jtable. Someone help!
first year student so I'm definitely a newbie and my assignment is due soon, I cant move on without solving this!
thanks! - Mrs x
Also
The text file looks like this (separated by tab so the first row is too long, but it imports into the Jtable just fine)
enter image description here
try this code:
Scanner input = new Scanner(new File(FILE_NAME));
int rows = 0;
String[] columnsName = null;
if (input.hasNext()) {
columnsName = input.nextLine().split("\t");
} else {
return;
}
while (input.hasNextLine()) {
input.nextLine();
++rows;
}
String[][] a = new String[rows][columnsName.length];
input.close();
input = new Scanner(new File(FILE_NAME));
if (input.hasNextLine()) {
input.nextLine();
}
for (int i = 0; i < rows; i++) {
a[i] = input.nextLine().split("\t");
}
JTable jt = new JTable(a, columnsName);

Populating a JTable with parsed information

I am trying to populate a JTable with information taken from a website (namely price and item name). I have a class that asks the user to input a URL and scans the page for the price and item name as well as the URL. Currently it takes all the parsed information and stores it in three different text files, one for price, one for item name, and one for the URL. I am trying to populate a JTable containing three columns (item name, price, and URL) with this information but every time I scan a new page the text files are overwritten and the previous information is lost. I don't necessarily need the JTable to be populated via the text file, I just need it to somehow get the information. Here is some of my code.
public BestBuy (JFrame frame){
super (frame, "Best Buy URL", true);
setLayout (new FlowLayout());
label = new JLabel ("Enter Best Buy URL");
add (label);
url = new JTextField ("Enter URL Here", 40);
add (url);
submit = new JButton ("Submit");
add (submit);
event b = new event ();
submit.addActionListener (b);
}
public class event implements ActionListener{
public void actionPerformed (ActionEvent b){
try {
String datab = url.getText(); //perform your operation
datab = datab.trim();
datab = datab.toLowerCase();
Document document = Jsoup.connect(datab).get();
String amountb = document.select(".amount").first().text();
String nameb = document.select(".product-title").first().text();
FileWriter stream = new FileWriter ("C:\\Users\\Daniel\\Desktop\\price.txt");
BufferedWriter out = new BufferedWriter (stream);
out.write(amountb + "\n");
out.newLine();
out.close();
FileWriter stream1 = new FileWriter ("C:\\Users\\Daniel\\Desktop\\itemName.txt");
BufferedWriter out1 = new BufferedWriter (stream1);
out1.write(nameb + "\n");
out1.newLine();
out1.close();
FileWriter stream2 = new FileWriter ("C:\\Users\\Daniel\\Desktop\\url.txt");
BufferedWriter out2 = new BufferedWriter (stream2);
out2.write(datab + "\n");
out2.newLine();
out2.close();
}
catch (Exception ex) {
}
setVisible (false);
}
This class asks the user for a Best Buy URL and parses the given page for item name, and price then writes it to files on my desktop.
public FirstGui (){
setLayout (new FlowLayout ());
String[] columnName = {"Item Name", "Price", "URL"};
Object [] [] data = {
};
table = new JTable (data, columnName);
table.setPreferredScrollableViewportSize(new Dimension (500, 300));
table.setFillsViewportHeight (true);
JScrollPane scrollpane = new JScrollPane (table);
add (scrollpane);
Now I am trying to get that parsed information onto my JTable but I have no idea how to do so. I tried to do
public getdatab() {
return datab;
}
public getnameb() {
return nameb;
}
public getamountb() {
return amountb;
}
but all these strings are within a void so that did not work. As you can probably see I am quite new to java and this might have an obvious solution but I have been stuck on this for a few days and cant figure it out. Thank you.
I'm not sure exactly how your getting your data, but you want to do something like this. Since you're trying to write the data to three different files, I will assume the data is coming in from three different streams. Here's the thing though. For this to work, all the data needs to be in parallel, Meaning that the first item, should correspond to the first price and first url, and so on. If this is the case, you can do something like this.
Have three separate lists.
List<String> names = new ArrayList<String>();
List<String> prices = new ArrayList<String>();
List<String> urls = new ArrayList<String>();
Then for each item you were going to add to a file, add to the list instead.
Use a DefaultTableModel as the model of your JTable
String[] columnName = {"Item Name", "Price", "URL"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
table = new JTable(model);
Now you can just add rows, using the data from the lists. Use the method model.addRow(row), where row is an array of Objects
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
String price = prices.get(i);
String url = urls.get(i);
model.addRow(new Object[] { name, price, url });
}
That's all there is to it. The model will update the table for you dynamically. But remember, like I said, the data in the lists must be in sync with one another for you to get the desired result.
If you're getting data in one row at a time, instead of one column at a time, that makes it even easier. For each set of data, that comes in, just add it as a row like it did in step 5.

Is a text file in Java a GUI

Is it right to think that when you create a text file in Java, you are essentially creating a text file like the one that appears with programs like notepad?
I have a JComboBox menu with various selections. I also created a text file and had it so that the user selection will be written in the text file. So the question is, how can I have this text file that I've created to appear? (as a GUI or any other way...)
My Code:
static JFrame frame;
FileWriter f;
BufferedWriter bw;
int myAge;
String myStringAge;
for (int i = 1; i <= 100; ++i) {
ageList.add(i);
}
DefaultComboBoxModel modelAge = new DefaultComboBoxModel();
for (Integer i : ageList) {
modelAge.addElement(i);
}
JComboBox ageEntries = new JComboBox();
ageEntries.setModel(modelAge);
//Add ItemListener
ageEntries.addItemListener(new ageListener());
class ageListener implements ItemListener {
public void itemStateChanged(ItemEvent event){
myAge = (Integer) event.getItem();
myStringAge = Integer.toString(myAge);
try {
bw.write(myStringAge);
bw.close();
} catch (Exception e){
}
}
A text file is not a GUI. Use JTextArea to display text. Have a look at http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html
You can do so using JEditorPane. You might want to create a new JFrame for it. Don't forget to setContentType() to "text/plain". Then you can just create a FileReader for your file and pass it to the editor pane throught the read() method.
Start with Basic I/O. That should answer your question (and the next 9).

Categories