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.
Related
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.
I have some java code that opens an excel sheet, adds auto filter to a group of columns, then saves and closes. The problem is that when a user opens the file and trys to sort smallest to largest or largest to smallest excel will freeze then crash. But if you first filter then you can sort with out issue and it does not freeze and crash.
private static void AddFilter()
{
//Adds filter to the rows in Column 2
try
{
FileInputStream fileIn = new FileInputStream("C:\\Users\\gria\\Desktop\\Fleet Manager Summary.xls");
HSSFWorkbook report = new HSSFWorkbook(fileIn);
Sheet sheet = report.getSheetAt(0);
sheet.setAutoFilter(CellRangeAddress.valueOf("A5:P5"));
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\gria\\Desktop\\Fleet Manager SummaryT.xls");
report.write(fileOut);
fileOut.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Thank you,
UPDATE:
After some experimenting I have updated the info and code since the original question was asked to better explain the problem.
Try changing
XSSFFormulaEvaluator.evaluateAllFormulaCells(report);
to
HSSFFormulaEvaluator.evaluateAllFormulaCells(report);
XSSFFormulaEvaluator.evaluateAllFormulaCells() works for XSSfWorkbook, but not for the HSSFWorkbook.
Documentation
Also,
you can edit your commented code to:
for(int i = 5; i < sheet.getLastRowNum(); i++)
{
Cell cell = sheet.getRow(i).getCell(6);
//I don't know if you have data in all of the cells,
//So I suggest you to evaluate null
if(cell != null && !cell.getStringCellValue().isEmpty())
{
cell.setCellValue(Double.valueOf(cell.getStringCellValue()).doubleValue());
}
}
I am creating a little GUI for a "movie manager" with Java and Swing.
I have a class MovieTableModel that extends AbstractTableModel and has the data for the rows of the table in an Object[][]data.
A second class MovieUI manages the JFrame and well, the GUI in general.
The last class MovieManager is actually just a main function to create an instance of movieui and make it visible.
Now my problem is that by now, data is "saved" in my code. I want it to be able to be loaded and saved. If there is no save-file, one should be created and I should be able to add or delete rows of it (the actionlisteners are already set up, I just need a way to handle the file).
So the GUI looks like this:
MovieManager
This is kinda what I tried:
File tabledata = new File("tabledata.class");
if (!tabledata.exists()) {
try {
tabledata.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
tabledata.
FileInputStream in = new FileInputStream("tabledata.class");
ObjectInputStream input = new ObjectInputStream(in);
Object data = input.readObject();
System.out.print(data);
Both didn't work - I think I do understand how this works in general, but I don't know how to make it to the data in my table, especially as it is saved as an Object[][] but the file is an Object.
And if that works out - how can I add or delete single rows?
Thanks for your help in advance! :)
If you serialize you tablemodel or the object that backs your tablemodel, then you can read it later and restore it to the JTable.
When you read the object again from the ObjectInputStream, I think you are missing the cast to the right type you are saving:
FileInputStream in = new FileInputStream("tabledata.class");
ObjectInputStream input = new ObjectInputStream(in);
Object[][] data = (Object[][])input.readObject();
After you create new file you need to write the data using ObjectOutputStream and then read it with ObjectInputStream.
Object[][] data;
//save
File tabledata = new File("tabledata.dat"); //I wouldn't use class extension (class is for compiled Java)
//creation of file omitted
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tabledata));
out.writeObject(data);
out.close();
//load
ObjectInputStream in = new ObjectInputStream(new FileInputStream(tabledata));
data = (Object[][]) in.readObject(); //explict cast required
in.close();
Because this stores all data as one big chunk I don't think it is possible to just read/write one element. You would have to resort to counting bytes of stored objects and then skip to right position. If you would really need to store huge amount of table data I would use some relational database as backend. Otherwise I wouldn't bother with such optimization. Just rewrite everything on save.
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!
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.