JFrame FileChooser get file directory - java

I was doing an assignment. Basically the assignment is done but I was trying to make it better by adding a GUI to it.
But I was encountering some issue on FileChooser because I don't quite understand how it works.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CaesarCipherGui extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private static JButton Encrypt = new JButton("Encrypttion");
private static JButton Decrypt = new JButton("Decrypttion");
private static JPanel panel = new JPanel();
public static void main(String[] args) {
new CaesarCipherGui();
}
private void addComponent(JPanel p, JComponent c, int x, int y, int width, int height, int align) {
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = width;
gc.gridheight = height;
gc.weightx = 100.0;
gc.weighty = 100.0;
gc.insets = new Insets(5, 5, 5, 5);
gc.anchor = align;
gc.fill = GridBagConstraints.NONE;
p.add(c, gc);
}
public CaesarCipherGui() {
this.setSize(310, 192);
this.setTitle("Caesar Cipher");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(false);
panel.setLayout(new GridBagLayout());
addComponent(panel, Encrypt, 1, 4, 1, 1, GridBagConstraints.WEST);
Encrypt.addActionListener(this);
addComponent(panel, Decrypt, 1, 4, 1, 1, GridBagConstraints.EAST);
Decrypt.addActionListener(this);
this.add(panel);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Encrypt){
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
try{
FileReader reader = new FileReader("C:/"+inputFileName+".txt");
Scanner in = new Scanner(reader);
PrintWriter out = new PrintWriter("C:/"+outputFileName+".txt");
while (in.hasNextLine()){
String line = in.nextLine();
String outPutText = "";
int key = 3;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c >= 'a' && c <= 'z') {
c += key % 26;
if (c < 'a')
c += 26;
if (c > 'z')
c -= 26;
}
if (c >= 'A' && c <= 'Z') {
c += key % 26;
if (c < 'A')
c += 26;
if (c > 'Z')
c -= 26;
}
if (c == ' '){
c = '#';
}
outPutText += c;
}
out.println(outPutText);
}
out.close();
}
catch (IOException exception){
System.out.println("Error processing file:" + exception);
}
}
if (e.getSource() == Decrypt){
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
try{
FileReader reader = new FileReader("C:/"+inputFileName+".txt");
Scanner in = new Scanner(reader);
PrintWriter out = new PrintWriter("C:/"+outputFileName+".txt");
while (in.hasNextLine()){
String line = in.nextLine();
String outPutText = "";
int key = -3;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c >= 'a' && c <= 'z') {
c += key % 26;
if (c < 'a')
c += 26;
if (c > 'z')
c -= 26;
}
if (c >= 'A' && c <= 'Z') {
c += key % 26;
if (c < 'A')
c += 26;
if (c > 'Z')
c -= 26;
}
if (c == '#'){
c = ' ';
}
outPutText += c;
}
out.println(outPutText);
}
out.close();
}
catch (IOException exception){
System.out.println("Error processing file:" + exception);
}
}
}
}
As the code above is my assignment, but I wish to add the file chooser for the input filename and save file for the output filename, how am I gonna do it? Or you can just modify the part that needs to change and show me.

no, you add an actionlistener to a button and define the filechooser:
cmdSearch = new AbstractAction("Search", null) {
public void actionPerformed(ActionEvent evt) {
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
txtSearch.setText( (fc.showOpenDialog(YOURCLASSNAME.this) == JFileChooser.APPROVE_OPTION) ? fc.getSelectedFile().toString() : txtSearch.getText() );
}
};

I guess you should start from the official documentation. Using a JFileChooser is quite easy, you just need to:
show an open or save dialog according to what you are doing
check the return value of the show function to see that the user effectively chose a file
retrieve the File through getSelectedFile() method
optionally use a custom FileFilter to let the user see just the file types you want

Related

repaint() method not calling paintCompnent

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).

JScrollPane array in JOptionPane.showMessageDialog

In my code, I'm trying to use a JScrollPane and add it into a JOptionPane.showMessageDialog. I don't know if this is possible to start with but I don't know how to do it if it is, and how to add the whole array into the one message and not multiple. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Iterator;
public class CulminatingPro implements ActionListener
{
//Create an array of buttons
static JButton[][] buttons = new JButton[10][4];
static JButton jbtList = new JButton("List");
ArrayList<Culminating> flyers = new ArrayList<Culminating>();
String fn;
String ln;
String pn;
String adress;
int column;
int row;
int reply;
int v;
Object[] options = {"First Name",
"Last Name",
"Phone Number",
"Adress"};
public static void main(String[] args)
{
JFrame frame = new JFrame("Fly By Buddies");
frame.setSize(900, 900);
JPanel mainPanel = new JPanel();
mainPanel.setLayout( new GridLayout(1,2));
JPanel paneSeats = new JPanel();
JPanel paneInfo = new JPanel();
paneSeats.setLayout( new GridLayout(11, 4, 5,5));
mainPanel.add(paneSeats);
mainPanel.add(paneInfo);
frame.setContentPane(mainPanel);
for (int i = 0; i < buttons.length; i++)
{
for(int j = 0; j < buttons[0].length; j++)
{
if (j + 1 == 1)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "A");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1 == 2)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "B");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1== 3)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "C");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1== 4)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "D");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
}
}
jbtList.setPreferredSize(new Dimension(400, 40));
jbtList.addActionListener(new CulminatingPro());
paneInfo.add(jbtList, BorderLayout.SOUTH);
frame.setVisible(true);
frame.toFront();
}
public void actionPerformed(ActionEvent event)
{
for (int i = 0; i < buttons.length; i++)
{
for(int j = 0; j < buttons[0].length; j++)
{
if (event.getSource() == buttons[i][j])
{
v = 0;
for (int k = 0; k < flyers.size();k++)
{
if((flyers.get(k).getColumn() == (j) && (flyers.get(k).getColumn() == (j))))
{
if (!flyers.get(k).getFirstName().equals(""))
{
reply = JOptionPane.showConfirmDialog(null,
"Would you like to delete the info on the passenger?", "Deletion", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
flyers.remove(k);
buttons[i][j].setBackground(Color.GREEN);
}
else if (reply == JOptionPane.NO_OPTION)
{
reply = JOptionPane.showConfirmDialog(null,
"Would you like to modify the info on the passenger?", "Modification", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
int n = JOptionPane.showOptionDialog(null, "Message", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
n = n + 1;
if(n == 0)
{
fn = JOptionPane.showInputDialog(null,"Re-enter passenger's first name: ");
flyers.get(k).setFirstName(fn);
}
if(n == 2)
{
ln = JOptionPane.showInputDialog(null,"Re-enter passenger's last name: ");
flyers.get(k).setLastName(ln);
}
if(n == 3)
{
pn = JOptionPane.showInputDialog(null,"Re-enter passenger's phone number: ");
flyers.get(k).setPhoneNumber(pn);
}
if(n == 4)
{
adress = JOptionPane.showInputDialog(null,"Re-enter passenger's adress: ");
flyers.get(k).setAdress(adress);
}
}
}
v = 1;
}
}
}
if(v == 0)
{
fn = JOptionPane.showInputDialog(null,"Passenger's first name (Necessary): ");
ln = JOptionPane.showInputDialog(null,"Passenger's last name (Necessary): ");
pn = JOptionPane.showInputDialog(null,"Passenger's phone number: ");
adress = JOptionPane.showInputDialog(null,"Passenger's adress: ");
column = j;
row = i;
flyers.add(new Culminating(fn,ln,pn,adress,column,row));
buttons[i][j].setBackground(Color.RED);
}
}
}
}
if (event.getSource().equals("List"))
{
JScrollPane[] scroll = new JScrollPane[flyers.size()];
for(int p = 0; p < flyers.size(); p++)
{
JTextArea text = new JTextArea(flyers.get(p).toString(), 10, 40);
scroll[p] = new JScrollPane(text);
}
for(int p = 0; p < flyers.size(); p++)
{
JOptionPane.showMessageDialog(null,scroll[p]);
}
}
}
}

Count occurrences of all 256 characters (GUI/Arrays)

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.

Wordsearch puzzle nullpointerexception on array

Am getting a java.lang.NullPointerException on an array I have initialized and I can't quite figure it out what am doing wrong. The error is occuring at line 371.
Below is the code of the parent class followed by the class initializng the letterArray ArrayList:
package wordsearch;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
/**
* Main class of Puzzle Program
* #author mungaialex
*
*/
public class WordSearchPuzzle extends JFrame {
private static final long serialVersionUID = 1L;
/** No. Of Columns in Wordlist*/
private static final int WORDLISTCOLS = 1;
static JButton[][] grid; //names the grid of buttons
GridLayout myGridLayout = new GridLayout(1,2,3,3);
/**Array to hold wordList*/
ArrayList<String> wordList;
JButton btnCheck, btnClear;
/** Panel to hold Components to the left*/
JPanel leftSidePanel;
/** Panel to hold components to the right*/
JPanel rightSidePanel;
/**Panel to hold word List*/
JPanel wordListPanel;
/**Panel to hold grid buttons*/
JPanel gridPanel;
/**Panel to hold clear button and check button*/
JPanel buttonsPanel;
/**Panel to hold output textarea*/
JPanel bottomPanel;
private JLabel[] wordListComponents;
#SuppressWarnings("rawtypes")
List puzzleLines;
//Grid Size
private final int ROWS = 20;
private final int COLS = 20;
/** Output Area of system*/
private JTextArea txtOutput;
/**Scrollpane for Output area*/
private JScrollPane scptxtOutput;
private Object[] theWords;
public String wordFromChars = new String();
/** the matrix of the letters */
private char[][] letterArray = null;
/**
* Constructor for WordSearchPuzzle
* #param wordListFile File Containing words to Search for
* #param wordSearhPuzzleFile File Containing the puzzle
*/
public WordSearchPuzzle(String wordSearchFile,String wordsListFile) throws IOException {
FileIO io = new FileIO(wordSearchFile,wordsListFile,grid);
wordList = io.loadWordList();
theWords = wordList.toArray();
addComponentsToPane();
buildWordListPanel();
buildBottomPanel();
io.loadPuzleFromFile();
//Override System.out
PrintStream stream = new PrintStream(System.out) {
#Override
public void print(String s) {
txtOutput.append(s + "\n");
txtOutput.setCaretPosition(txtOutput.getText().length());
}
};
System.setOut(stream);
System.out.print("MESSAGES");
}
/**
* Constructor two
*/
public WordSearchPuzzle() {
}
/**
* Gets the whole word of buttons clicked
* #return
* Returns whole Word
*/
public String getSelectedWord() {
return wordFromChars;
}
/**
* Adds word lists to Panel on the left
*/
private void buildWordListPanel() {
leftSidePanel.setBackground(Color.WHITE);
// Build the word list
wordListComponents = new JLabel[wordList.size()];
wordListPanel = new JPanel(new GridLayout(25, 1));
wordListPanel.setBackground(Color.white);
//Loop through list of words
for (int i = 0; i < this.wordList.size(); i++) {
String word = this.wordList.get(i).toUpperCase();
wordListComponents[i] = new JLabel(word);
wordListComponents[i].setForeground(Color.BLUE);
wordListComponents[i].setHorizontalAlignment(SwingConstants.LEFT);
wordListPanel.add(wordListComponents[i]);
}
leftSidePanel.add(wordListPanel,BorderLayout.WEST);
}
/**
* Adds an output area to the bottom of
*/
private void buildBottomPanel() {
bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
txtOutput = new JTextArea();
txtOutput.setEditable(false);
txtOutput.setRows(5);
scptxtOutput = new JScrollPane(txtOutput);
bottomPanel.add(txtOutput,BorderLayout.CENTER);
bottomPanel.add(scptxtOutput,BorderLayout.SOUTH);
rightSidePanel.add(bottomPanel,BorderLayout.CENTER);
}
/**
* Initialize Components
*/
public void addComponentsToPane() {
// buttonsPanel = new JPanel(new BorderLayout(3,5)); //Panel to hold Buttons
buttonsPanel = new JPanel(new GridLayout(3,1));
leftSidePanel = new JPanel(new BorderLayout());
rightSidePanel = new JPanel(new BorderLayout());
btnCheck = new JButton("Check Word");
btnCheck.setActionCommand("Check");
btnCheck.addActionListener(new ButtonClickListener());
btnClear = new JButton("Clear Selection");
btnClear.setActionCommand("Clear");
btnClear.addActionListener(new ButtonClickListener());
buttonsPanel.add(btnClear);//,BorderLayout.PAGE_START);
buttonsPanel.add(btnCheck);//,BorderLayout.PAGE_END);
leftSidePanel.add(buttonsPanel,BorderLayout.SOUTH);
this.getContentPane().add(leftSidePanel,BorderLayout.LINE_START);
gridPanel = new JPanel();
gridPanel.setLayout(myGridLayout);
myGridLayout.setRows(20);
myGridLayout.setColumns(20);
grid = new JButton[ROWS][COLS]; //allocate the size of grid
//theBoard = new char[ROWS][COLS];
for(int Row = 0; Row < grid.length; Row++){
for(int Column = 0; Column < grid[Row].length; Column++){
grid[Row][Column] = new JButton();//Row + 1 +", " + (Column + 1));
grid[Row][Column].setActionCommand(Row + "," + Column);
grid[Row][Column].setActionCommand("gridButton");
grid[Row][Column].addActionListener(new ButtonClickListener());
gridPanel.add(grid[Row][Column]);
}
}
rightSidePanel.add(gridPanel,BorderLayout.NORTH);
this.getContentPane().add(rightSidePanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
try {
if (args.length !=2) { //Make sure we have both the puzzle file and word list file
JOptionPane.showMessageDialog(null, "One or All Files are Missing");
} else { //Files Found
WordSearchPuzzle puzzle = new WordSearchPuzzle(args[0],args[1]);
puzzle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
puzzle.setSize(new Dimension(1215,740));
//Display the window.
puzzle.setLocationRelativeTo(null); // Center frame on screen
puzzle.setResizable(false); //Set the form as not resizable
puzzle.setVisible(true);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public int solvePuzzle( ){
int matches = 0;
for( int r = 0; r < ROWS; r++ )
for( int c = 0; c < COLS; c++ )
for( int rd = -1; rd <= 1; rd++ )
for( int cd = -1; cd <= 1; cd++ )
if( rd != 0 || cd != 0 )
matches += solveDirection( r, c, rd, cd );
return matches;
}
private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta ){
String charSequence = "";
int numMatches = 0;
int searchResult;
FileIO io = new FileIO();
charSequence += io.theBoard[ baseRow ][ baseCol ];
for( int i = baseRow + rowDelta, j = baseCol + colDelta;
i >= 0 && j >= 0 && i < ROWS && j < COLS;
i += rowDelta, j += colDelta )
{
charSequence += io.theBoard[ i ][ j ];
searchResult = prefixSearch( theWords, charSequence );
if( searchResult == theWords.length )
break;
if( !((String)theWords[ searchResult ]).startsWith( charSequence ) )
break;
if( theWords[ searchResult ].equals( charSequence ) )
{
numMatches++;
System.out.println( "Found " + charSequence + " at " +
baseRow + " " + baseCol + " to " +
i + " " + j );
}
}
return numMatches;
}
private static int prefixSearch( Object [ ] a, String x ) {
int idx = Arrays.binarySearch( a, x );
if( idx < 0 )
return -idx - 1;
else
return idx;
}
class ButtonClickListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String command = ((JButton)e.getSource()).getActionCommand();
if (command == "Clear") {
//Enable the buttons that have been disabled and not form a whole word
//JOptionPane.showMessageDialog(null, "Cooming Soon");
for (String word : wordList) {
System.out.print(word);
}
} else if (command == "Check") {
String selectedWord = getSelectedWord();
if (!selectedWord.equals("")){
System.out.print("Selected word is " + getSelectedWord());
//First check if selected word exits in wordList
if (ifExists(selectedWord)) {
if(searchWord(selectedWord)){
JOptionPane.showMessageDialog(null, "Success");
wordFromChars = ""; //Reset the selected Word
}
} else {
JOptionPane.showMessageDialog(null, "[" + selectedWord + "] " +
"Does Not Belong to Word list");
wordFromChars = ""; //Reset the selected Word
}
} else {
JOptionPane.showMessageDialog(null, "No Buttons on Grid have been clicked");
}
} else if (command == "gridButton") {
getSelectedCharacter(e);
((JButton)e.getSource()).setEnabled(false);
}
}
/**
* Gets the character of each button and concatenates each character to form a whole word
* #param e The button that received the Click Event
* #return Whole word
*/
private String getSelectedCharacter (ActionEvent e) {
String character;
character = ((JButton) e.getSource()).getText();
wordFromChars = wordFromChars + character;
return wordFromChars;
}
}
/**
* Checks if selected word is among in wordlist
* #param selectedWord
* #return The word to search for
*/
private boolean ifExists(String selectedWord) {
if (wordList.contains(selectedWord)) {
return true;
}
return false;
}
public boolean searchWord(String word) {
if (!wordList.contains(word)) {
return false;
}
//int index = wordList.indexOf(word);
Line2D.Double line = new Line2D.Double();
//System.out.print("LetterArray is " + letterArray.length);
for (int x = 0; x < letterArray.length; x++) {
for (int y = 0; y < letterArray[x].length; y++) {
// save start point
line.x1 = y; // (y + 1) * SCALE_INDEX_TO_XY;
line.y1 = x; // (x + 1) * SCALE_INDEX_TO_XY;
int pos = 0; // current letter position
if (letterArray[x][y] == word.charAt(pos)) {
// first letter correct -> check next
pos++;
if (pos >= word.length()) {
// word is only one letter long
// double abit = SCALE_INDEX_TO_XY / 3;
line.x2 = y; // (y + 1) * SCALE_INDEX_TO_XY + abit;
line.y2 = x; // (x + 1) * SCALE_INDEX_TO_XY + abit;
return true;
}
// prove surrounding letters:
int[] dirX = { 1, 1, 0, -1, -1, -1, 0, 1 };
int[] dirY = { 0, -1, -1, -1, 0, 1, 1, 1 };
for (int d = 0; d < dirX.length; d++) {
int dx = dirX[d];
int dy = dirY[d];
int cx = x + dx;
int cy = y + dy;
pos = 1; // may be greater if already search in another
// direction from this point
if (insideArray(cx, cy)) {
if (letterArray[cx][cy] == word.charAt(pos)) {
// 2 letters correct
// -> we've got the direction
pos++;
cx += dx;
cy += dy;
while (pos < word.length() && insideArray(cx, cy)
&& letterArray[cx][cy] == word.charAt(pos)) {
pos++;
cx += dx;
cy += dy;
}
if (pos == word.length()) {
// correct end if found
cx -= dx;
cy -= dy;
pos--;
}
if (insideArray(cx, cy) && letterArray[cx][cy] == word.charAt(pos)) {
// we've got the end point
line.x2 = cy; // (cy + 1) *
// SCALE_INDEX_TO_XY;
line.y2 = cx; // (cx + 1) *
// SCALE_INDEX_TO_XY;
/*
* System.out.println(letterArray[x][y] +
* " == " + word.charAt(0) + " (" + line.x1
* + "," + line.y1 + ") ->" + " (" + line.x2
* + "," + line.y2 + "); " + " [" + (line.x1
* / SCALE_INDEX_TO_XY) + "," + (line.y1 /
* SCALE_INDEX_TO_XY) + "] ->" + " [" +
* (line.x2 / SCALE_INDEX_TO_XY) + "." +
* (line.y2 / SCALE_INDEX_TO_XY) + "]; ");
*/
//result[index] = line;
// found
return true;
}
// else: try next occurence
}
}
}
}
}
}
return false;
}
private boolean insideArray(int x, int y) {
boolean insideX = (x >= 0 && x < letterArray.length);
boolean insideY = (y >= 0 && y < letterArray[0].length);
return (insideX && insideY);
}
public void init(char[][] letterArray) {
try {
for (int i = 0; i < letterArray.length; i++) {
for (int j = 0; j < letterArray[i].length; j++) {
char ch = letterArray[i][j];
if (ch >= 'a' && ch <= 'z') {
letterArray[i][j] = Character.toUpperCase(ch);
}
}
}
} catch (Exception e){
System.out.println(e.toString());
}
//System.out.println("It is " + letterArray.length);
this.letterArray = letterArray;
}
}
Here is class initializing the letterArray array:
package wordsearch;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
/**
* Reads wordlist file and puzzle file
* #author mungaialex
*
*/
public class FileIO {
String _puzzleFile, _wordListFile;
/**ArrayList to hold words*/
ArrayList<String> wordList;
/** No. Of Columns in Wordlist*/
private static final int WORDLISTCOLS = 1;
List puzzleLines;
JButton[][] _grid;
char theBoard[][];
private final int _rows = 20;
private final int _columns = 20;
WordSearchPuzzle pz = new WordSearchPuzzle();
/**
* Default Constructor
* #param puzzleFile
* #param wordListFile
*/
public FileIO(String puzzleFile, String wordListFile,JButton grid[][]){
_puzzleFile = new String(puzzleFile);
_wordListFile = new String(wordListFile);
_grid = pz.grid;
}
public FileIO() {
}
/**
* Reads word in the wordlist file and adds them to an array
* #param wordListFilename
* File Containing Words to Search For
* #throws IOException
*/
protected ArrayList<String> loadWordList()throws IOException {
int row = 0;
wordList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(_wordListFile));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() != WORDLISTCOLS) {
JOptionPane.showMessageDialog(null, "Error: only one word per line allowed in the word list",
"WordSearch Puzzle: Invalid Format", row);//, JOptionPane.OK_CANCEL_OPTION);
//"Error: only one word per line allowed in the word list");
}
String tok = tokenizer.nextToken();
wordList.add(tok.toUpperCase());
line = reader.readLine();
row++;
}
reader.close();
return wordList;
}
/**
* Reads the puzzle file line by by line
* #param wordSearchFilename
* The file containing the puzzle
* #throws IOException
*/
protected void loadPuzleFromFile() throws IOException {
int row = 0;
BufferedReader reader = new BufferedReader(new FileReader(_puzzleFile));
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
puzzleLines = new ArrayList<String>();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
int col = 0;
sb.append(line);
sb.append('\n');
while (tokenizer.hasMoreTokens()) {
String tok = tokenizer.nextToken();
WordSearchPuzzle.grid[row][col].setText(tok);
pz.grid[row][col].setForeground(Color.BLACK);
pz.grid[row][col].setHorizontalAlignment(SwingConstants.CENTER);
puzzleLines.add(tok);
col++;
}
line = reader.readLine();
row++;
theBoard = new char[_rows][_columns];
Iterator itr = puzzleLines.iterator();
for( int r = 0; r < _rows; r++ )
{
String theLine = (String) itr.next( );
theBoard[ r ] = theLine.toUpperCase().toCharArray( );
}
}
String[] search = sb.toString().split("\n");
initLetterArray(search);
reader.close();
}
protected void initLetterArray(String[] letterLines) {
char[][] array = new char[letterLines.length][];
System.out.print("Letter Lines are " +letterLines.length );
for (int i = 0; i < letterLines.length; i++) {
letterLines[i] = letterLines[i].replace(" ", "").toUpperCase();
array[i] = letterLines[i].toCharArray();
}
System.out.print("Array inatoshana ivi " + array.length);
pz.init(array);
}
}
Thanks in advance.
Here it is!
char[][] array = new char[letterLines.length][];
You are only initializing one axis.
When you pass this array to init() and set this.letterArray = letterArray;, the letterArray is also not fully initialized.
Try adding a length to both axes:
char[][] array = new char[letterLines.length][LENGTH];
first you will handle the NullPoinetrException , the code is
if( letterArray != null){
for (int x = 0; x < letterArray.length; x++)
{
..........
............
}
}

Null Pointer Exception in Array of String

I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception.
I am trying to create TextReport on JTextArea using array of String input.even i am working on Text spillover to get extra text on next line and it should be display as in table format on JTextArea. my boss told me to make simple report for bank project. For more simplicity. Thanks in advance.
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.Border;
public class testit extends JApplet implements ActionListener {
String[] colName = new String[]{"Date", "Account.No", "Description", "Deposit", "Withdraw"};
String A[][] = {{"13/12/2013", "101", "AlphaSoft Infotek Ltd. Nashik", "3000", "0"},
{"15/12/2013", "103", "Bank Ladger ", "5000", "0"}};
String[][] B = new String[3][5];
String[] K = new String[5];
Container c;
JTextArea outputArea;
//JScrollPane js1;
JButton b;
public void init() {
c = getContentPane();
c.setLayout(new FlowLayout());
outputArea = new JTextArea(20, 80);
Border border = BorderFactory.createLineBorder(Color.RED);
outputArea.setBorder(BorderFactory.createCompoundBorder(border,
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
c.add(outputArea);
//js1=new JScrollPane(outputArea);
// add(js1);
b = new JButton("Show Report");
b.addActionListener(this);
c.add(b);
}
public void actionPerformed(ActionEvent e) {
outputArea.setEditable(false);
outputArea.setFont(new Font("Times New Roman", Font.PLAIN, 14));
outputArea.setText(" ");
outputArea.append("ALPHASOFT -- BANK LADGER , REPORTS.\n\n");
//outputArea.append("Sr.No");
for (int j = 0; j < colName.length; j++) {
outputArea.append("\t" + colName[j]);
}
outputArea.append("\n");
for (int i = 0; i < A.length; i++) {
int colv = A[i].length;
String D = null;
String Z[][] = A;
//String Y[]=new String[];
String Y[] = new String[colv];
//Y=A;
for (int ZX = 0; ZX < A[i].length; ZX++) {
Y[ZX] = A[i][ZX];
}
while (Y != null) {
Z[i] = Y;
Y = null;
D = null;
String bb[] = new String[colv];
for (int nx = 0; nx < A[i].length; nx++) {
Y[nx] = null;
//if(Z[i][nx].length()>0){
if (Z[i][nx].length() > 20) {
D += Z[i][nx].substring(0, 20);
Y[nx] = Z[i][nx].substring(20);
} else {
D += rightpad(Z[i][nx], 20, "R");
}
}
outputArea.append(D + "\n");
}
}
}
public static String rightpad(String inp, int ln, String rl) {
String pd = "";
for (int nx = 0; nx < ln - inp.length(); nx++) {
pd += " ";
}
if (rl == "R") {
pd = inp + pd;
} else {
pd = pd + inp;
}
return pd;
}
}
following errors are on console:
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at reportlast.testit.actionPerformed(testit.java:93)
BUILD SUCCESSFUL (total time: 9 seconds)
You have assigned D and Y as null
Y = new String[array_length]; // this was null earlier
D = ""; // this was null earlier
String bb[] = new String[colv];
for (int nx = 0; nx < A[i].length; nx++) {
Y[nx] = null;
//if(Z[i][nx].length()>0){
if (Z[i][nx].length() > 20) {
D += Z[i][nx].substring(0, 20); // 1
Y[nx] = Z[i][nx].substring(20); // 2
} else {
D += rightpad(Z[i][nx], 20, "R"); // 3
}
This was the reason why you would have got a null pointer exception at 1, 2 or/and 3

Categories