Java GUI import textfile data to a JTable - java

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.

Related

Columns not displaying in TableView - java

I am trying to write a programm that displays the content of a table in a database in a javafx gui using a TableView. I have a generic gui that has an empty TableView in it. After you decide what table you want to display the application send the table name to the middleware which gets all the column names from the database and sends them bakc to the application.Then i loop over all the column names, generate a new TableColumn and add it to the TableView and call the refresh() method of TableView. Using table.getChidlren(); I can see that the columns were successfully added to the TableView, however they are not displayed in the JavaFX GUI whatsoever. It just keeps displaying "No columns in table". All the fx:ids and controller classes are correct too.
Here is my code:
public void loadTableContent(){
try (Socket client = new Socket(InetAddress.getLocalHost(), 667);
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(client.getInputStream())) {
System.out.println("Sending request");
oos.writeUTF(databaseTableComboBox.getSelectionModel().getSelectedItem().toString());
oos.flush();
System.out.println("reading from sever");
String[] columnNames = ois.readUTF().split(";");
System.out.println("Column names received");
for (String s: columnNames)
table.getColumns().add(new TableColumn(s));
table.refresh();
} catch (IOException e) {
e.printStackTrace();
}
}
I figured out what the problem was. I added the TableView in SceneBuilder, however I called table = new TableView(); in my Code which just erased the one from SceneBuilder. Thank you all for your help.

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

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!

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).

Writing String and Double values stored in Array to a file using BufferWriter

I have a simple question regarding how to write my object array data into a file
Using a buffered writer, I have had no joy and I need some help please.
Please excuse my lack of knowledge I have only just started learning Java.
Object[][] data = {
{"dd/mm/yyyy", new Double(5), new Boolean(false),
{"21/12/2013", new Double(5), new Boolean(false)};
}
String sDividendDate1 = (String)data[0][0];
Double dDividend1 = (Double)data[0][1];
try
{
FileWriter file = new FileWriter(NewCodeFile);
BufferedWriter buffer = new BufferedWriter(file);
buffer.write(sDividendDate1);
buffer.newLine();
**buffer.write(sDividend1); /*This is where the compiler does not like
[I think it is because I am trying to write a double variable into a char
text buffer?]**/
}
How do I write the double value stored in dDividend1 in the same file after
I have written sDividendDate1 into the same file.
Any help is always greatly appreciated.
Many thanks
Kind Regards
Stephen
Try String.valueOf(sDividend1)or Double.toString(...).
You might also want to check java.text.NumberFormat.
Stephen,
Based on your code above you have referenced an undeclared variable:
Object[][] data = {
{
{
"dd/mm/yyyy",
new Double(5),
new Boolean(false)
},
{
"21/12/2013",
new Double(5),
new Boolean(false)
}
};
String sDividendDate1 = (String)data[0][0];
Double dDividend1 = (Double)data[0][1];
try {
FileWriter file = new FileWriter(NewCodeFile);
BufferedWriter buffer = new BufferedWriter(file);
buffer.write(sDividendDate1);
buffer.newLine();
buffer.write(dDividend1); /* you had this as sDividend1 which was not declared */
} catch(Exception ex) {
//catch logic here
}
If you want to write Objects in a binary representation you should use an ObjectOutputStream

Categories