What in my code can be indentified as virus? - java

When I finish to do my home task, I get error "could not find or load main class".
I spent near 20 minutes in fully disunderstanding. Reason was "Kaspersky Anti-Virus", which was blocking my MyClass.class.
Here is the code, anyone knows, what's here Kaspersky can indentified as virus?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class CryptoUtil extends JFrame{
private String keyWord;
private JFileChooser inputFileChooser = new JFileChooser();
private JButton openFileChooser = new JButton("Выбрать файл");
private JTextField inputKeyWord = new JTextField();
private JButton operate = new JButton("Выполнить");
private File inputFile;
private File encode;
private File decode;
private String inputData;
public CryptoUtil(){
initFrame();
}
public void initFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Шифратор/дешифратор XOR");
this.setLayout(new GridLayout(3, 1));
this.setSize(300, 100);
operate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
operate();
Desktop.getDesktop().open(new File(encode.getParent()));
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
openFileChooser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
inputFileChooser.showOpenDialog(CryptoUtil.this);
}
});
this.add(openFileChooser);
this.add(inputKeyWord);
this.add(operate);
}
public void operate() throws IOException {
keyWord = inputKeyWord.getText();
inputFile = inputFileChooser.getSelectedFile();
encode = new File(inputFile.getParent() + "//encode.txt");
decode = new File(inputFile.getParent() + "//decode.txt");
BufferedReader br = new BufferedReader(new FileReader(inputFile));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
inputData = sb.toString();
br.close();
PrintWriter writerEn = new PrintWriter(encode, "UTF-8");
writerEn.print(encrypt(inputData, keyWord));
writerEn.close();
PrintWriter writerDe = new PrintWriter(decode, "UTF-8");
writerDe.print(decrypt(encrypt(inputData, keyWord), keyWord));
writerDe.close();
}
public byte[] encrypt(String text, String keyWord){
byte[] arr = text.getBytes();
byte[] keyArr = keyWord.getBytes();
byte[] result = new byte[arr.length];
for(int i = 0; i < arr.length; i++){
result[i] = (byte) (arr[i] ^ keyArr[i % keyArr.length]);
}
return result;
}
public String decrypt(byte[] text, String keyWord){
byte[] result = new byte[text.length];
byte[] keyArr = keyWord.getBytes();
for(int i = 0; i < text.length;i++){
result[i] = (byte) (text[i] ^ keyArr[i% keyArr.length]);
}
return new String(result);
}
public static void main(String[] args) {
new CryptoUtil().setVisible(true);
}
}

You can add your file as trusted in kaspersky antivirus, same happened with me also, necessarily it won't be a virus.

Related

How to connect method from another class to actionListener?

I'm trying to finish my project about searching graphs, where one of the functions is input (vertex and edges) from user.
I already have a method for this in another class, but now I need to put it into GUI.
I've already tried many of tutorials, but nothing worked. Can somebody help me, how to put the method getInputFromCommand to gui?
I've already tried to copy the method into the GUI, but there was problem with the "return g" because of the void result type, I've tried just to call the method, (I know.. stupid) but it didn't work either.
package Process;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
public static FindIslands getInputFromCommand() {
FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return g;
}
}
Where important is the last method "getInputFromCommand()"
and... gui
package Process;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.Scanner;
public class Guicko extends JFrame {
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
public Guicko() {
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FindIslands.getInputFromCommand();
}
});
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String str = "asd";
FindIslands g = null;
g.connectedComponents();
textArea1.setText(str);
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
}
I'm sure there are many correct ways this code can be fixed, but in IMHO, your Guicko class needs to have a FindIslands class member, and I think you need to move some stuff from FindIslands.main() into Guicko.main() or some other method.
Then your "Action Listener" inner classes' actionPerformed methods just delegate to the methods in the FindIslands member instance, like this
....
private FindIslands fi;
public Guicko() {
....
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fi = FindIslands.getInputFromCommand();
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String comps = fi.connectedComponents();// method needs to return a string
textArea1.setText(comps);
}
});
}
The whole idea of seperating GUI from domain is to make changes easily. GUI has knowledge of the domain but domain has no knowledge about the GUI. We can use an interface to seperate them, in that case, Domain says , i don't care who implements this interface but whoever implements this interface will get response and can work with me.
So , If we create a new GUI, we can let it implements that interface and the same domain will work with that GUI.
There are many mistakes but in order to make it work and to show you an example i did few changes.
public class Guicko extends JFrame implements PropertyChangeListener{
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
private FindIslands land;
private JTextField textField;
private JButton button;
public Guicko() {
JPanel panel = new JPanel();
super.getContentPane().setLayout(new GridLayout());
//For each gui, there should be one land.
this.setLand(new FindIslands(100));
//Subscribe to the domain so that you can get update if something change in domain.
this.getLand().subscribe(this);
//Dummy buttons are fields(need too initiate first)
textField2 = new JTextField("",30);
štartButton = new JButton();
textField = new JTextField("",30);
button = new JButton();
button.setPreferredSize(new Dimension(100, 40));
button.setText("Get input from Domain");
štartButton.setPreferredSize(new Dimension(100, 40));
textField.setEditable(false);
štartButton.setText("Start");
panel.add(textField2);
panel.add(štartButton);
panel.add(textField);
panel.add(button);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
//When you type something in , then this function will send it to domain(i mean to function : getInputFromCommand();).
this.addListerToField(štartButton,this.getLand(),textField2);
//Now the second case, suppose you press a button and want something to show up in textfield. In that case , this function will do work.
this.addListerToSecondField(button,this.getLand(),textField);
}
//Here i can catch the events from the domain.
#Override
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals("String changed")) {
this.getTextField().setText((String) e.getNewValue());
}
}
private void addListerToSecondField(JButton button, FindIslands land, JTextField field) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.requireArgumentsForField();
}
});
}
private void addListerToField(JButton štartButton, FindIslands land, JTextField field) {
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.getInputFromCommand(field.getText());
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
public FindIslands getLand() {
return land;
}
public void setLand(FindIslands land) {
this.land = land;
}
public JTextField getTextField() {
return textField;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
Here is the second class. Run it and try to get feeling for it how it works.
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
//initialize the list
this.setListeners(new ArrayList<>());
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
//You need only one main class, not two.----------------------------
/**
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
**/
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
//Static cases are to be avoided.This is the property of object not class.
public void getInputFromCommand(String string) {
//Here you will recieve a string from the GUI and will be printed in command prompt.You can do whatever you want to do with it.
System.out.println("Recieve string is " + string);
//No idea what you are trying to do.
/** FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return line;**/
}
//This function is triggered with second button and you can send data to gui as shown below.
public void requireArgumentsForField() {
//Suppose i want to send following string.
String name = "I don't know";
this.getListeners().stream().forEach(e -> {
// I will catch this in view.
e.propertyChange(new PropertyChangeEvent(this, "String changed", null, name));
});
}
private ArrayList<PropertyChangeListener> listeners;
//Let the objects subscibe. You need this to publish the changes in domain.
public void subscribe(PropertyChangeListener listener) {
this.getListeners().add(listener);
}
public ArrayList<PropertyChangeListener> getListeners() {
return listeners;
}
public void setListeners(ArrayList<PropertyChangeListener> listeners) {
this.listeners = listeners;
}

Get the character of a JLabel in Java

I have a JLabel array that contains many words. I am trying to get the first character of the words. In fact I am trying to get all the character, but if I see how to get the first, I will get the others.
I tried this
mport java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class WordSearchFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static final int COLS_IN_WORDLIST = 1;
private static final int FRAME_WIDTH = 640;
private static final int FRAME_HEIGHT = 480;
private JLabel[][] wordSearch;
private JLabel[] wordListLabels;
private JPanel wordListPanel;
private JPanel wordsearchPanel;
private JPanel rightSidePanel;
private JPanel leftSidePanel;
private JPanel searchButtonPanel;
private JButton searchButton;
private int numRows;
private int numCols;
private ActionListener searchButtonListener;
private ArrayList<String> wordList;
class SearchListener implements ActionListener {
private int x = 0;
public void actionPerformed(ActionEvent event) {
wordListLabels[0].setForeground(Color.BLACK);
if (x == 0) {
findword(x);
x++;
} else {
wordListLabels[x - 1].setForeground(Color.BLACK);
findword(x);
x++;
}
}
private void findword(int x) {
wordListLabels[x].setForeground(Color.RED);
findword2(x);
}
private void findword2(int x) {
for (int i = 0; i < 7; i++)
wordSearch[x + i][x].setForeground(Color.RED);
}
}
private void buildLeftSidePanel() throws WordSearchException, IOException {
leftSidePanel = new JPanel();
leftSidePanel.setLayout(new BorderLayout());
leftSidePanel.setBorder(new TitledBorder(new EtchedBorder(), "Word Search"));
wordsearchPanel = new JPanel();
wordsearchPanel.setLayout(new GridLayout(numRows, numCols));
leftSidePanel.add(wordsearchPanel, BorderLayout.CENTER);
this.getContentPane().add(leftSidePanel, BorderLayout.CENTER);
}
private void initGridFromFile(String wordSearchFilename) throws WordSearchException, IOException {
this.numRows = 0;
this.numCols = 0;
BufferedReader reader = new BufferedReader(new FileReader(wordSearchFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (this.numCols == 0) {
this.numCols = tokenizer.countTokens();
} else {
if (tokenizer.countTokens() != this.numCols) {
throw new WordSearchException("Invalid number of columns in word search");
}
}
line = reader.readLine();
this.numRows++;
}
reader.close();
this.wordSearch = new JLabel[numRows][numCols];
}
protected void loadGridFromFile(String wordSearchFilename) throws IOException {
int row = 0;
BufferedReader reader = new BufferedReader(new FileReader(wordSearchFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
int col = 0;
while (tokenizer.hasMoreTokens()) {
String tok = tokenizer.nextToken();
wordSearch[row][col] = new JLabel(tok);
wordSearch[row][col].setForeground(Color.BLACK);
wordSearch[row][col].setHorizontalAlignment(SwingConstants.CENTER);
wordsearchPanel.add(wordSearch[row][col]);
col++;
}
line = reader.readLine();
row++;
}
reader.close();
}
private void buildRightSidePanel() {
rightSidePanel = new JPanel();
rightSidePanel.setBorder(new TitledBorder(new EtchedBorder(), "Word List"));
rightSidePanel.setLayout(new BorderLayout());
wordListLabels = new JLabel[wordList.size()];
wordListPanel = new JPanel();
wordListPanel.setLayout(new GridLayout(wordList.size(), 1));
for (int i = 0; i < this.wordList.size(); i++) {
// If the line below won't compile in Java 1.4.2, make it
// String word = (String)this.wordList.get(i);
String word = this.wordList.get(i);
wordListLabels[i] = new JLabel(word);
wordListLabels[i].setForeground(Color.BLUE);
wordListLabels[i].setHorizontalAlignment(SwingConstants.CENTER);
wordListPanel.add(wordListLabels[i]);
}
rightSidePanel.add(wordListPanel, BorderLayout.CENTER);
searchButton = new JButton("Search");
searchButtonListener = new SearchListener();
searchButton.addActionListener(searchButtonListener);
searchButtonPanel = new JPanel();
searchButtonPanel.add(searchButton);
rightSidePanel.add(searchButtonPanel, BorderLayout.SOUTH);
this.getContentPane().add(rightSidePanel, BorderLayout.EAST);
}
private void loadWordList(String wordListFilename) throws WordSearchException, IOException {
int row = 0;
wordList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(wordListFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() != COLS_IN_WORDLIST) {
throw new WordSearchException("Error: only one word per line allowed in the word list");
}
String tok = tokenizer.nextToken();
wordList.add(tok);
line = reader.readLine();
row++;
}
reader.close();
}
public WordSearchFrame(String wordSearchFilename, String wordListFilename) throws IOException, WordSearchException {
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.getContentPane().setLayout(new BorderLayout());
this.initGridFromFile(wordSearchFilename);
buildLeftSidePanel();
this.loadGridFromFile(wordSearchFilename);
loadWordList(wordListFilename);
buildRightSidePanel();
}
public WordSearchFrame(String[][] wordSearch, String[] wordList) throws IOException, WordSearchException {
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.getContentPane().setLayout(new BorderLayout());
this.numRows = wordSearch.length;
this.numCols = wordSearch[0].length;
this.wordSearch = new JLabel[this.numRows][this.numCols];
buildLeftSidePanel();
for (int row = 0; row < this.numRows; row++) {
for (int col = 0; col < this.numCols; col++) {
this.wordSearch[row][col] = new JLabel(wordSearch[row][col]);
this.wordSearch[row][col].setForeground(Color.BLACK);
this.wordSearch[row][col].setHorizontalAlignment(SwingConstants.CENTER);
this.wordsearchPanel.add(this.wordSearch[row][col]);
}
}
this.wordList = new ArrayList<String>();
for (int i = 0; i < wordList.length; i++) {
this.wordList.add(wordList[i]);
}
buildRightSidePanel();
}
public static void main(String[] args) {
try {
if (args.length != 2) {
System.out.println("Command line arguments: <word search file> <word list>");
} else {
WordSearchFrame frame = new WordSearchFrame(args[0], args[1]);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I have all the next:
the panel on the left hand side, which consists of the word search
the contents of the word search into the JLabels of the word search grid in the GUI
Now I just need the jlabe[index].charAt(0). That does not work.
I tried jlabe[index].getText().charAt(0). That does not work.
What I tried above works fine, but not for what I want it.
Also the other class
public class WordSearchException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WordSearchException() {
}
public WordSearchException(String reason) {
super(reason);
}
}
The best way to do that is to gettext().charat(index)

how to access main class jtextfield in Extended class

I have a main class File
and another extend class File 2
how can i access a textfield declared in File with awt and Swing to the extended class File2 ?
main class:-
import java.util.*;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FileReceive extends FileReceiveUtil {
int msgIndex = 1;
Statement s;
public static File f;
public static String phoneNo, phoneNoLo, sk;
public static String str = "";
public static String path = "";
public String ran, ran11;
public String mes, sharedString;
FileReceive() throws Exception {
super("COM4");
}
#Override
public void processSMS(String str) throws Exception {
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("File Receive");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JLabel nameId = new JLabel("Enter Destination Path");
JButton browseb = new JButton("Browse");
JLabel bodyTempId = new JLabel("Path : ");
final JTextField jtf = new JTextField(" ");
JButton sendB = new JButton("Receive");
panel.add(nameId);
panel.add(browseb);
panel.add(bodyTempId);
panel.add(jtf);
panel.add(sendB);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
this()
browseb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jf = new JFileChooser();
String str1 = "";
int m = jf.showOpenDialog(null);
if (m == JFileChooser.APPROVE_OPTION) {
f = jf.getSelectedFile();
str = f.getPath();
path = f.getAbsolutePath();
jtf.setText(path);
}
}
});
sendB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FileReceiveUtil util = null;
try {
util = new FileReceive();
} catch (Exception ex) {
Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList al = new ArrayList();
try {
util.startReceive(al, 10);
} catch (Exception ex) {
Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
Extended class :-
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.JTextField;
public abstract class FileReceiveUtil implements Runnable {
private static int responseCode = -1;
private static String userCredentials = null;
private static String cookie = null;
private static String site = null;
private static String actionStr = null;
private Enumeration portList;
private CommPortIdentifier portId;
private SerialPort serialPort;
private OutputStream outputStream;
private String strPortName;
private InputStream inputStream;
private boolean boolKeepReceiving = true;
private Thread threadRX;
private ArrayList alSMSStore;
private int intDelay;
public FileReceiveUtil(String strPortName) throws Exception {
this.strPortName = strPortName;
initCommPort();
}
private void initCommPort() throws Exception {
boolean boolPortOK = false;
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equalsIgnoreCase(strPortName)) {
this.serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
serialPort.notifyOnDataAvailable(true);
serialPort.setSerialPortParams(230400,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
boolPortOK = true;
break;
}
}
}
if (!boolPortOK) {
throw new Exception("Port " + strPortName + " does not exist!");
}
}
private String readSMS() throws Exception {
StringBuffer sb = new StringBuffer();
sb.append(writeATCmd());
return sb.toString();
}
private String writeATCmd() throws Exception {
//Thread.sleep(2000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[1];
// Thread.sleep(10);
int ch = inputStream.read(data);
//System.out.println(x);
bos.write(data, 0, 1);
byte[] bytes = bos.toByteArray();
File someFile = new File("D:\\yadhu.txt");
FileOutputStream fos = new FileOutputStream(someFile,true);
fos.write(bytes);
fos.flush();
fos.close();
String str = bytes.toString();
System.out.println("Data : "+ str);
return str;
}
private void startReceivingSMS() throws Exception {
final String ERROR = "ERROR";
while (boolKeepReceiving) {
Thread.sleep(intDelay);
try {
System.out.println(" File recieved ");
String str = readSMS();
} catch (Throwable t) {
System.out.println("ERROR RECEIVING MSG");
t.printStackTrace();
}
}
}
final public void startReceive(ArrayList alSMSStore, int intDelay) throws Exception {
this.alSMSStore = alSMSStore;
this.intDelay = intDelay;
threadRX = new Thread(this);
threadRX.start();
}
final public void run() {
try {
startReceivingSMS();
} catch (Throwable t) {
t.printStackTrace();
}
}
final public void stopReceivingSMS() {
this.boolKeepReceiving = false;
}
public ArrayList getReceivedMessages() {
return this.alSMSStore;
}
private static void exit(String errorMsg) {
System.err.println(errorMsg);
System.exit(1);
}
public abstract void processSMS(String message) throws Exception;
}
i want " File someFile = new File("D:\yadhu.txt"); " to change this and add file name from the jtextfield on gui
please help
make the JTextField global in the class instead of a local function item.

threads and swing components in java

As you see, I've been researching and tried to set a thread in main.java class. This is the main method:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
check ch = new check();
ch.start();
}
});
}
Main method calls a thread called ch , from check.java class.
This is the thread class:
public class check extends Thread {
public JTextArea estado = new JTextArea();
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();
public String catchUpdatedVersion;
int UPDATENUMBER;
int CURRENTNUMBER;
public void run() {
String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
String name = "thread.inf";
File file = new File(name);
try {
URLConnection conn = new URL(infURL).openConnection();
conn.connect();
estado.append("Conectando al servidor...");
estado.append(System.getProperty("line.separator"));
estado.append(" -- Buscando actualizaciones... --");
estado.append(System.getProperty("line.separator"));
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(file);
int b = 0;
while (b != -1) {
b = in.read();
if (b != -1) {
out.write(b);
}
}
out.close();
in.close();
} catch (MalformedURLException ex) {
} catch (IOException ioe) { }
String fileToReadUpdatedVersion = "thread.inf";
try {
BufferedReader br = new BufferedReader(
new FileReader(fileToReadUpdatedVersion));
String brr = br.readLine();
catchUpdatedVersion = brr.substring(34,42);
String catchUpdatedShortVersion = brr.substring(15,16);
UPDATENUMBER = Integer.parseInt(catchUpdatedShortVersion);
String fileToReadCurrentVer = "thread.inf";
BufferedReader brrw = new BufferedReader(
new FileReader(fileToReadCurrentVer));
String brrwREAD = brrw.readLine();
String catchCurrentShortVersion = brrwREAD.substring(15,16);
CURRENTNUMBER = Integer.parseInt(catchCurrentShortVersion);
if (CURRENTNUMBER >= UPDATENUMBER) {
estado.setText("No se han encontrado actualizaciones.");
} else {
updatedVersion.setForeground(new Color(0,102,0));
updatedLabel.setForeground(new Color(0,153,51));
updatedVersion.setText(catchUpdatedVersion);
estado.append("-------------------" +
"NUEVA ACTUALIZACIÓN DISPONIBLE: " +
catchUpdatedVersion + " -------------------");;
estado.append(System.getProperty("line.separator"));
estado.append("Descargando actualizaciones... " +
"Espere por favor, no cierre este " +
"programa hasta que esté completado...");
try {
String updateURL = "https://thread.googlecode.com/" +
"svn/trunk/thread.inf";
String updatedname = (catchUpdatedVersion + ".zip");
File updatedfile = new File(updatedname);
URLConnection conn = new URL(updateURL).openConnection();
conn.connect();
estado.append(System.getProperty("line.separator"));
estado.append(" Archivo actual: " + updatedname);
estado.append(System.getProperty("line.separator"));
estado.append(" Tamaño: " +
conn.getContentLength() / 1000 / 1000 + " MB");
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(updatedfile);
int c = 0;
while (c != -1) {
c = in.read();
if (c != -1) {
out.write(c);
}
}
out.close();
in.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
} catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}
}
}
When I run the program, the thread does not work fine. It is supposed to download a file and then display its progress in a JTextArea in main.java class. It does download the file, but nothing appears in JTextArea.
Where is my mistake?
EDIT: Showing all the code.
Problem #1
The components you are trying to update are not, in any way, connected to the screen...
public JTextArea estado = new JTextArea();
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();
That means, anytime you interact with these components, it's doing nothing to what's on the screen...
Problem #2
You're trying to make modifications to the UI from outside the context of the Event Dispatching Thread. This is significant violation of the Swing threading rules.
public class Check extends SwingWorker<String, String> {
private JTextArea estado;
Private JTextField updatedVersion;
private JLabel updatedLabel;
private String catchUpdatedVersion;
int UPDATENUMBER;
int CURRENTNUMBER;
public Check(JTextArea estado, JTextField updatedVersion, JLabel updatedLabel) {
this.estado = estado;
this.updatedVersion = updatedVersion;
this.updatedLabel = updatedLabel;
}
protected void process(List<String> values) {
for (String value : values) {
estado.append(value);
}
}
protected String doInBackground() throws Exception {
String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
String name = "thread.inf";
File file = new File(name);
URLConnection conn = new URL(infURL).openConnection();
conn.connect();
publish("Conectando al servidor...");
publish(System.getProperty("line.separator"));
publish(" -- Buscando actualizaciones... --");
publish(System.getProperty("line.separator"));
/*...*/
}
}
IfYou need to do any post-processing, then you also override done which will be called after doInBackground has existed, but is called within the context of the EDT
For more details read through Concurrency in Swing

Unable to print console output in same format onto text document

I have my java file set up to calculate a phone bill and print out to the console in this format.
Invoice
--------------------------
Account Amount Due
10011 $12.25
10033 $11.70
--------------------------
Total $23.95
but when I run the program I only get this on the text file
Account Amount_Due
10011 $12.25
10033 $11.7
Can someone help me edit my filecreating code in correct format?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
public class PhoneBill {
Vector data;
Vector processed = new Vector();
Vector markProcessed = new Vector();
public void readFile(String inFileStr)
{
String str = "";
data = new Vector<LineItem>();
FileReader fReader;
InputStream inFileStream;
try{
fReader = new FileReader(inFileStr);
BufferedReader br=new BufferedReader(fReader);
String line;
while ((line=br.readLine())!= null){
if (line.indexOf("_") != -1)
continue;
else
if (!line.isEmpty()){
data.add(new LineItem(line.trim()));
}
}
br.close();
}
catch (Exception e){
}
}
public void processCharges()
{
String out = "Account Amount_Due\n";
System.out.println ("Invoice");
System.out.println ("--------------------------");
System.out.println ("Account " + "Amount Due ");
double total = 0.0;
double lCharges =0;
boolean done = false;
DecimalFormat numFormatter = new DecimalFormat("$##.##");
for (int j = 0; j < data.size(); j++ ){
LineItem li = (LineItem)data.get(j);
String accNum = li.getAccountNum();
if (j > 0){
done = checkProcessed(accNum);}
else
processed.add(accNum);
if (!done){
lCharges = 0;
for (int i = 0; i < data.size(); i++){
String acc = ((LineItem)data.get(i)).getAccountNum();
if (acc.equals(accNum) && !done)
lCharges += processItemCharges(accNum);
done = checkProcessed(accNum);
}
lCharges+=10.0;
System.out.format ("%s" + " $%.2f%n",accNum, lCharges);
out += accNum+" ";
out += numFormatter.format(lCharges)+"\n";
processed.add(accNum);
total += lCharges;
}
}
System.out.println ("--------------------------");
System.out.format ("%s" + " $%.2f%n","Total", total);
writeToFile("invoice.txt", out);
}
private void writeToFile(String filename,String outStr)
{
try{
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(outStr);
bw.close();
} catch (IOException ioe){
System.out.println(ioe.getMessage());
}
}
private boolean checkProcessed(String accNum){
if (processed.contains(accNum))
return true;
else
return false;
}
private double processItemCharges(String accNum)
{
double charges = 0.0;
for (int i = 0; i < data.size(); i++)
{
if(((LineItem)data.get(i)).getAccountNum().equals(accNum))
charges += ((LineItem)data.get(i)).getCharges();
}
return charges;
}
public static void main(String[] args)
{
PhoneBill pB = new PhoneBill();
pB.readFile("input_data.txt");
pB.processCharges();
}
class LineItem{
String accNum ;
String timeOfCall;
double mins;
double amountDue;
boolean counted = false;
public LineItem(String accStr)
{
processAccount(accStr);
}
private void processAccount(String accStr){
StringTokenizer st = new StringTokenizer(accStr);
accNum = (String)st.nextElement();
timeOfCall = (String) st.nextElement();
mins = Double.parseDouble((String) st.nextElement());
if (timeOfCall.compareTo("08:00")>0 && timeOfCall.compareTo("22:00")<0)
amountDue = mins*0.10;
else
amountDue = mins*0.05;
}
public String getAccountNum()
{
return accNum;
}
public double getCharges()
{
return amountDue;
}
}
}
Study this. It uses a bit more advanced Java but understanding it will be well worth your while.
package test;
import java.io.*;
import java.util.*;
public class PhoneBill {
private static String BILL_FORMAT = "%-10s $%,6.2f\n";
private static boolean DEBUG=true;
Map<String, List<LineItem>> accounts = new HashMap<String,List<LineItem>>();
public void readFile(String inFileStr) {
FileReader fReader=null;
try {
fReader = new FileReader(inFileStr);
BufferedReader br = new BufferedReader(fReader);
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("_") != -1)
continue;
else if (!line.isEmpty()) {
LineItem li = new LineItem(line.trim());
List<LineItem> list = accounts.get(li.accNum);
if(list==null){
list = new ArrayList<LineItem>();
accounts.put(li.accNum, list);
}
list.add(li);
}
}
br.close();
} catch (Exception e) {
/* Don't just swallow Exceptions. */
e.printStackTrace();
} finally {
if(fReader!=null){
try{
fReader.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
}
public void processCharges() {
StringBuffer out = new StringBuffer(100)
.append("Invoice\n")
.append("--------------------------\n")
.append("Account Amount Due \n");
double total = 0.0;
double lCharges = 0;
for (String accNum:accounts.keySet()) {
List<LineItem> account = accounts.get(accNum);
lCharges = 10;
for(LineItem li:account){
lCharges += li.getCharges();
}
total += lCharges;
out.append(String.format(BILL_FORMAT, accNum, lCharges));
}
out.append("--------------------------\n");
out.append(String.format(BILL_FORMAT, "Total", total));
writeToFile("invoice.txt", out.toString());
}
private void writeToFile(String filename, String outStr) {
if(DEBUG){
System.out.printf("========%swriteToFile:%s=========\n", '=', filename);
System.out.println(outStr);
System.out.printf("========%swriteToFile:%s=========\n", '/', filename);
}
try {
File file = new File(filename);
// If file doesn't exist, then create it.
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(outStr);
bw.close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
public static void main(String[] args) {
PhoneBill pB = new PhoneBill();
pB.readFile("input_data.txt");
pB.processCharges();
}
static class LineItem {
String accNum;
double timeOfCall;
double mins;
double amountDue;
boolean counted = false;
private static final double EIGHT_AM = convertTime("08:00");
private static final double TEN_PM = convertTime("22:00");
public LineItem(String accStr) {
processAccount(accStr);
}
private void processAccount(String accStr) {
StringTokenizer st = new StringTokenizer(accStr);
accNum = st.nextToken();
timeOfCall = convertTime(st.nextToken());
mins = Double.parseDouble(st.nextToken());
if (timeOfCall > EIGHT_AM && timeOfCall < TEN_PM)
amountDue = mins * 0.10;
else
amountDue = mins * 0.05;
}
public String getAccountNum() {
return accNum;
}
public double getCharges() {
return amountDue;
}
private static double convertTime(String in){
/* Will blow up if `in` isn't given in h:m. */
String[] h_m = in.split(":");
return Double.parseDouble(h_m[0])*60+Double.parseDouble(h_m[1]);
}
}
}
Printing to the console (i.e. System.out.println) is not the same as concatenating to your out variable (i.e. out+=).
So when you call
writeToFile("invoice.txt", out);
You are only writing what is in the string 'out' to the file. If you look back at your code, you'll see that all of your missing lines are only ever printed to the console, but not concatenated to the 'out' variable. Correct that and you shouldn't have a problem.

Categories