JFrame Printing out not as expected. if loop trouble - java

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;
}

Related

How to sort JTable depending of JComboBox selected item

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

How to print the contents of a file to a GUI

For my program one of the major things we have to do is print the contents of a .csv file to a GUI. I have figured out the GUI and sorting methods however we are having trouble figuring out how to actually print the file to the GUI. Any ideas on how to do this? Here is the code for the GUI:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class FirstGUI2 {
private static JTextArea textAreaMon;
private static JTextArea textAreaTue;
private static JTextArea textAreaWed;
private static JTextArea textAreaThu;
private static JTextArea textAreaFri;
private static JTextArea description;
private static String gE1 = "Group Exam 1";
private static String gE2 = "Group Exam 2";
private static String gE3 = "Group Exam 3";
private static String gE4 = "Group Exam 4";
private static String gE5 = "Group Exam 5";
private static String gE6 = "Group Exam 6";
private static String gE7 = "Group Exam 7";
private static String gE8 = "Group Exam 8";
private static String gE9 = "Group Exam 9";
private Container pane;
final static boolean fill = true;
final static boolean weightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static String mon = "";
public static String tues = "";
public static String wed = "";
public static String thu = "";
public static String fri = "";
public static void addComponents(Container pane) {
if (RIGHT_TO_LEFT)
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
button = new JButton("Open File");
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(5, 5, 5, 5);
pane.add(button, c);
textAreaMon = new JTextArea(mon);
//textAreaMon.append(mon.substring(0));
textAreaMon.setLineWrap(true);
textAreaMon.setEditable(false);
c.gridx = 1;
c.gridy = 2;
pane.add(textAreaMon, c);
textAreaTue = new JTextArea(tues);
textAreaTue.setLineWrap(true);
textAreaTue.setEditable(false);
c.gridx = 1;
c.gridy = 3;
pane.add(textAreaTue, c);
textAreaWed = new JTextArea(wed);
textAreaWed.setLineWrap(true);
textAreaWed.setEditable(false);
c.gridx = 1;
c.gridy = 4;
pane.add(textAreaWed, c);
textAreaThu = new JTextArea(thu);
textAreaThu.setLineWrap(true);
textAreaThu.setEditable(false);
c.gridx = 1;
c.gridy = 5;
pane.add(textAreaThu, c);
textAreaFri = new JTextArea(fri);
textAreaFri.setLineWrap(true);
textAreaFri.setEditable(false);
c.gridx = 1;
c.gridy = 6;
pane.add(textAreaFri, c);
description = new JTextArea(
"Click the open button in order to select and import your .csv file. Your scehdule and times will be displayed in the schedule below.");
description.setEditable(false);
c.gridx = 1;
c.gridy = 0;
pane.add(description, c);
// attaching the file opener to the open file button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
new InterfacePanel();
}
});
}
//creates the frame and showing the GUI to the user
public static void makeGUI(){
JFrame frame = new JFrame("Final Exam Scheduler");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void printToGUI(){
//JText Fields
//textAreaMon
mon= "Monday: \n \n 8:00 - 10:00:\t Group Exam 1 \n 10:15-12:15:\t Group Exam 2 \n 12:45 - 2:45:\t";
while(!ArrayListsForClasses.time1.isEmpty()){
for(int i = 0; i < ArrayListsForClasses.time1.size(); i++){
mon += ArrayListsForClasses.time1.get(i);
mon += ", ";
}
}
mon += "\n 3:00 - 5:00:\t";
while(!ArrayListsForClasses.time2.isEmpty()){
for(int i = 0; i < ArrayListsForClasses.time2.size(); i++){
mon += ArrayListsForClasses.time2.get(i);
mon += ", ";
}
}
mon += "\n 5:30 - 7:30:\t Group Exam 3 \n \n 7:45 - 9:45:\t";
while(!ArrayListsForClasses.time3.isEmpty()){
for(int i = 0; i < ArrayListsForClasses.time3.size(); i++){
mon += ArrayListsForClasses.time3.get(i);
mon += ", ";
}
}
mon+= "\n \n";
// textAreaTues
tues = "Tuesday: \n \n 8:00 - 10:00: \t";
while (!ArrayListsForClasses.time4.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time4.size(); i++) {
tues += ArrayListsForClasses.time4.get(i);
tues += ", ";
}
}
tues += "\n 10:15 - 12:15:\t Group Exam 4 \n \n 12:45 - 2:45:\t ";
while (!ArrayListsForClasses.time5.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time5.size(); i++) {
tues += ArrayListsForClasses.time5.get(i);
tues += ", ";
}
}
tues += "\n 3:00 - 5:00:\t ";
while (!ArrayListsForClasses.time6.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time6.size(); i++) {
tues += ArrayListsForClasses.time6.get(i);
tues += ", ";
}
}
tues += "\n 5:30 - 7:30:\t ";
while (!ArrayListsForClasses.time7.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time7.size(); i++) {
tues += ArrayListsForClasses.time7.get(i);
tues += ", ";
}
}
tues += "\n 7:45 - 9:45:\t ";
while (!ArrayListsForClasses.time8.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time8.size(); i++) {
tues += ArrayListsForClasses.time8.get(i);
tues += ", ";
}
}
//TextAreaWed
wed = "Wednesday \n \n 8:00 - 10:00:\t";
while(!ArrayListsForClasses.time9.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time9.size(); i++) {
wed += ArrayListsForClasses.time9.get(i);
wed += ", ";
}
}
wed += "\n 10:15-12:15:\t";
while(!ArrayListsForClasses.time10.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time10.size(); i++) {
wed += ArrayListsForClasses.time10.get(i);
wed += ", ";
}
}
wed += "\n 12:45 - 2:45 :\t Group Exam 5 \n 3:00 - 5:00:\t";
while(!ArrayListsForClasses.time11.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time11.size(); i++) {
wed += ArrayListsForClasses.time11.get(i);
wed += ", ";
}
}
wed += "\n 5:30 - 7:30:\t";
while(!ArrayListsForClasses.time12.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time12.size(); i++) {
wed += ArrayListsForClasses.time12.get(i);
wed += ", ";
}
}
wed += "\n 7:45 - 9:45:\t";
while(!ArrayListsForClasses.time13.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time13.size(); i++) {
wed += ArrayListsForClasses.time13.get(i);
wed += ", ";
}
}
//TextAreaThurs
thu = "Thursday \n \n 8:00 - 10:00:\t";
while(!ArrayListsForClasses.time14.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time14.size(); i++) {
thu += ArrayListsForClasses.time14.get(i);
thu += ", ";
}
}
thu += "\n 10:15-12:15 :\t Group Exam 6 \n 12:45 - 2:45:\t";
while(!ArrayListsForClasses.time15.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time15.size(); i++) {
thu += ArrayListsForClasses.time15.get(i);
thu += ", ";
}
}
thu += "\n 3:00 - 5:00:\t";
while(!ArrayListsForClasses.time16.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time16.size(); i++) {
thu += ArrayListsForClasses.time16.get(i);
thu += ", ";
}
}
thu += "\n 5:30 - 7:30:\t Group Exam 7 \n 7:45 - 9:45:\t";
while(!ArrayListsForClasses.time17.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time17.size(); i++) {
thu += ArrayListsForClasses.time17.get(i);
thu += ", ";
}
}
//TextAreaFri
fri = "Friday \n \n 8:00 - 10:00:\t Group Exam 8 \n 10:15-12:15:\t";
while(!ArrayListsForClasses.time18.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time18.size(); i++) {
fri += ArrayListsForClasses.time18.get(i);
fri += ", ";
}
}
fri += "\n 12:45 - 2:45:\t Group Exam 9";
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
makeGUI();
}
});
}
}
I have figured out the GUI
Actaully, the design of your code is all wrong. You should NOT be using static variables and static methods. In general, the only static method should be the method to create the GUI. All other application code should be defined in a class so any method can access the variables of your class.
we have to do is print the contents of a .csv file to a GUI
To me the word "print" means to use a printer to print something to a piece of paper. I'm guessing you really want to display the contents of a file in a GUI.
Below is a simple example that shows how to read and write a file. The contents of the file will be displayed in a text area. Note you need to write to the file first before you can read the file.
I suggest you start with this basic code and rewrite your class so you can get rid of all the static variables and methods:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
class TextAreaLoad extends JPanel
{
private JTextArea edit;
public TextAreaLoad()
{
setLayout( new BorderLayout() );
edit = new JTextArea(30, 60);
add(new JScrollPane(edit), BorderLayout.NORTH);
JButton read = new JButton("Read TextAreaLoad.txt");
read.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader( "TextAreaLoad.txt" );
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
add(read, BorderLayout.LINE_START);
JButton write = new JButton("Write TextAreaLoad.txt");
write.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter writer = new FileWriter( "TextAreaLoad.txt" );
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
bw.close();
edit.setText("");
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
add(write, BorderLayout.LINE_END);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("TextArea Load");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TextAreaLoad());
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
You have yet to set the String value with the imported data to the TextAreas. What you did do, was give the JTextAreas a value equal to the initial value of strings like mon, like so:
textAreaMon = new JTextArea(mon);
However, that does not mean textAreaMon will be updated if mon is updated; it simply matters when the view is initialized.
Add method calls to your file-import button listener that contain methods that do something like this
textAreaMon.setText(mon);
This should properly update the GUI every time a file is imported.
I may be wrong, but inside the actionPerformed() method, you should write the following code
String myCsvFile = "mySCVFile.csv"; //you can modify this based on where the file is located
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(myCsvFile));
while ((line = br.readLine()) != null) {
String[] columns = line.split(","); //you may do extra tweeks in here based on how you want to display the data
for(int x=0; x <columns.length(); x++){
description.append(columns[x]); //I guess this is the textarea you want to display the content of the CSV file
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

reading desired data from file but saving the whole file data

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

Array Required, but java.lang.String found

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)

Change java applet to java application

I have an applet that runs a GUI. I want to call this GUI from my other program. I know that I need to turn this applet into an application. I have an init() and a actionPerformed(ActionEvent ae). How can I do it?
My code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class survey extends Applet implements ActionListener
{
private TextField question;
private Button enter, start;
int count = 0;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
String text, input;
private Label intro1, intro2, intro3;
private Label qone1, qone2, qone3, qone4, qone5, qone6, qone7, qone8, qone9, qone10, qone11, qone12;
private Label qtwo1, qtwo2, qtwo3, qtwo4, qtwo5, qtwo6, qtwo7, qtwo8, qtwo9, qtwo10, qtwo11, qtwo12;
private Label qthree1, qthree2, qthree3, qthree4, qthree5, qthree6, qthree7, qthree8, qthree9, qthree10, qthree11, qthree12;
private Label qfour1, qfour2, qfour3, qfour4, qfour5, qfour6, qfour7, qfour8, qfour9, qfour10, qfour11, qfour12;
private Label qfive1, qfive2, qfive3, qfive4, qfive5, qfive6, qfive7, qfive8, qfive9, qfive10, qfive11, qfive12;
private Label qsix1, qsix2, qsix3, qsix4, qsix5, qsix6, qsix7, qsix8, qsix9, qsix10, qsix11, qsix12;
private Label qseven1, qseven2, qseven3, qseven4, qseven5, qseven6, qseven7, qseven8, qseven9, qseven10, qseven11, qseven12;
private Label qeight1, qeight2, qeight3, qeight4, qeight5, qeight6, qeight7, qeight8, qeight9, qeight10, qeight11, qeight12;
private Label qnine1, qnine2, qnine3, qnine4, qnine5, qnine6, qnine7, qnine8, qnine9, qnine10, qnine11, qnine12;
private Label qten1, qten2, qten3, qten4, qten5, qten6, qten7, qten8, qten9, qten10, qten11, qten12;
private Label qeleven1, qeleven2, qeleven3, qeleven4, qeleven5, qeleven6,
private Label finish1, finish2, finish3;
public void init()
{
setLayout(null);
start = new Button ("Start");
question = new TextField(10);
enter = new Button ("Enter");
if (count == 0)
{
setBackground( Color.yellow);
intro1 = new Label("Target Advertising", Label.CENTER);
intro1.setFont(new Font("Times-Roman", Font.BOLD, 16));
intro2 = new Label("Welcome to this questionnaire. First, we would like to know more about your personal preferences.");
intro3 = new Label("For each question, Input a rating between 0-9 (zero = least interested, 9 = most interested) in the text box. Click enter for next question.");
add(intro1);
add(intro2);
add(intro3);
intro1.setBounds(0,0,800,20);
intro2.setBounds(15,20,800,20);
intro3.setBounds(15,40,800,20);
add(start);
start.setBounds(370,60,70,23);
start.addActionListener(this);
}
if(count == 1)
{
setBackground( Color.yellow );
qone1 = new Label("Question 1", Label.LEFT);
qone1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qone2 = new Label("How much do you like action movies?");
qone3 = new Label("0");
qone4 = new Label("1");
qone5 = new Label("2");
qone6 = new Label("3");
qone7 = new Label("4");
qone8 = new Label("5");
qone9 = new Label("6");
qone10 = new Label("7");
qone11 = new Label("8");
qone12 = new Label("9");
add(qone1);
add(qone2);
add(qone3);
add(qone4);
add(qone5);
add(qone6);
add(qone7);
add(qone8);
add(qone9);
add(qone10);
add(qone11);
add(qone12);
qone1.setBounds(15,0,800,20);
qone2.setBounds(15,20,800,15);
qone3.setBounds(15,60,800,15);
qone4.setBounds(15,80,800,15);
qone5.setBounds(15,100,800,15);
qone6.setBounds(15,120,800,15);
qone7.setBounds(15,140,800,15);
qone8.setBounds(15,160,800,15);
qone9.setBounds(15,180,800,15);
qone10.setBounds(15,200,800,15);
qone11.setBounds(15,220,800,15);
qone12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if (count == 2)
{
qtwo1 = new Label("Question 2", Label.LEFT);
qtwo1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qtwo2 = new Label("How much do you like Science Fiction?");
qtwo3 = new Label("0");
qtwo4 = new Label("1");
qtwo5 = new Label("2");
qtwo6 = new Label("3");
qtwo7 = new Label("4");
qtwo8 = new Label("5");
qtwo9 = new Label("6");
qtwo10 = new Label("7");
qtwo11 = new Label("8");
qtwo12 = new Label("9");
add(qtwo1);
add(qtwo2);
add(qtwo3);
add(qtwo4);
add(qtwo5);
add(qtwo6);
add(qtwo7);
add(qtwo8);
add(qtwo9);
add(qtwo10);
add(qtwo11);
add(qtwo12);
qtwo1.setBounds(15,0,800,20);
qtwo2.setBounds(15,20,800,15);
qtwo3.setBounds(15,60,800,15);
qtwo4.setBounds(15,80,800,15);
qtwo5.setBounds(15,100,800,15);
qtwo6.setBounds(15,120,800,15);
qtwo7.setBounds(15,140,800,15);
qtwo8.setBounds(15,160,800,15);
qtwo9.setBounds(15,180,800,15);
qtwo10.setBounds(15,200,800,15);
qtwo11.setBounds(15,220,800,15);
qtwo12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 3)
{
qthree1 = new Label("Question 3", Label.LEFT);
qthree1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qthree2 = new Label("How much do you like comedy?");
qthree3 = new Label("0");
qthree4 = new Label("1");
qthree5 = new Label("2");
qthree6 = new Label("3");
qthree7 = new Label("4");
qthree8 = new Label("5");
qthree9 = new Label("6");
qthree10 = new Label("7");
qthree11 = new Label("8");
qthree12 = new Label("9");
add(qthree1);
add(qthree2);
add(qthree3);
add(qthree4);
add(qthree5);
add(qthree6);
add(qthree7);
add(qthree8);
add(qthree9);
add(qthree10);
add(qthree11);
add(qthree12);
qthree1.setBounds(15,0,800,20);
qthree2.setBounds(15,20,800,15);
qthree3.setBounds(15,60,800,15);
qthree4.setBounds(15,80,800,15);
qthree5.setBounds(15,100,800,15);
qthree6.setBounds(15,120,800,15);
qthree7.setBounds(15,140,800,15);
qthree8.setBounds(15,160,800,15);
qthree9.setBounds(15,180,800,15);
qthree10.setBounds(15,200,800,15);
qthree11.setBounds(15,220,800,15);
qthree12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 4)
{
qfour1 = new Label("Question 4", Label.LEFT);
qfour1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qfour2 = new Label("How much do you like luxary cars?");
qfour3 = new Label("0");
qfour4 = new Label("1");
qfour5 = new Label("2");
qfour6 = new Label("3");
qfour7 = new Label("4");
qfour8 = new Label("5");
qfour9 = new Label("6");
qfour10 = new Label("7");
qfour11 = new Label("8");
qfour12 = new Label("9");
add(qfour1);
add(qfour2);
add(qfour3);
add(qfour4);
add(qfour5);
add(qfour6);
add(qfour7);
add(qfour8);
add(qfour9);
add(qfour10);
add(qfour11);
add(qfour12);
qfour1.setBounds(15,0,800,20);
qfour2.setBounds(15,20,800,15);
qfour3.setBounds(15,60,800,15);
qfour4.setBounds(15,80,800,15);
qfour5.setBounds(15,100,800,15);
qfour6.setBounds(15,120,800,15);
qfour7.setBounds(15,140,800,15);
qfour8.setBounds(15,160,800,15);
qfour9.setBounds(15,180,800,15);
qfour10.setBounds(15,200,800,15);
qfour11.setBounds(15,220,800,15);
qfour12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 5)
{
qfive1 = new Label("Question 5", Label.LEFT);
qfive1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qfive2 = new Label("How much do you like trucks?");
qfive3 = new Label("0");
qfive4 = new Label("1");
qfive5 = new Label("2");
qfive6 = new Label("3");
qfive7 = new Label("4");
qfive8 = new Label("5");
qfive9 = new Label("6");
qfive10 = new Label("7");
qfive11 = new Label("8");
qfive12 = new Label("9");
add(qfive1);
add(qfive2);
add(qfive3);
add(qfive4);
add(qfive5);
add(qfive6);
add(qfive7);
add(qfive8);
add(qfive9);
add(qfive10);
add(qfive11);
add(qfive12);
qfive1.setBounds(15,0,800,20);
qfive2.setBounds(15,20,800,15);
qfive3.setBounds(15,60,800,15);
qfive4.setBounds(15,80,800,15);
qfive5.setBounds(15,100,800,15);
qfive6.setBounds(15,120,800,15);
qfive7.setBounds(15,140,800,15);
qfive8.setBounds(15,160,800,15);
qfive9.setBounds(15,180,800,15);
qfive10.setBounds(15,200,800,15);
qfive11.setBounds(15,220,800,15);
qfive12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 7)
{
finish1 = new Label("Thank You." , Label.CENTER);
finish1.setFont(new Font("Times-Roman", Font.BOLD, 50));
finish2 = new Label("Questionnaire Completed.", Label.CENTER);
finish2.setFont(new Font("Times-Roman", Font.BOLD, 50));
add(finish1);
add(finish2);
finish1.setBounds(0,200,800,60);
finish2.setBounds(0,300,800,60);
}
}
public void actionPerformed(ActionEvent ae)
{
String button = ae.getActionCommand();
text = question.getText();
b = 0;
c = 0;
if (count == 6)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qsix1);
remove(qsix2);
remove(qsix3);
remove(qsix4);
remove(qsix5);
remove(qsix6);
remove(qsix7);
remove(qsix8);
remove(qsix9);
remove(qsix10);
remove(qsix11);
remove(qsix12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("OL"))
{
b = 1;
count = 7;
init();
}
else
{
b = 2;
count = 7;
init();
}
}
if (count == 5)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qfive1);
remove(qfive2);
remove(qfive3);
remove(qfive4);
remove(qfive5);
remove(qfive6);
remove(qfive7);
remove(qfive8);
remove(qfive9);
remove(qfive10);
remove(qfive11);
remove(qfive12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("BR"))
{
b = 1;
count = 6;
init();
}
else
{
b = 2;
count = 6;
init();
}
}
if (count == 4)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qfour1);
remove(qfour2);
remove(qfour3);
remove(qfour4);
remove(qfour5);
remove(qfour6);
remove(qfour7);
remove(qfour8);
remove(qfour9);
remove(qfour10);
remove(qfour11);
remove(qfour12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("no"))
{
b = 1;
count = 5;
init();
}
else
{
b = 2;
count = 5;
init();
}
}
if (count == 3)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qthree1);
remove(qthree2);
remove(qthree3);
remove(qthree4);
remove(qthree5);
remove(qthree6);
remove(qthree7);
remove(qthree8);
remove(qthree9);
remove(qthree10);
remove(qthree11);
remove(qthree12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("black"))
{
b = 1;
count = 4;
init();
}
else
{
b = 2;
count = 4;
init();
}
}
if (count == 2)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qtwo1);
remove(qtwo2);
remove(qtwo3);
remove(qtwo4);
remove(qtwo5);
remove(qtwo6);
remove(qtwo7);
remove(qtwo8);
remove(qtwo9);
remove(qtwo10);
remove(qtwo11);
remove(qtwo12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("yes"))
{
b = 1;
count = 3;
init();
}
else
{
b = 2;
count = 3;
init();
}
}
if (count == 1)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qone1);
remove(qone2);
remove(qone3);
remove(qone4);
remove(qone5);
remove(qone6);
remove(qone7);
remove(qone8);
remove(qone9);
remove(qone10);
remove(qone11);
remove(qone12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("i"))
{
b = 1;
count = 2;
init();
}
else
{
b = 1;
count = 2;
init();
}
}
if (count == 0)
{
remove(intro1);
remove(intro2);
remove(intro3);
remove(start);
count = 1;
init();
}
this.validate();
}
}
In all honesty, you need to re-write your program from scratch so that you can incorporate OOP techniques, arrays, collections, and other advantages that Java has to offer. I recommend:
First of all since your code displays a series of questions and prompts for response, don't hard-code the questions in the code but make them part of the data. Have your program read in a text file that holds the questions. This will allow you to change questions or add questions without altering code.
Create a non-GUI Question class that holds questions and user responses and that is used by the GUI as its "model".
Create an ArrayList of Question objects.
For your GUI, code to the JPanel, not the applet or the JFrame. This will give you the option of using your GUI in a JFrame or a JApplet, or even a JDialog or embedded in another JPanel should you so desire.
If you will need to swap display panels, consider using CardLayout for this purpose.
If however all you'll be doing is changing the text of the question, then display the question text in a JLabel and when you want to change it, call setText(...) on the JLabel passing in the new question's text.
Use the user-friendly layout managers to ease your work of laying out components in the GUI.
Your current code has a lot of unnecessary redundencies. Use of arrays and collections such as ArrayLists will remove many of these redudancies and make debugging and upgrading much easier.
As others have stated and as I stated in my earlier comment, you should move up to the Swing library as it is much more flexible and robust than the AWT gui library that you are currently using. The Swing tutorials will show you what you need to know to create beautiful Swing programs.
Just add a main() method, make a Frame for your applet, add the applet to the frame, and call the applet's init() and start() methods. See my Mandelbrot.java for an example: http://unixshell.jcomeau.com/src/java/com/jcomeau/Mandelbrot.java
One advantage of this approach is that it can be used with any existing applet, to allow it to function as either an applet or application. Use a JFrame if you're using Swing components, otherwise it should work pretty nearly the same.
In general, you'll want to change all the non swing components to swing components. For events, they're roughly the same for both applets and swing applications. Hope it helps.
I'm not sure what you are asking, but if you want it inside a window all you need to do is this:
public Object[] startNewSurvey()
{
java.awt.Frame f = new java.awt.Frame("You're title here.");
f.setSize(new Dimension(<Width>, <Height>));
f.setResizable(false);
survey s = new survey();
s.init();
f.add(s);
f.setVisible(true);
return new Object[] { f, s };
}
That will just instance a brand new frame and put another new instance of your survey class in that frame, then display it. It also returns a 2 sized Object[] array containing the new Frame and survey instances made. Hope that helps.
https://way2java.com/applets/applet-to-application/
Following are the changes to be made from Applet to Application
Delete the statement "import java.applet" package
Replace extends Applet with Frame
Replace the init() method with constructor
Check the layout (for Applet, the default layout is FlowLayout and for Frame, it is BorderLayout)
Add setXXX() methods like setSize() etc.
Add the main() method
HTML is not required (delete it)

Categories

Resources