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
Related
Im having trouble with importing XLS data to jtable.
My program reads only the last row from XLS.
Here is my code:
JButton btnImportExcelFiles = new JButton("EXCEL FILES");
btnImportExcelFiles.setIcon(new ImageIcon(racunariAplikacija.class.getResource("/image/Excel-icon.png")));
btnImportExcelFiles.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
FileFilter filter = new FileNameExtensionFilter("Excel Files", "xls");
// here is my file chooser
JFileChooser jf = new JFileChooser();
jf.addChoosableFileFilter(filter);
int rezultat = jf.showOpenDialog(null);
if(rezultat == JFileChooser.APPROVE_OPTION)
{
String excelPath = jf.getSelectedFile().getAbsolutePath();
ArrayList<Stavka>lista = new ArrayList<>();
Stavka stavka = new Stavka();
File f = new File(excelPath);
Workbook wb = null;
try {
wb = Workbook.getWorkbook(f);
}
catch (BiffException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
// this is where i call for nested forloop
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
System.out.println("redovi" + row + "kolone" + col);
for (int i = 0; i < 18; i++) {
for (int j = 0; j < col; j++) {
Cell c = s.getCell(j,i);
if(j==0) {stavka.setStavkaID(Integer.parseInt(c.getContents().toString()));}
else if(j==1) {}
else if(j==2) {stavka.setSifraKomponente(c.getContents().toString());}
else if(j==3) {stavka.setOpis(c.getContents().toString());}
else if(j==4) {stavka.setVrednost(c.getContents().toString());}
else if(j==5) {stavka.setKuciste(c.getContents().toString());}
else if(j==6) {stavka.setSektor(c.getContents().toString());}
else if(j==7) {stavka.setRack(c.getContents().toString());}
else if(j==8) {stavka.setProizvodjac(c.getContents().toString());}
else if(j==9) {stavka.setKolicina(Integer.parseInt(c.getContents().toString()));}
//System.out.println(c.getContents());
}
// this is my tableModel
lista.add(stavka);
TabelaStavka stavka1 = new TabelaStavka(lista);
tblAzuriranjeMagacina.setModel(stavka1);
}
}
}
}
How can this be fixed?
I believe the error exists because you must create a new Stavka object for each line in your XLS, and then add it to 'lista'. Finally, I believe you also want to set the model (TabelaStavka) outside these for loops.
I don't have a full Java environment installed here, so forgive me if there is any syntax error below. The most important thing is that you understand what are the fixes you have to do in your code.
Also, never underestimate code formatting, you should consider using a better IDE, which helps out better formatting your source code.
JButton btnImportExcelFiles = new JButton("EXCEL FILES");
btnImportExcelFiles.setIcon(new ImageIcon(racunariAplikacija.class.getResource("/image/Excel-icon.png")));
btnImportExcelFiles.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
FileFilter filter = new FileNameExtensionFilter("Excel Files", "xls");
// here is my file chooser
JFileChooser jf = new JFileChooser();
jf.addChoosableFileFilter(filter);
int rezultat = jf.showOpenDialog(null);
if(rezultat == JFileChooser.APPROVE_OPTION)
{
String excelPath = jf.getSelectedFile().getAbsolutePath();
ArrayList<Stavka>lista = new ArrayList<>();
File f = new File(excelPath);
Workbook wb = null;
try
{
wb = Workbook.getWorkbook(f);
}
catch (BiffException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
// this is where i call for nested forloop
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
System.out.println("redovi" + row + "kolone" + col);
for (int i = 0; i < 18; i++)
{
Stavka stavka = new Stavka(); // new instance <<<<<<<<
for (int j = 0; j < col; j++)
{
Cell c = s.getCell(j,i);
if(j==0) {stavka.setStavkaID(Integer.parseInt(c.getContents().toString()));}
else if(j==1) {}
else if(j==2) {stavka.setSifraKomponente(c.getContents().toString());}
else if(j==3) {stavka.setOpis(c.getContents().toString());}
else if(j==4) {stavka.setVrednost(c.getContents().toString());}
else if(j==5) {stavka.setKuciste(c.getContents().toString());}
else if(j==6) {stavka.setSektor(c.getContents().toString());}
else if(j==7) {stavka.setRack(c.getContents().toString());}
else if(j==8) {stavka.setProizvodjac(c.getContents().toString());}
else if(j==9) {stavka.setKolicina(Integer.parseInt(c.getContents().toString()));}
}
lista.add(stavka); // inside second for loop <<<<<<<<
}
// outside the second for loop <<<<<<<<<<<<<<<<<<<<<<<<<<
// this is my tableModel
TabelaStavka stavka1 = new TabelaStavka(lista);
tblAzuriranjeMagacina.setModel(stavka1);
}
}
}
Sorry for the long code, didn't want to leave anything out.
Little explanation, I'm just trying to do a way where the user inputs a date to check there history between the two dates now i have it working to an extent, it reads of a text document, which for each transactions has 8 lines that need to be printed if the date is between the dates
the Example document is structured as below:
######## START OF TRANSACTION ########
Name: name
DATE: 14/05/2015
Ammount: 100
Address: address
Card Number: 123312
ExpiryDate: 123312
######## END OF TRANSACTION ########
######## START OF TRANSACTION ########
Name: name
DATE: 19/05/2015
Ammount: 100
Address: address
Card Number: 123312
ExpiryDate: 123312
######## END OF TRANSACTION ########
if i input the date 15-05-2015 to 16-05-2015
i get:
######## START OF TRANSACTION ########
Name: name
DATE: 14/05/2015
Ammount: 100
Address: address
Card Number: 123312
ExpiryDate: 123312
null######## END OF TRANSACTION ########
######## START OF TRANSACTION ########
Name: name
DATE: 19/05/2015
Ammount: 105
Address: address
Card Number: 123312
null
1: what is with the NULL values guessing my loop
2: why does it print the 19. even if i have the 16th in their it still prints the 19th....please help, I've been on this for awhile
import javax.swing.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class TopUpHistoryScreen extends JDialog {
private JPanel mainPanel;
private JTextArea historyScreen;
public TopUpHistoryScreen()
{
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 450);
setVisible(true);
}
public String Reader() {
try {
ArrayList<String> Trains = new ArrayList<String>();
int count = 0;
String testing = "";
File file = new File("TopUp.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
count += count;
Trains.add(line + "\n");
stringBuffer.append("\n");
testing += line + "\n";
//field.setText(line);
}
fileReader.close();
return testing;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String checkDates(String startDate, String endDate) {
try {
ArrayList<String> Lines = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int count = 0;
int check = 0;
String[] lineArray = new String[8];
String DateSelected = "";
String testing="";
File file = new File("TopUp.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
lineArray[count] = line+"\n";
if (count < 8){
count ++;
}
if (count == 7){
if(check == 1){
testing += lineArray[0];
testing += lineArray[1];
testing += lineArray[2];
testing += lineArray[3];
testing += lineArray[4];
testing += lineArray[5];
testing += lineArray[6];
testing += lineArray[7];
check = 0;
}
}
if (count == 7){
count = 0;
check = 0;
lineArray = new String[8];
}
if (line.contains("DATE")){
try {
DateSelected = line.replace("DATE: ", "");
Date MainDate = sdf.parse(DateSelected);
Date SDate = sdf.parse(startDate);
Date EDate = sdf.parse(endDate);
if(MainDate.compareTo(SDate)>=0 || MainDate.compareTo(EDate)<=0 ){
//is after Sdate and before eDate
check = 1;
}
// if(MainDate.compareTo(SDate)<0){ //is Before SDate
//
// }
// if(MainDate.compareTo(SDate)==0){ //is equal to mainDate
//
// }
} catch (ParseException e) {
//e.printStackTrace();
}
}
stringBuffer.append(line);
Lines.add(line + "\n");
stringBuffer.append("\n");
}
fileReader.close();
return testing;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void setPanels()
{
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JPanel lowerPanel = new JPanel(new FlowLayout());
//JButton apply = new JButton("Select data area");
JButton exit = new JButton("Okay!");
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
JButton checkDate = new JButton("check dates");
JLabel START = new JLabel("START DATE!");
JLabel startDay = new JLabel("Day:");
JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
JTextField sYear = new JTextField("2015");
JLabel END = new JLabel("END DATE!");
JLabel endDay = new JLabel("Day:");
JTextField eDay = new JTextField();
JLabel endMonth = new JLabel("Month:");
JTextField eMonth = new JTextField();
JLabel endYear = new JLabel("Year:");
JTextField eYear = new JTextField("2015");
//JTextField Data = new JTextField();
//JTextField touchOnTimeFieldminute = new JTextField();
historyScreen = new JTextArea(10,20);
JScrollPane scrolll = new JScrollPane(historyScreen);
//mainPanel.add(SelectData);
//mainPanel.add(SelectData);
// mainPanel.add(new JLabel());
mainPanel.add(new JLabel());
mainPanel.add(START);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(new JLabel());
mainPanel.add(END);
mainPanel.add(endDay);
mainPanel.add(eDay);
mainPanel.add(endMonth);
mainPanel.add(eMonth);
mainPanel.add(endYear);
mainPanel.add(eYear);
mainPanel.add(new JLabel());
mainPanel.add(checkDate);
lowerPanel.add(scrolll);
lowerPanel.add(exit);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
checkDate.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String startday = sDay.getText();
String startmonth = sMonth.getText();
String startyear = sYear.getText();
String endday = eDay.getText();
String endmonth = eMonth.getText();
String endyear = eYear.getText();
String startDate = (startday+"/"+startmonth+"/"+startyear);
String endDate = (endday+"/"+endmonth+"/"+endyear);
String AnswerDates = checkDates(startDate,endDate);
historyScreen.setText(AnswerDates);
}
});
}
}
sorry guys i got it this time, just incase someone looks at this later hahaha, it was because my for loop was ending at 7 instead of 8 and was saving no value into array [7], and also because the date check was doing || instead of && below is the updated class
public String checkDates(String startDate, String endDate) {
try {
ArrayList<String> Lines = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int count = 0;
int check = 0;
String[] lineArray = new String[8];
String DateSelected = "";
String testing="";
File file = new File("TopUp.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
lineArray[count] = line+"\n";
if (count < 8){
count ++;
}
if (count == 8){
if(check == 1){
testing += lineArray[0];
testing += lineArray[1];
testing += lineArray[2];
testing += lineArray[3];
testing += lineArray[4];
testing += lineArray[5];
testing += lineArray[6];
testing += lineArray[7];
check = 0;
}
}
if (count == 8){
count = 0;
check = 0;
lineArray = new String[8];
}
if (line.contains("DATE")){
try {
DateSelected = line.replace("DATE: ", "");
Date MainDate = sdf.parse(DateSelected);
Date SDate = sdf.parse(startDate);
Date EDate = sdf.parse(endDate);
if(MainDate.compareTo(SDate)>=0 && MainDate.compareTo(EDate)<=0 ){
//is after Sdate and before eDate
check = 1;
}
// if(MainDate.compareTo(SDate)<0){ //is Before SDate
//
// }
// if(MainDate.compareTo(SDate)==0){ //is equal to mainDate
//
//
}
} catch (ParseException e) {
//e.printStackTrace();
}
}
stringBuffer.append(line);
Lines.add(line + "\n");
stringBuffer.append("\n");
}
fileReader.close();
return testing;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
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'm trying to hide a random word which I retrieved from a list in a text file, but the code keeps giving me the following error: Array Required, but java.lang.String found
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;
public class Hangman extends JFrame
{
private static final char HIDECHAR = '_';
String imageName = null;
String Path = "D:\\Varsity College\\Prog212Assign1_10-013803\\images\\";
static int guesses =0;
private String original = readWord();
private String hidden;
int i = 0;
static JPanel panel;
static JPanel panel2;
static JPanel panel3;
static JPanel panel4;
public Hangman(){
JButton[] buttons = new JButton[26];
this.original = original;
this.hidden = this.createHidden();
panel = new JPanel(new GridLayout(0,9));
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
JButton btnRestart = new JButton("Restart");
btnRestart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}
});
JButton btnNewWord = new JButton("Add New Word");
btnNewWord.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter fw = new FileWriter("Words.txt", true);
PrintWriter pw = new PrintWriter(fw, true);
String word = JOptionPane.showInputDialog("Please enter a word: ");
pw.println(word);
pw.close();
}
catch(IOException ie)
{
System.out.println("Error Thrown" + ie.getMessage());
}
}
});
JButton btnHelp = new JButton("Help");
btnHelp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word."
+ "\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions."
+ "\nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark."
+ "\n"
+ "\nThe game is over when:"
+ "\nThe guessing player completes the word, or guesses the whole word correctly"
+ "\nThe other player completes the diagram";
JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JLabel lblWord = new JLabel(original);
if(guesses >= 0) imageName = "Hangman1.jpg";
if(guesses >= 1) imageName = "Hangman2.jpg";
if(guesses >= 2) imageName = "Hangman3.jpg";
if(guesses >= 3) imageName = "Hangman4.jpg";
if(guesses >= 4) imageName = "Hangman5.jpg";
if(guesses >= 5) imageName = "Hangman6.jpg";
if(guesses >= 6) imageName = "Hangman7.jpg";
ImageIcon icon = null;
if(imageName != null){
icon = new ImageIcon(Path + File.separator + imageName);
}
JLabel label = new JLabel();
label.setIcon(icon);
String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
panel.add(buttons[i]);
}
panel2.add(label);
panel3.add(btnRestart);
panel3.add(btnNewWord);
panel3.add(btnHelp);
panel3.add(btnExit);
panel4.add(lblWord);
}
public String readWord()
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
String line = reader.readLine();
List<String> words = new ArrayList<String>();
while(line != null)
{
String[] wordsLine = line.split(" ");
boolean addAll = words.addAll(Arrays.asList(wordsLine));
line = reader.readLine();
}
Random rand = new Random(System.currentTimeMillis());
String randomWord = words.get(rand.nextInt(words.size()));
return randomWord;
}catch (Exception e){
return null;
}
}
private String printWord(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.original.length(); i++){
sb.append(HIDECHAR);
}
return sb.toString();
}
public boolean check(char input){
boolean found = false;
for (int i = 0; i < this.original.length(); i++){
if(this.original.charAt(i)== input)){
found = true;
this.hidden[i] = this.original.charAt(i);
}
}
return found;
}
public static void main(String[] args)
{
System.out.println();
Hangman frame = new Hangman();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box mainPanel = Box.createVerticalBox();
frame.setContentPane(mainPanel);
mainPanel.add(panel, BorderLayout.NORTH);
mainPanel.add(panel2);
mainPanel.add(panel4);
mainPanel.add(panel3);
frame.pack();
frame.setVisible(true);
}
}
Okay there's the whole code< the error is now on line 151 and 149... I've also tried to fix it according to one of the posts
You can't use array subscripts: [], to index into a String, and both hidden and original are Strings.
You can instead use original.charAt(i) to read a character at an index.
As for writing a character at an index: java Strings are immutable, so you can't change individual characters. Instead make hidden a StringBuilder, or simply a char[]:
// in your class member declarations:
char hidden[] = createHidden();
// possible implementation of createHidden:
char[] createHidden()
{
if (original != null)
return new char[original.length()];
else return null;
}
And then your loop can use original.charAt like so:
if (this.original.charAt(i) == input)
{
found = true;
this.hidden[i] = this.original.charAt(i);
1. As you are using original.length() its a String, as length() method works with String, not with Array, as for array, length is an Instance variable.
2. Try it like this....
this.hidden[i] = original.charAt(i);
3. And as char is Not an object but a primitive, use "=="
if (this.original[i] == input)
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.