I am trying to make a JFrame program that interfaces a binary-decimal-hexadecimal converter with buttons. A part of this, I would like to draw circles to represent binary numbers in a row of circles with a filled circle representing a one and an empty circle representing a zero. However, when I try to call repaint to draw anything, it does not execute the paintComponent() method, which I know because it does not perform the print statement inside of it. Full code below:
package e2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
public class DecBin extends JPanel {
String theText = "IT WORKS";
int style = Font.BOLD; // bold only
Font font = new Font("Arial", style, 40);
DecBin() {
JFrame f = new JFrame("Decimal to binary and binary to decimal converter");
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
Font font = new Font("Arial", style, 40);
JLabel textLabel = new JLabel(theText);
textLabel.setFont(font);
JButton b = new JButton("DectoBin");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a decimal number");
int num = Integer.parseInt(msg);
theText = num + " is " + decToBin(num) + " in binary";
textLabel.setText(theText);
}
});
f.add(b);
JButton d = new JButton("BintoDec");
d.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a binary number");
System.out.print("The decimal form of " + msg + " is " + binToDec(msg));
theText = msg + " is " + binToDec(msg) + " in decimal";
textLabel.setText(theText);
}
});
f.add(d);
JButton hd = new JButton("hexToDec");
hd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a hexadecimal number");
theText = msg + " is " + hexToDec(msg) + " in decimal";
textLabel.setText(theText);
}
});
f.add(hd);
JButton dh = new JButton("DectoHex");
dh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a decimal number");
int num = Integer.parseInt(msg);
theText = num + " is " + decToHex(num) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(dh);
JButton bh = new JButton("BinToHex");
bh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a binary number");
theText = msg + " is " + decToHex(binToDec(msg)) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(bh);
JButton hb = new JButton("HexToBin");
hb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a Hexadecimal number");
theText = msg + " is " + decToBin(hexToDec(msg)) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(hb);
JButton c = new JButton("Draw");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.print("test1");
validate();
repaint();
}
});
f.add(c);
f.add(textLabel, BorderLayout.SOUTH);
f.setVisible(true);
}
public static void main(String[] args) {
new DecBin();
}
static String decToBin(int d) {
StringBuilder binary = new StringBuilder("");
while (d != 0) {
binary.insert(0, d % 2);
d = d / 2;
}
return binary.toString();
}
static int binToDec(String b) {
int total = 0;
int x;
for (int i = b.length(); i > 0; i--) {
x = Integer.parseInt(Character.toString(b.charAt(i - 1)));
if (x == 1) {
total += Math.pow(2, b.length() - i);
}
}
return total;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(100, 100, 20, 20);
System.out.print("painted components");
}
static String decToHex(int d) {
StringBuilder Hex = new StringBuilder("");
while (d != 0) {
int remainder = d % 16;
if (remainder < 10) {
Hex.insert(0, d % 16);
} else if (remainder == 10) {
Hex.insert(0, 'A');
} else if (remainder == 11) {
Hex.insert(0, 'B');
} else if (remainder == 12) {
Hex.insert(0, 'C');
} else if (remainder == 13) {
Hex.insert(0, 'D');
} else if (remainder == 14) {
Hex.insert(0, 'E');
} else if (remainder == 15) {
Hex.insert(0, 'F');
}
d = d / 16;
}
return Hex.toString();
}
static int hexToDec(String b) {
int total = 0;
int len = b.length();
for (int i = len - 1; i >= 0; i--) {
if (b.charAt(i) == 'A') {
total += 10 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'B') {
total += 11 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'C') {
total += 12 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'D') {
total += 13 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'E') {
total += 14 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'F') {
total += 15 * Math.pow(16, len - i - 1);
} else {
total += Character.getNumericValue(b.charAt(i)) * Math.pow(16, len - i - 1);
}
}
return total;
}
}
Pertinent code in my opinion is:
DecBin() {
JFrame f=new JFrame("Decimal to binary and binary to decimal converter");
f.setSize(1000,1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
JButton c =new JButton("Draw");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.print("test1");
validate();
repaint();
}
});
f.add(c);
f.setVisible(true);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(100, 100, 20, 20);
System.out.print("painted components");
}
public static void main(String[] args) {
new DecBin();
}
I have spent hours researching this and have yet to find a solution that will get "painted components" to print.
You do not appear to be adding your DecBin panel to any other UI element. It therefore has no reason to be painted.
You should avoid initializing JFrames inside the constructor of your JPanel child class - it should really be the other way around. That will make things easier to understand (and to debug).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
my progress bar is update only to 100%. i check with printing and it's seems everything run as it should be but the UI does not update according to the parameters in the printing check!
here is my Panel class. the main class create frame the adding the MyPanel i create:
public class MyPanel extends JPanel {
File[] DFLIST;
File DF[];
File INP;
File LOG;
JButton chooseDF = new JButton("Choose defect file");
JButton chooseLog = new JButton("Choose log file");
JButton chooseInp = new JButton("Choose inp file");
JButton analayze = new JButton("Analayze");
DefectFileReader[] dfReader;
Document[] docArray;
boolean DFloaded = false;
boolean LOGloaded = false;
boolean INPloaded = false;
Checkbox recipeName;
Checkbox inspectionDuration;
Checkbox area;
Checkbox numberOfDefects;
Checkbox numberOfDefectsPerDetector;
Checkbox sensetivityName;
Checkbox SlicesDetected;
private static int rowIndex = 2;
private static int cellIndex = 4;
FileOutputStream fos;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("analyze_result");
Row row = sheet.createRow(rowIndex);
Cell cell = row.createCell(cellIndex);
XSSFCellStyle csForFirstWrite = workbook.createCellStyle();
XSSFCellStyle csForSecondWrite = workbook.createCellStyle();
XSSFFont fontForBold = workbook.createFont();
XSSFFont fontNotForBold = workbook.createFont();
String totalDuration = "00:00:00";
private int currentFolder = 0;
//TwoRoot t;
JProgressBar pBar = new JProgressBar();
Frame frame = new Frame("Progress Bar");
MyprogressBar taskBar;
/* creating the main panel of the frame - divided to 3 parts. in the north pictures , in the west checkbox , in the east the file chooser */
public MyPanel(){
this.setLayout(new BorderLayout());
this.add(pictureInNorth() , BorderLayout.NORTH);
this.add(checkBoxPanel() , BorderLayout.WEST);
this.add(chooseFilesPanel() , BorderLayout.EAST);
//pBar.setForeground(Color.black);
//pBar.setStringPainted(true);
//this.add(pBar , BorderLayout.SOUTH);
}
/* creating the north panel with the picture */
private JPanel pictureInNorth(){
JPanel toReturn = new JPanel();
toReturn.setBackground(Color.black);
JButton analayzerPic = new JButton(new ImageIcon(new ImageIcon("C:/Users/uvalerx073037/workspace/Analayzer_GUI_Ver2/src/Images/vXqyQkOv.jpeg")
.getImage().getScaledInstance(600, 30,
java.awt.Image.SCALE_SMOOTH)));
analayzerPic.setBackground(Color.black);
toReturn.add(analayzerPic);
return toReturn;
}
/* creating the checkBox in the west */
private JPanel checkBoxPanel(){
recipeName = new Checkbox("Recipe Name" , false);
inspectionDuration = new Checkbox("Inspection Duration" , false);
area = new Checkbox("Area" , false);
numberOfDefects = new Checkbox("Number Of Defects" , false);
numberOfDefectsPerDetector = new Checkbox("Number Of Defects Per Detector", false);
sensetivityName = new Checkbox("Sensetivity Name", false);
SlicesDetected = new Checkbox("Slices were detected" , false);
JPanel toReturn = new JPanel();
toReturn.setLayout(new BoxLayout(toReturn, BoxLayout.Y_AXIS));
toReturn.add(recipeName);
toReturn.add(inspectionDuration);
toReturn.add(numberOfDefects);
toReturn.add(numberOfDefectsPerDetector);
toReturn.add(sensetivityName);
toReturn.add(SlicesDetected);
toReturn.add(area);
return toReturn;
}
/*creating the file chooser in the east */
private Box chooseFilesPanel(){
MyActionListener lis = new MyActionListener();
chooseDF.addActionListener(lis);
chooseInp.addActionListener(lis);
chooseLog.addActionListener(lis);
analayze.addActionListener(lis);
analayze.setForeground(Color.BLUE);
Box toReturn = Box.createVerticalBox();
toReturn.add(Box.createGlue());
toReturn.add(chooseDF);
toReturn.add(Box.createGlue());
toReturn.add(chooseLog);
toReturn.add(Box.createGlue());
toReturn.add(chooseInp);
toReturn.add(Box.createGlue());
toReturn.add(analayze).setSize(50,50);
return toReturn;
}
/* function to check after the user clicked on the analyze button if all the conditions are OK */
public Boolean isValidToStart(){
if(DFloaded == false && LOGloaded == false && INPloaded == false){
JOptionPane.showMessageDialog(null, "NO FILE WAS LOADED!!!", "User Error" , JOptionPane.ERROR_MESSAGE);
return false;
}
if(recipeName.getState() == false && inspectionDuration.getState() == false && area.getState() == false &&
numberOfDefects.getState() == false && numberOfDefectsPerDetector.getState() == false && sensetivityName.getState() == false){
JOptionPane.showMessageDialog(null , "NO CHECK BOX WAS MARKED!!!" + "\n" + "WHAT DATA WOULD YOU LIKE TO COLLECT?" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
if(area.getState() == true && (LOGloaded == false || DFloaded == false || INPloaded == false)){
JOptionPane.showMessageDialog(null , "IF YOU WANT TO COLLECT AERA YOU NEED TO CHOOSE INP + LOG + DEF" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
if(SlicesDetected.getState() == true && LOGloaded == false){
JOptionPane.showMessageDialog(null , "You need to load the LOG in order to get the amount of slices were detected!" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
else
return true;
}
/* build the row of the titles , only what the user marked in the check box */
private void firstWriteToExcel(DefectFileReader curDF , XSSFSheet sheet , XSSFWorkbook workbook , FileOutputStream fos) throws Exception{
fontForBold.setBold(true);
csForFirstWrite.setFont(fontForBold);
csForFirstWrite.setFillForegroundColor(new XSSFColor(java.awt.Color.lightGray));
csForFirstWrite.setFillPattern(CellStyle.SOLID_FOREGROUND);
csForFirstWrite.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
if(recipeName.getState() == true){
row = sheet.createRow(rowIndex - 1);
row.createCell(cellIndex).setCellValue("Recipe Name: " + curDF.getRecipeName());
sheet.autoSizeColumn(cellIndex);
}
row = sheet.createRow(rowIndex++);
row.createCell(cellIndex).setCellValue("inspection index");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
if(numberOfDefects.getState() == true){
row.createCell(cellIndex).setCellValue("Total Defects");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(numberOfDefectsPerDetector.getState() == true){
ArrayList<String> toOtherFunc = new ArrayList<String>();
toOtherFunc = curDF.getDetectorNames();
for(int i=0; i < toOtherFunc.size() ; i++){
row.createCell(cellIndex).setCellValue(toOtherFunc.get(i));
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
}
if(sensetivityName.getState() == true){
row.createCell(cellIndex).setCellValue("sensetivity Name");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(LOGloaded == true){
row.createCell(cellIndex).setCellValue("Slices were detected");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(inspectionDuration.getState()==true){
row.createCell(cellIndex).setCellValue("Inspection Duration");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
for (Row row : sheet){
for (Cell cell_local : row){
cell_local.setCellStyle(csForFirstWrite);
}
}
System.out.println("row index is: " + rowIndex + "cell index is: " + cellIndex);
}
/* fill the excel in the data were collected */
private void writeToExcel(DefectFileReader curDF , XSSFSheet sheet , XSSFWorkbook workbook , FileOutputStream fos) throws Exception{
fontNotForBold.setBold(false);
csForSecondWrite.setFont(fontNotForBold);
csForSecondWrite.setFillForegroundColor(new XSSFColor(java.awt.Color.white));
csForSecondWrite.setFillPattern(CellStyle.SOLID_FOREGROUND);
csForSecondWrite.setBorderBottom(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderTop(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderRight(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellIndex = 4;
row = sheet.createRow(rowIndex++);
row.createCell(cellIndex++).setCellValue("inspection_" + (rowIndex - 3));
if(numberOfDefects.getState() == true)
row.createCell(cellIndex++).setCellValue(curDF.getTotalDefects());
if(numberOfDefectsPerDetector.getState() == true){
ArrayList<String> toOtherFunc = new ArrayList<String>();
int[] toPrintNumber = new int[toOtherFunc.size()];
toOtherFunc = curDF.getDetectorNames();
System.out.println(toOtherFunc);
toPrintNumber = curDF.getDefectPerDetector(toOtherFunc);
for(int i=0; i < toOtherFunc.size() ; i++)
row.createCell(cellIndex++).setCellValue(toPrintNumber[i]);
}
if(sensetivityName.getState() == true)
row.createCell(cellIndex++).setCellValue(curDF.getSensetivityName());
if(LOGloaded == true){
LogFileReader logReader = new LogFileReader(LOG , curDF.getInspectionEndTime());
ArrayList<String> toLog = curDF.getRunsIndex();
String toPrint = "";
for(int i=0 ; i < toLog.size() ; i = i+2)
toPrint += toLog.get(i) + ": " + logReader.diagnozeLog(toLog.get(i+1)) + " ";
if(toPrint.equals(""))
row.createCell(cellIndex).setCellValue("The data of this run is not in this log!");
else
row.createCell(cellIndex).setCellValue(toPrint);
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(inspectionDuration.getState()==true)
row.createCell(cellIndex++).setCellValue(curDF.inspectionDuration());
for (Row row : sheet){
if( row.getRowNum() > 2){
for (Cell cell_local : row){
cell_local.setCellStyle(csForSecondWrite);
}
}
}
System.out.println("row index is: " + rowIndex + " cell index is: " + cellIndex);
}
/* adding the inspection time of the current run to the total time */
public String sumTimes(String time1) {
PeriodFormatter formatter = new PeriodFormatterBuilder()
.minimumPrintedDigits(2)
.printZeroAlways()
.appendHours()
.appendLiteral(":")
.appendMinutes()
.appendLiteral(":")
.appendSeconds()
.toFormatter();
org.joda.time.Period period1 = formatter.parsePeriod(time1);
org.joda.time.Period period2 = formatter.parsePeriod(totalDuration);
return formatter.print(period2.plus(period1).normalizedStandard());
}
public void initializeFrame(){
frame.setSize(300, 100);
pBar.setForeground(Color.black);
pBar.setStringPainted(true);
frame.add(pBar);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MyprogressBar extends SwingWorker<Void, Integer> {
JProgressBar pBar;
int max;
int currentFolder;
public MyprogressBar(JProgressBar curBar , int max , int currentFolder){
this.pBar = curBar;
this.max = max;
this.currentFolder = currentFolder;
}
public void done(){
}
#Override
protected Void doInBackground() throws Exception {
System.out.println("i'm in background");
double i = currentFolder;
double t = DFLIST.length;
double toSetInDouble = (i/t);
int toSet = (int) (toSetInDouble * 100);
pBar.setValue(toSet);
System.out.println(toSet);
repaint();
Thread.sleep(10);
publish(toSet);
return null;
}
}
/* adding listener to all of the buttons and check boxes */
public class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
if(click.getSource() == chooseDF){
File directory;
FilenameFilter f = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.length()<=2;
}
};
FilenameFilter def = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".def");
}
};
JFileChooser chooser = new JFileChooser(System.getProperties().getProperty("user.dir"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
DFloaded = true;
directory = chooser.getSelectedFile();
File[] fileList = directory.listFiles(f);
Arrays.sort(fileList , new NaturalOrderComparator());
DFLIST = new File[fileList.length];
for(int i = 0 ; i<fileList.length ; i++){
File[] tmp = fileList[i].listFiles(def);
for(int j=0 ; j<tmp.length ; j++)
DFLIST[i] = tmp[j];
}
}
}
if(click.getSource() == chooseInp){
JFileChooser fc2 = new JFileChooser();
if (fc2.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
INPloaded = true;
INP = fc2.getSelectedFile();
}
}
if(click.getSource() == chooseLog){
JFileChooser fc3 = new JFileChooser();
if(fc3.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
LOGloaded = true;
LOG = fc3.getSelectedFile();
}
}
if(click.getSource() == analayze){
Boolean valid = isValidToStart();
if(valid == true){
try{
fos = new FileOutputStream("c:/temp/analayze.xlsx");
if(DFloaded == true){
try {
initializeFrame();
DF = new File[DFLIST.length];
dfReader = new DefectFileReader[DFLIST.length];
docArray = new Document[DFLIST.length];
for( ; currentFolder < DFLIST.length ; currentFolder++){
new MyprogressBar(pBar, 100, currentFolder + 1).execute();
frame.repaint();
System.out.println("i'm sending the file down here to parse from file to document");
System.out.println(DFLIST[currentFolder].getAbsoluteFile());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
docArray[currentFolder] = (Document) db.parse(DFLIST[currentFolder]);
docArray[currentFolder].getDocumentElement().normalize();
dfReader[currentFolder] = new DefectFileReader(DFLIST[currentFolder] , docArray[currentFolder]);
dfReader[currentFolder].getRunsIndex();
totalDuration = sumTimes(dfReader[currentFolder].inspectionDuration());
if(currentFolder==0){
firstWriteToExcel(dfReader[0], sheet, workbook, fos);
writeToExcel(dfReader[0], sheet, workbook, fos);
}
if(currentFolder!=0)
writeToExcel(dfReader[currentFolder] , sheet , workbook , fos );
repaint();
if(INPloaded == true){
}
DFLIST[currentFolder] = null;
dfReader[currentFolder].clearDfReader();
docArray[currentFolder] = null;
System.gc();
}
}
catch(Exception e ) {
System.out.println(e);
System.exit(0);
}
}
row = sheet.createRow(rowIndex);
totalDuration = sumTimes("00:00:00");
if(inspectionDuration.getState() == true){
row.createCell(cellIndex - 1).setCellValue(totalDuration);
row.getCell(cellIndex - 1).setCellStyle(csForFirstWrite);
}
((Workbook) workbook).write(fos);
workbook.close();
JOptionPane.showMessageDialog(null, "Your data has been analyze!\n you can find the result in c:\\temp");
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
#Udi it would have been really great if you could have pasted a structured code. However, with whatever code you pasted, here is an indicative solution using swingworker. You just need to call your whole actionPerformed() code from doInBackground() of swingworker. Hope it helps.
Moreover, I find the java docs of swingworker a very useful to understand how it works. Examples are very simple yet well explained.
https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html
// use this code inside actionPerformed()
new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
// all your code goes here
for( ; currentFolder < DFLIST.length ; currentFolder++){
double f = currentFolder + 1;
double t = DFLIST.length;
double currentPercentInDouble = (f / t);
int currentPercent = (int) (currentPercentInDouble * 100);
// send the current progress to progress bar. This needs to be updated to progress bar in process() method
publish(currentPercent)
}
// rest of the code
}
#Override
protected void process(List<V> chunks) {
// update the progress bar here
}
}.execute();
I need help tweaking my code. I need to write a program that outputs the count of individual ascii characters in a txt file that the user uploads, but I'm having a lot of problems trying to get the array that I count into the GUI portion of the program that "draws" the data on the screen.
I have the output looking how I want, but I can't figure out how to get the character count up there
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.FileReader; // both needed
import java.io.BufferedReader;
import java.io.IOException;
public class textreader extends Frame implements ActionListener
{
String dataFilePath = null;
String dataFileName = null;
int[] counter = new int[256];
String command = "";
public static void main(String[] args)
{
Frame frame = new textreader();
frame.setResizable(true);
frame.setSize(1000,850);
frame.setVisible(true);
}
public textreader()
{
setTitle("Text File Processing");
// Menu Creation
MenuBar mn = new MenuBar();
setMenuBar(mn);
// Create "File" and add it
Menu fileMenu = new Menu("File");
mn.add(fileMenu);
// Create Menu Items, Add action Listener, Add to "File" Menu Group
// Open file
MenuItem miOpen = new MenuItem("Open");
miOpen.addActionListener(this);
fileMenu.add(miOpen);
// Process file
MenuItem miProcess = new MenuItem("Process");
miProcess.addActionListener(this);
fileMenu.add(miProcess);
// Exit program
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
fileMenu.add(miExit);
// To Terminate
WindowListener d = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// listener registry
this.addWindowListener(d);
this.addComponentListener(k);
}
public void actionPerformed (ActionEvent ev)
{
// which command was issued?
command = ev.getActionCommand();
// act
if("Open".equals(command))
{
dataFilePath = null;
dataFileName = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
dataFilePath = chooser.getSelectedFile().getPath();
dataFileName = chooser.getSelectedFile().getName();
}
repaint();
}
else
if("Process".equals(command))
{
try
{
// Initialize
int[] aCount = new int[256];
// "Instantiate" streams
BufferedReader inputStream = new BufferedReader(new FileReader(dataFilePath));
// read the file line by line and count the characters read
String line = null;
char c = 0;
int lineLength = 0;
int charValue = 0;
while ((line = inputStream.readLine()) != null)
{
// ********* process line
for (int i = 0; i < line.length(); i++)
{
char ch = line.charAt(i);
if (ch >= 0 && ch <= 255)
{
counter[(int)ch]++;
}
else
{ // silently ignore non-ASCII characters
}
// count newline at the end
counter['\n']++;
}
}
}
catch(IOException ioe)
{
System.out.print("You want to run that by me again?");
}
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
}
//********************************************************
//called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
if("Open".equals(command))
{
// Acknowledge that file was opened
if (dataFileName != null)
{
g.drawString("File -- "+dataFileName+" -- was successfully opened", 400, 400);
}
else
{
g.drawString("NO File is Open", 400, 400);
}
return;
}
else
if("Process".equals(command))
{
for(int i = 0; i < 256; i++)
{
int x = 100;
int y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 30;
int line = 0;
for(int j = 0; j < 256; j++)
{
line++;
g.drawString(Integer.toString(j), x, y);
g.drawString(Character.toString((char)j), x + 50, y); // Converts the # to a char, then to a String
// This part of the code adds a new column when the flag reaches 43
if(line == 45)
{
x = x + 150;
y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 15;
line = 0;
}
y = y+15;
}
}
return;
}
}
}
Your charValue variable appears to break your logic. You should remove it. This is sufficient:
for (int i=0; i<alphabetArray.length; i++)
alphabetArray[i] = 0; // set initial values
while ((line = inputStream.readLine()) != null) {
for(int i=0; i<line.length(); i++)
alphabetArray[(int)line.charAt(i)]++; // use the ASCII value of the character as an index
}
Your alphabet counter also seems to go out of scope. Either (1) make alphabetArray an instance variable of the class, or (2) display its contents before it goes out of scope. I think #1 is preferable.
I'd also be concerned about this line:
System.out.println(c + " : "+ char.alphabetArray[i]);
char is a datatype, and alphabetArray does not exist inside of it (and technically doesn't exist anywhere at this point since it's gone out of scope). c is also undefined. Take advantage of ASCII values! However, be careful printing non-printable characters and such. Your output will look really funky.
System.out.println((char)i + " : "+ alphabetArray[i]);
Of course, you'd still need to make alphabetArray accessible somehow.
What i am trying to do is when i click a button, i copy some files from a portable drive like usb and copy those files to my local drive, then i read all csv files which i copied ealier and i put it's values in an arraylist and inject it to database, and then i can delete those files, and i want to show the process in progress bar based on process completion. so this is what i do :
void main()
{
JButton btnTransfer = new JButton("Transfer");
Image transferIMG = ImageIO.read(new File("C:\\Users\\User\\Desktop\\images\\transfer.png"));
btnTransfer.setIcon(new ImageIcon(transferIMG));
btnTransfer.setPreferredSize(new Dimension(110, 90));
btnTransfer.setOpaque(false);
btnTransfer.setContentAreaFilled(false);
btnTransfer.setBorderPainted(false);
btnTransfer.setVerticalTextPosition(SwingConstants.BOTTOM);
btnTransfer.setHorizontalTextPosition(SwingConstants.CENTER);
btnTransfer.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
File csvpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\csv");
File htmlpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\html");
String removepath = fileList1.getSelectedValue() + "\\salestablet\\report";
if(csvpath.listFiles().length > 0 && htmlpath.listFiles().length > 0)
{
File[] csvarr = csvpath.listFiles();
File[] htmlarr = htmlpath.listFiles();
try
{
copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
JPanel ButtonCont = new JPanel(new GridLayout(4, 1, 5, 0));
ButtonCont.setBackground(Color.LIGHT_GRAY);
ButtonCont.add(btnTransfer);
gui.add(ButtonCont , BorderLayout.EAST);
frame.setContentPane(gui);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setMinimumSize(new Dimension(900, 100));
frame.pack();
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void copyFileUsingStream(File[] csvsources, File[] htmlsources, String dest, String removepath) throws IOException
{
int count = 0;
int MaxCount = countprocess(csvsources, htmlsources);
progressBar = new JProgressBar(0, MaxCount);
progressBar.setStringPainted(true);
InputStream is = null;
OutputStream os = null;
String csvfolderpath = dest + "\\csv";
String htmlfolderpath = dest + "\\html";
if(!(new File(csvfolderpath)).exists())
{
(new File(csvfolderpath)).mkdirs(); //create csv folder;
}
if(!(new File(htmlfolderpath)).exists())
{
(new File(htmlfolderpath)).mkdirs(); //create csv folder;
}
for(int i= 0; i < csvsources.length; i++) //copy all csv files to csv folder
{
try
{
is = new FileInputStream(csvsources[i]);
os = new FileOutputStream(csvfolderpath + "\\" + csvsources[i].getName());
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
is.close();
os.close();
}
}
for(int i= 0; i < htmlsources.length; i++) //copy all html, images and css to html folder
{
if(htmlsources[i].isFile())
{
try
{
is = new FileInputStream(htmlsources[i]);
os = new FileOutputStream(htmlfolderpath + "\\" + htmlsources[i].getName());
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
is.close();
os.close();
}
}
else if(htmlsources[i].isDirectory()) //for subfolder
{
String path = dest + "\\html\\" + htmlsources[i].getName();
if(!new File(path).exists())
{
(new File(path)).mkdirs(); //create subfolder;
}
File[] arr = (new File(htmlsources[i].getAbsolutePath())).listFiles();
for(int j = 0; j < arr.length; j++)
{
if(arr[j].isFile())
{
try
{
is = new FileInputStream(arr[j]);
os = new FileOutputStream(path + "\\" + arr[j].getName());
byte[] buffer = new byte[1000000];
int length;
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
if(htmlsources[i].getName().contains("images"))
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
is.close();
os.close();
}
}
}
}
}
ArrayList<String > DBValues = new ArrayList<String>(); //read all csv files values
File f1 = new File(csvfolderpath);
for(int i = 0; i < f1.listFiles().length; i++)
{
if(f1.listFiles()[i].isFile())
{
FileReader fl = new FileReader(f1.listFiles()[i]);
BufferedReader bfr = new BufferedReader(fl);
for(int j = 0; j < 2; j++)
{
if(j == 1)
{
DBValues.add(bfr.readLine());
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
else
{
bfr.readLine();
}
}
bfr.close();
}
}
/*for(int x = 0; x < DBValues.size(); x++)
{
//System.out.println(DBValues.get(x));
}*/
//removing csv in local computer
File f2 = new File(csvfolderpath);
File[] removelist = f2.listFiles();
for(int x = 0; x < removelist.length; x++)
{
if(removelist[x].isFile())
{
removelist[x].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}
//removing csv in device
File f3 = new File(removepath + "\\csv");
if(f3.isDirectory())
{
removelist = f3.listFiles();
for(int y = 0; y < removelist.length; y++)
{
try
{
if(removelist[y].isFile())
{
//System.out.println(removelist[y].getName());
removelist[y].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
//removing html and images in device
File f4 = new File(removepath + "\\html");
if(f4.isDirectory())
{
removelist = f4.listFiles();
for(int z = 0; z < removelist.length; z++)
{
try
{
if(removelist[z].isFile())
{
removelist[z].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
else if(removelist[z].isDirectory())
{
if(removelist[z].getName().contains("images"))
{
File[] subfolder = removelist[z].listFiles();
for (int idx = 0; idx < subfolder.length; idx++)
{
if(subfolder[idx].isFile())
{
subfolder[idx].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
/* JProgressBar progressBar = new JProgressBar();
progressBar.setValue(25);
progressBar.setStringPainted(true);*/
Border border = BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
gui.add(progressBar, BorderLayout.SOUTH);
gui.repaint();
gui.revalidate();
// System.out.println(count);
}
private static int countprocess(File[] csv, File[] html_image)
{
int x = 0;
int y = 0;
int z = 0;
for(int i = 0; i < csv.length; i++)
{
if(csv[i].isFile())
{
x += 1;
}
} //get total count of csv files throught loop
for(int i = 0; i < html_image.length; i++)
{
if(html_image[i].isFile())
{
y += 1;
}
else if(html_image[i].isDirectory())
{
if(html_image[i].getName().contains("images"))
{
File[] flist = html_image[i].listFiles();
for(int j = 0; j < flist.length; j++)
{
z += 1;
}
}
} //get total count of html and images files throught loop
}
return ((4*x) + (2*y) + (2*z));
}
so i tried to refresh my progress bar value by setting it's value like this
progressBar.setValue((count / MaxCount) * 100);
but somehow i can't make it to work, my progress bar does not showing it's progress like 1% 2% 3%.. 10% and so on.. instead it's only show 100% when it's process completed.. what i miss here?
note : i also have tried to set my progress bar value this way progressBar.setValue(count); still no luck.
Reviewing your whole code will take a while. But, inside your btnTransfer.addActionListener's actionPerformed function you are trying to copy stream which might take a while. Any kind of event listener is performed in event dispatch thread. Please refer to this answer for more details.
Now as a quick solution:
put your copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath); function inside a in-line thread:
new Thread()
{
public void run()
{
copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
}
}.start();
}
Put your progress update of JProgressBar inside SwingUtilities.invokeLater and make the (count/MaxCount) computation by casting one of them to double, as follows:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
count += 1;
progressBar.setValue((int) (((double)count/ MaxCount) * 100));
}
});
as count is local to the copyFileUsingStream function, please try to declare it in your class context to access and change.
But SwingWorker is preferable for this kind of task.
Tutorial Resources:
Worker Threads and SwingWorker
How to use progress bars with swing worker
ProgressBar Demo with SwingWorker
You are setting a value in your progress bar to a percent complete. But the max value of your progress bar is actually the total number of items.
Instead, you need to just set your progressbar value to your current count and get rid of the calculation for the %.
Something like:
progressBar.setValue(count );
Also you should be doing your long running task in a SwingWorker thread so that you don't have to force repainting of the GUI.
I have created a java GUI that works as a 6-question questionnaire. For each of the six question, I have 4 choices , i, ii, iii, iv for the user to choose, and then type out one of the four choices in a text box, then click a button "enter" to go to the next question. After all six questions have been answered, it will jump to a finish page.
I want to write the input value (in the text box) of each question to a text file. So After clicking on the "enter button" to answer all six questions I can see something like "i ii iii i ii iii" in a text file.
Is there a way to do it?
Here is my code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class HTML 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;
private Label qone1, qone2, qone3, qone4, qone5, qone6;
private Label qtwo1, qtwo2, qtwo3, qtwo4, qtwo5, qtwo6;
private Label qthree1, qthree2, qthree3, qthree4, qthree5, qthree6;
private Label qfour1, qfour2, qfour3, qfour4, qfour5, qfour6;
private Label qfive1, qfive2, qfive3, qfive4, qfive5, qfive6;
private Label qsix1, qsix2, qsix3, qsix4, qsix5, qsix6;
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. In order to show the most appropriate advertisement, we would like to know more about your personal preferences.");
add(intro1);
add(intro2);
intro1.setBounds(0,0,800,20);
intro2.setBounds(15,20,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("On average, How many hours do you spend on playing sports every week?");
qone3 = new Label("i.0-2");
qone4 = new Label("ii.3-6");
qone5 = new Label("iii.7-10");
qone6 = new Label("iv.10+");
add(qone1);
add(qone2);
add(qone3);
add(qone4);
add(qone5);
add(qone6);
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);
add(question);
add(enter);
question.setBounds(15,140,70,15);
enter.setBounds(90,140,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("On average, How many hours do you spend on qsixening to music every week?");
qtwo3 = new Label("i. 0-4 ");
qtwo4 = new Label("ii. 5-10");
qtwo5 = new Label("iii. 11-20");
qtwo6 = new Label("iv. 20+");
add(qtwo1);
add(qtwo2);
add(qtwo3);
add(qtwo4);
add(qtwo5);
add(qtwo6);
qtwo1.setBounds(15,20,800,15);
qtwo2.setBounds(15,40,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);
add(question);
add(enter);
question.setBounds(15,140,70,15);
enter.setBounds(90,140,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("On average, How many hours do you spend on using computers every week?");
qthree3 = new Label("i.0-2");
qthree4 = new Label("ii.3-10");
qthree5 = new Label("iii.11-15");
qthree6 = new Label("iv.20+");
add(qthree1);
add(qthree2);
add(qthree3);
add(qthree4);
add(qthree5);
add(qthree6);
qthree1.setBounds(15,20,800,20);
qthree2.setBounds(15,40,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);
add(question);
add(enter);
question.setBounds(15,140,70,15);
enter.setBounds(90,140,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("On average, How many hours do you spend on groceries every week?");
qfour3 = new Label("i.0-2");
qfour4 = new Label("ii.3-10");
qfour5 = new Label("iii.11-15");
qfour6 = new Label("iv.20+");
add(qfour1);
add(qfour2);
add(qfour3);
add(qfour4);
add(qfour5);
add(qfour6);
qfour1.setBounds(15,20,800,15);
qfour2.setBounds(15,40,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);
add(question);
add(enter);
question.setBounds(15,140,70,15);
enter.setBounds(90,140,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("On average, How many hours do you spend on watching TV every week?");
qfive3 = new Label("i.0-2");
qfive4 = new Label("ii.3-10");
qfive5 = new Label("iii.11-15");
qfive6 = new Label("iv.20+");
add(qfive1);
add(qfive2);
add(qfive3);
add(qfive4);
add(qfive5);
add(qfive6);
qfive1.setBounds(15,20,800,15);
qfive2.setBounds(15,40,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);
add(question);
add(enter);
question.setBounds(15,140,70,15);
enter.setBounds(90,140,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 6)
{
qsix1 = new Label("Question 6", Label.LEFT);
qsix1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qsix2 = new Label("On average, How many times do you spend with family every week?");
qsix3 = new Label("i.0-2");
qsix4 = new Label("ii.3-10");
qsix5 = new Label("iii.11-15");
qsix6 = new Label("iv.20+");
add(qsix1);
add(qsix2);
add(qsix3);
add(qsix4);
add(qsix5);
add(qsix6);
qsix1.setBounds(15,20,800,15);
qsix2.setBounds(15,40,800,15);
qsix3.setBounds(15,60,800,15);
qsix4.setBounds(15,80,800,15);
qsix5.setBounds(15,100,800,15);
qsix6.setBounds(15,120,800,15);
add(question);
add(enter);
question.setBounds(15,140,70,15);
enter.setBounds(90,140,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
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);
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);
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);
}
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);
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);
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);
if(input.equals("i"))
{
b = 1;
count = 2;
init();
}
else
{
b = 1;
count = 1;
init();
}
}
if (count == 0)
{
remove(intro1);
remove(intro2);
remove(start);
count = 1;
init();
}
this.validate();
}
}
Sure, something like
OutputStream out = new FileOutputStream("/path/to/your/file");
out.write(answer.getBytes());
out.close();