I Have java code like this:
private ArrayList<Room> loadRoom() {
ArrayList<Room> rooms = new ArrayList<Room>();
try {
File roomsFile = new File("src/txt/rooms");
BufferedReader br = new BufferedReader(new FileReader(roomsFile));
String line = null;
while ((line = br.readLine()) != null) {
String[] split = line.split("\\|");
int number = Integer.parseInt(split[0]);
String type = split[1];
String name = split[2];
int beds = Integer.parseInt(split[3]);
Boolean tv = Boolean.parseBoolean(split[4]);
Boolean miniBar = Boolean.parseBoolean(split[5]);
Boolean ocupied = Boolean.parseBoolean(split[6]);
Boolean deleted = Boolean.parseBoolean(split[7]);
Room newRoom = new Room(number, type, name, beds, tv, miniBar, ocupied, deleted);
rooms.add(newRoom);
}
} catch (Exception e) {
e.printStackTrace();
}
return rooms;
}
private void initGUI() {
tbToolBar = new JToolBar();
btnAdd = new JButton();
tbToolBar.add(btnAdd);
spScroll = new JScrollPane();
lblSort = new JLabel("Sort by ");
cbSort = new JComboBox();
btnSort = new JButton("Sort");
cbSort.addItem("Number");
cbSort.addItem("Type");
tbToolBar.add(lblSort);
tbToolBar.add(cbSort);
tbToolBar.add(btnSort);
ArrayList<Room> rooms = loadRoom();
String[] header = new String[] { "Number", "Type", "Name", "No. beds", "TV", "Mini bar", "Occupation" };
Object[][] show = new Object[rooms.size()][header.length];
for (int i = 0; i < rooms.size(); i++) {
Room r = rooms.get(i);
show[i][0] = r.getNumber();
show[i][1] = r.getType();
show[i][2] = r.getName();
show[i][3] = r.getBeds();
show[i][4] = r.getTv().toString();
show[i][5] = r.getMiniBar().toString();
show[i][6] = r.getOcupied().toString();
// show[i][7] = r.getDeleted();
}
DefaultTableModel tableModel = new DefaultTableModel(show, header);
tblRooms = new JTable(tableModel);
tblRooms.setRowSelectionAllowed(true);
tblRooms.setColumnSelectionAllowed(true);
tblRooms.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
tblRooms.setDefaultEditor(Object.class, null);
JScrollPane tableScroll = new JScrollPane(tblRooms);
add(spScroll);
add(tbToolBar, BorderLayout.NORTH);
add(tableScroll, BorderLayout.CENTER);
}
private void initAction() {
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
RoomAddWindow addRoom = new RoomAddWindow();
addRoom.setVisible(true);
}
});;
}
And text file like this:
13|family room|name apartman|4|true|true|empty|false
16|superior room|super room|2|true|false|empty|false
15|room|room for one|1|false|false|full|false
Text file is shown normaly in JTable in order like in text file. But I have JComboBox with two filters: Number (room Number - split[0] in text file) and Room Type split[2].
The question is:
What is the simplest way to sort JTable by one of theese parameters?
EDIT:
I would like to use tblRooms.setAutoCreateRowSorter(true);, but profesor said he want from us to do that on harder way and you sort only by these two parameters. :D
Also, Even when I tried it number is sorted only by first digit.
For example if I want to sort by descending numbers it will sort like this:
41
21
15
13
1234
123
12
0
Instead of:
1234
123
41
21
15
13
12
0
Related
I'm trying to use the BufferedFileReader to read a Document with saved Information. It's working good, but it always skips the first line of the code. Is it because I'm calling readLine() in the for loop? If so how could I change it?
private void createViewUser() {
String[] stringFirstName = new String[10];
String[] stringName = new String[10];
String[] stringAge= new String[10];
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
for (int i = 0; br.readLine() != null; i++) {
stringFirstName[i] = br.readLine();
stringName[i] = br.readLine();
stringAge[i] = br.readLine();
firstname[i] = new JTextField();
firstname[i].setBounds(100, 100 + 50 * i, 100, 30);
view.add(firstname[i]);
name[i] = new JTextField();
name[i].setBounds(200, 100 + 50 * i, 100, 30);
view.add(name[i]);
age[i] = new JTextField();
age[i].setBounds(300, 100 + 50 * i, 100, 30);
view.add(age[i]);
firstname[i].setText(stringFirstName[i]);
name[i].setText(stringName[i]);
age[i].setText(stringAge[i]);
}
fr.close();
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Exactly, each time before going into the for loop your program reads a line and checks if it is not null.
More you will also skip a line because of this condition. (not sure if it's desired or not)
You kinda got the answer yourself ;)
you're reading first line in the for loop:
for (int i = 0; br.readLine() /* HERE*/ != null; i++) {
You could do something like this:
String line = br.readLine();
for(int i = 0; line != null ; i++){
stringFirstName[i] = line;
line = br.readLine();
}
Hello you can init String var to fix it:
String line = br.readLine();
for (int i = 0; line != null; i++) {
stringFirstName[i] = line;
stringName[i] = br.readLine();
stringAge[i] = br.readLine();
It's doesn't work because it's load first line on for loop verification for (int i = 0; br.readLine() != null; i++) {
Good luck.
Your question involves several steps, but the most important issue for your purposes is how to efficiently and safely read data held in a text file when the data is presented in groups of three lines, something like:
first_name_1
last_name_1
age_1
first_name_2
last_name_2
age_2
first_name_3
last_name_3
age_3
first_name_4
last_name_4
age_4
where of course the names are replaced with real names, and likewise the age_? is replaced with a real number.
If you're going to go the BufferedReader route, I think that the safest thing to do is get all three Strings in each grouping within the while loop's boolean condition, something like:
BufferedReader reader = new BufferedReader(....);
// declare empty Strings first
String firstName = "";
String lastName = "";
String ageString = ""; // need to get age *first* as a String
while ((firstName = reader.readLine()) != null // get all 3 Strings here
&& (lastName = reader.readLine()) != null
&& (ageString = reader.readLine()) != null) { // boolean condition ends here
int age = Integer.parseInt(ageString.trim()); // NumberFormatException risk here
// ....
}
This way, if any of the Strings in the text file are missing, the whole while loop ends, and bad data is not obtained.
Other recommendations, create a plain-old Java object to hold your Person data, the names and the age, a class with 3 fields, 2 that are Strings for the names, and one int field for the age. Give it a decent constructor, getter methods.... For example:
public class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
#Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
}
}
This way, the while loop above could be used to simply create Person objects:
List<Person> persons = new ArrayList<>(); // an ArrayList of Person to hold the data
while ((firstName = reader.readLine()) != null // get all 3 Strings here
&& (lastName = reader.readLine()) != null
&& (ageString = reader.readLine()) != null) { // the while loop ends here
int age = Integer.parseInt(ageString.trim());
Person person = new Person(firstName, lastName, age); // create a new Person object
persons.add(person); // put it into the arraylist
}
OK, how about displaying this information into a JTable -- that's easy.
Create a DefaultTableModel with the correct column names:
private static final String[] COL_NAMES = { "First Name", "Last Name", "Age" };
private DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0);
and then create a JTable with this model:
private JTable table = new JTable(model);
Then iterate through the ArrayList<Person> and fill our model with data:
for (Person person : personList) {
Vector<Object> rowData = new Vector<>();
rowData.add(person.getFirstName());
rowData.add(person.getLastName());
rowData.add(person.getAge());
model.addRow(rowData);
}
and the JTable is created and filled with data, just like that.
OK, assuming a data file called PersonData.txt that is located in the same directory as our class files, like so:
And assuming that this file holds our data like so:
John
Smith
21
Fred
Flinstone
53
Barny
Rubble
52
Mary
Contrary
22
Bo
Peep
12
Donald
Trump
75
Donald
Duck
40
Mickey
Mouse
45
Minnie
Mouse
41
Ebenezer
Scrooge
80
Bob
Cratchit
33
Ralph
Kramden
55
Alice
Kramden
48
Ed
Norton
54
Then using our Person.java class, we can create a GUI to hold and display our data like so:
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class PersonDisplay extends JPanel {
private static final String[] COL_NAMES = { "First Name", "Last Name", "Age" };
private static final String PERSON_DATA_PATH = "PersonData.txt";
private DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0);
private JTable table = new JTable(model);
public PersonDisplay(List<Person> personList) {
for (Person person : personList) {
Vector<Object> rowData = new Vector<>();
rowData.add(person.getFirstName());
rowData.add(person.getLastName());
rowData.add(person.getAge());
model.addRow(rowData);
}
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
private static void createAndShowGui(List<Person> personList) {
PersonDisplay mainPanel = new PersonDisplay(personList);
JFrame frame = new JFrame("Person Display");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static List<Person> readInPersons(InputStream is) throws IOException {
List<Person> persons = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String firstName = "";
String lastName = "";
String ageString = "";
while ((firstName = reader.readLine()) != null
&& (lastName = reader.readLine()) != null
&& (ageString = reader.readLine()) != null) {
int age = Integer.parseInt(ageString.trim());
Person person = new Person(firstName, lastName, age);
persons.add(person);
}
return persons;
}
public static void main(String[] args) {
try {
InputStream inputStream = PersonDisplay.class.getResourceAsStream(PERSON_DATA_PATH);
List<Person> personList = readInPersons(inputStream);
SwingUtilities.invokeLater(() -> createAndShowGui(personList));
} catch (IOException e) {
e.printStackTrace();
}
}
}
and when displayed, it would look like:
If I have 2 text files like this
textfile1:
textflie1 have
123456789 apple back 400000 1234
987654321 egg blue 500000 4321
textfile2:
5678900 fish dog 400000 4567
1234567 cat hat 500000 8905
And I read them like this:
public class main extends javax.swing.JFrame {
ArrayList<String>name = new ArrayList();
ArrayList<String>acNum = new ArrayList();
ArrayList<String>surname = new ArrayList();
ArrayList<String>pass = new ArrayList();
ArrayList<String>hasMoney = new ArrayList();
//ต่างธนาคาร
ArrayList<String>name2 = new ArrayList();
ArrayList<String>acNum2 = new ArrayList();
ArrayList<String>surname2 = new ArrayList();
ArrayList<String>pass2 = new ArrayList();
ArrayList<String>hasMoney2 = new ArrayList(); public main(){
initComponents();
try{
File f = new File("file1.txt");
Scanner a = new Scanner(f);
while( a.hasNextLine()){
String u[] = a.nextLine().split(" ");
name.add(u[1]);
surname.add(u[2]);
acNum.add(u[0]);
pass.add(u[4]);
hasMoney.add(u[3]);
}
}catch (FileNotFoundException e){
JOptionPane.showMessageDialog(null,
"Error opening accounts file.");
}
//ต่างธนาคาร
try{
File f = new File("file2.txt");
Scanner a = new Scanner(f);
while( a.hasNextLine()){
String u[] = a.nextLine().split(" ");
name2.add(u[1]);
surname2.add(u[2]);
acNum2.add(u[0]);
pass2.add(u[4]);
hasMoney2.add(u[3]);
}
}catch (FileNotFoundException e){
JOptionPane.showMessageDialog(null,
"Error opening accounts file.");
}
}
and I do this:
String me = acInField.getText();
if(acNum.contains(me)){
namu = name.get(acNum.indexOf(me));
mymon = hasMoney.get(acNum.indexOf(me));
surr= surname.get(acNum.indexOf(me));
String namsur= namu+" "+surr;
new
inputMoney(namsur,Integer.parseInt(mymon),0).setVisible(true);
this.dispose();
}else if(acNum2.contains(me)){
namu = name2.get(acNum2.indexOf(me));
mymon = hasMoney2.get(acNum2.indexOf(me));
surr= surname2.get(acNum2.indexOf(me));
String namsur= namu+" "+surr;
new
inputMoney(namsur,Integer.parseInt(mymon),0).setVisible(true);
this.dispose(); } else{
}
and this is inputMoney:
enter code here
public String namsur ;
public int mymoney ;
public int myvat=0;
public int bankin = 0 ;
public inputMoney() {
initComponents();
}
public inputMoney(String name ,int money,int vat){
initComponents();
namsur = name;
myvat += vat;
mymoney = money+vat;
inMo2.setText(namsur);
}
And I want to save mymoney back on textfile that I got them (in the same place and not change other value in old textfile)
I am making a ui in which i read data from a text file and save it to another text file after the user edits in it.i want to return integer values for all columns except column 6 and 7.For column 6 and 7 i want to return double values.Everything in this program works fine only for column 6 and column 7 when user edit in it until they enter a integer value it shows red marks in the cells whereas i should be double values for column 6 and column 7.please help
Code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Read extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Read()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("test1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens() )
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null)
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
final JTable table = new JTable(new DefaultTableModel(data, columnNames){
private static final long serialVersionUID = 1L;
#Override
public Class getColumnClass(int column) {
return Integer.class;
}
});
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button1 = new JButton( "Save" );
buttonPanel.add( button1 );
button1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Object Value = table.getValueAt (i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("new.txt"));
fileWriter.write(con.toString());
fileWriter.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Read a = new Read();
a.setDefaultCloseOperation( EXIT_ON_CLOSE );
a.pack();
a.setVisible(true);
}
}
text file
1 2 3 4 5 6 7 8
78 12 12 45 4 0.0045 0.0078 45
45 45 69 56 7 0.0056 0.0023 21
45 89 76 42 1 0.0036 0.0023 36
TableModel#getColumnClass is used to determine which renderer AND which editor should be used by the JTable.
When you use Integer.class for the column class, the JTable sets up a JFormattedField configured to only allow whole numbers to be accepted. You need to modify the getColumnClass to return the correct data type of the given column, for example...
#Override
public Class getColumnClass(int column) {
return column == 5 || column == 6 ? Double.class : Integer.class;
}
You should also make sure that the data you are entering into the model is capable of meeting this contract, for example...
while (st2.hasMoreTokens()) {
Object num = null;
String value = st2.nextToken();
Number num = NumberFormat.getNumberInstance().parse(value);
row.addElement(num);
}
I have made a GUI using swing, i read data from a text file to the jtable,
the text file has 6 columns and 5 rows,the 3 row has values 0,0.0,0,0,0,0.so i want to display
values in the JTable till it encounters 0.but to save the full text file while saving which means values of 5 rows.here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Bb extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Bb()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens())
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null )
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button2 = new JButton( "SAVE TABLE" );
buttonPanel.add( button2 );
button2.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuffer Con = new StringBuffer();
for (int i = 0; i < table.getRowCount(); i++)
{
for (int j = 0; j < table.getColumnCount(); j++)
{
Object Value = table.getValueAt(i, j);
Con.append(" ");
Con.append(Value);
}
Con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("cc.txt"));
fileWriter.write(Con.toString());
fileWriter.flush();
fileWriter.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Bb frame = new Bb();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
and the text file:
1 2 6 0.002 0.00 2
2 5 5 0.005 0.02 4
0 0 0 0.000 0.00 0
4 8 9 0.089 0.88 7
5 5 4 0.654 0.87 9
I was able to understand what you want
For first part that you just wanted to show your data in your JTable till you encounter 0
code:
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0")) {
break;
}
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
Explanation: when you read each line, split it, so if the first element of each splitted line is zero, you come out of the loop and do not show any other values inside the loop.
For saving all your data from first file to second file, you should copy them from first file to second file because your JTable will not have enough info to help your purpose in this matter.
Note: I do not understand why you want to do this but you can accomplish that in following way
Code:
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
String st = "";
FileInputStream fin = new FileInputStream("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
Scanner input = new Scanner(fin).useDelimiter("\\A");
while (input.hasNext()) {
st = input.next();
System.out.println("st is " + st);
}
FileWriter fileWriter = new FileWriter(new File("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"));
fileWriter.write(st);
fileWriter.flush();
fileWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
Explanation: you read the whole file with Scanner trick and write it down into a second file.
Source: https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html
Based on what the OP requested
Code:
public Bb() {
String aLine;
Vector columnNames = new Vector();
Vector data = new Vector();
boolean found = false;
StringBuilder temp = new StringBuilder();
/*Using try catch block with resources Java 7
Read about it
*/
try (FileInputStream fin = new FileInputStream("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
//the first line of the txt file fill colum names
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
columnNames.addElement(s);
}
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0") && !found) {
found = true;
} else if (found) {
temp.append(aLine).append("\r\n");
} else if (!sp[0].equals("0") && !found) {
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
}
} catch (IOException e) {
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JButton button2 = new JButton("SAVE TABLE");
buttonPanel.add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
Object Value = table.getValueAt(i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
try (FileWriter fileWriter = new FileWriter(new File("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"))) {
fileWriter.write(con.append(temp).toString());
fileWriter.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
My code just works if you have row includes zeros. if you want to make it better to cover up all conditions, I am sure you can follow my plan.
Sample to get rid of all zeros like
1 1 1
0 0 0
0 0 0
1 1 1
Code:
String s = "xxxooooooxxx";
String[] sp = s.split("");
boolean xFlag = false;
for (int i = 0; i < sp.length; i++) {
if (sp[i].equals("x") && !xFlag) {
System.out.print("x");
} else if (sp[i].equals("o")) {
xFlag = true;
} else if (sp[i].equals("x") && xFlag) {
System.out.print("X");
}
}
output:
xxxXXX
I have a csv file (5 columns, with | as delimiter) and I want to fill 2 JTable columns with two data columns from csv file.
public class jTable extends JFrame {
public static int rowNumber() {
int num = 0;
try {
File files = new File("C:\\BorsaItalia2.csv");
BufferedReader bf = new BufferedReader(new FileReader(files));
String lines = "";
while ((lines = bf.readLine()) != null) {
num++;
}
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
JTable table;
public jTable() {
setLayout(new FlowLayout());
String[] columnNames = {"a", "b", "c", "d", "e"};
Object[][] data = new Object[rowNumber()][5];
table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(600, 950));
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
add(scroll);
}
public static void main(String[] args) {
try {
int row = 0;
int col = 0;
Object[][] imported = new Object[rowNumber()][5];
File file = new File("C:\\BorsaItalia2.csv");
BufferedReader bfr = new BufferedReader(new FileReader(file));
String line = "";
while ((line = bfr.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, "|");
col = 0;
while (st.hasMoreTokens()) {
imported[row][col] = st.nextToken();
System.out.println("number["+ row + "]["
+ col + "]:" + imported[row][col]);
col++;
}
row++;
}
bfr.close();
Object[] description = new Object[imported.length];
Object[] symbol = new Object[imported.length];
for (int i = 0; i < imported.length; i++) {
description[i] = imported[i][2];
symbol[i] = imported[i][0];
}
for (int i = 1; i < imported.length; i++) {
System.out.println("Description is " + description[i]
+ " and symbol is: " + symbol[i]);
}
System.out.println("");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("error " + e);
}
jTable gui = new jTable();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(650, 950);
gui.setVisible(true);
gui.setTitle("Project Table");
}
}
I would like to fill table column a with Object[] symbol and column c with Object[] description.
Any coding help really appreciated.
Thanks all.
Instead of using the DefaultTableModel implied by your JTable constructor, create your own implementation of AbstractTableModel, as shown in How to Use Tables: Creating a Table Model. Arrange for your getValueAt() to return the data from the arrays you've read. There's a related example here.