Null Pointer Exception in Array of String - java

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

Related

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:Index 12 out of bounds for length 12

I'm currently trying to make a 2D game using VSCode, I am on a MacBook, and keep getting this error whenever trying to load the map. My map for some reason will only appear as all white, without the character, and I get this error in the terminal:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 12
at tile.TileManager.draw(TileManager.java:102)
at main.GamePanel.paintComponent(GamePanel.java:94)
Here is my TileManager class
package tile;
import main.GamePanel;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.io.InputStream;
import java.io.*;
public class TileManager {
GamePanel gp;
Tile[] tile;
int mapTileNum[][];
public TileManager(GamePanel gp) {
this.gp = gp;
tile = new Tile[10];
mapTileNum = new int[gp.maxWorldCol][gp.maxScreenRow];
getTileImage();
loadMap("res/maps/world01.txt");
}
public void getTileImage() {
System.out.println("image loading started");
try {
this.tile[0] = new Tile();
this.tile[0].image = ImageIO.read(new FileInputStream("res/tiles/grass01.png"));
this.tile[1] = new Tile();
this.tile[1].image = ImageIO.read(new FileInputStream("res/tiles/wall.png"));
this.tile[2] = new Tile();
this.tile[2].image = ImageIO.read(new FileInputStream("res/tiles/water01.png"));
this.tile[3] = new Tile();
this.tile[3].image = ImageIO.read(new FileInputStream("res/tiles/earth.png"));
this.tile[4] = new Tile();
this.tile[4].image = ImageIO.read(new FileInputStream("res/tiles/tree.png"));
this.tile[5] = new Tile();
this.tile[5].image = ImageIO.read(new FileInputStream("res/tiles/sand.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Image loading finished");
}
public void loadMap(String filePath) {
try {
InputStream is = getClass().getResourceAsStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
int col = 0;
int row = 0;
while (col < gp.maxWorldCol && row < gp.maxWorldRow) {
String line = br.readLine();
while (col < gp.maxWorldCol) {
String numbers[] = line.split(" "); // splits up strings at space
int num = Integer.parseInt(numbers[col]);
mapTileNum[col][row] = num;
col++;
}
if (col == gp.maxWorldCol) {
col = 0;
row++;
}
}
br.close();
} catch (Exception e) {
}
}
public void draw(Graphics2D g2) {
int worldCol = 0;
int worldRow = 0;
while (worldCol < gp.maxWorldCol && worldRow < gp.maxWorldRow) {
int tileNum = mapTileNum[worldCol][worldRow];
int worldX = worldCol * gp.tileSize;
int worldY = worldRow * gp.tileSize;
int screenX = worldX - gp.player.worldX + gp.player.screenX;
int screenY = worldY - gp.player.worldY + gp.player.screenY;
if (worldX + gp.tileSize > gp.player.worldX - gp.player.screenX &&
worldX - gp.tileSize < gp.player.worldX + gp.player.screenX &&
worldY + gp.tileSize > gp.player.worldY - gp.player.screenY &&
worldY - gp.tileSize < gp.player.worldY + gp.player.screenY) {
g2.drawImage(tile[tileNum].image, screenX, screenY, gp.tileSize, gp.tileSize, null);
}
g2.drawImage(tile[tileNum].image, screenX, screenY, gp.tileSize, gp.tileSize, null);
worldCol++;
if (worldCol == gp.maxWorldCol) {
worldCol = 0;
worldRow++;
}
}
}
}
In the public tile manager call the getTileImage method to initialize the tiles
public TileManager(GamePanel gp) {
this.gp = gp;
tile = new Tile[10];
getTileImage(); // Call the getTileImage method to initialize the tiles
}

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

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++)
{
..........
............
}
}

Can't see contents of JFrame until I drag open window

this is actually my first complete program which will eventually be used to write code for a robot I am making. Everything is working okay, except that when I run it, I have to drag open the window in order to see the content inside it.
Any suggestions on how to fix it.
frame2 - "click to build file" works.
frame - the one with the button grid, is the one I have to drag open to see.
Here is the setup file for frame (the one that doesn't work)
package Grid;
//march 13 to April 11
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class ButtonGrid extends JFrame {
public static int clicked[][] = new int[20][40];
static JButton button[] = new JButton[800];
static int x;
static int count = 1;
public static int clickedfinal[][];
int value;
public ButtonGrid() {
JFrame frame = new JFrame();
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
GridLayout grid = new GridLayout(20, 40, 10, 8);
frame.setLayout(grid);
for (int c = 0; c < 20; c++) {
for (int d = 0; d < 40; d++) {
clicked[c][d] = 0;
}
}
for (x = 0; x < 800; x++) {
button[x] = new JButton();
button[x].setActionCommand(Integer.toString(x));
frame.add(button[x]);
button[x].setBackground(Color.LIGHT_GRAY);
button[x].setOpaque(true);
thehandler handler = new thehandler();
button[x].addActionListener(handler);
}
}
public class thehandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
for (;;) {
value = Integer.parseInt(e.getActionCommand());
button[value].setBackground(Color.BLACK);
int r = value % 40;
int m = ((value - (value % 40)) / 40);
// learn how to round up
clicked[m][r] = 1;
break;
}
}
}
public static void main(String[] args) {
new ButtonGrid();
}
}
Here is the file for frame2, the one that does work; To test just run this one.
package Grid;
import javax.swing.JButton;
import javax.swing.JFrame;
import Grid.ButtonGrid;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
#SuppressWarnings("serial")
public class Arduinowriter extends JFrame {
static int t = 1;
static int buttonpressed;
static int total;
static String Code;
static String oldcode;
public Arduinowriter() {
JFrame frame2 = new JFrame("Build File");
JButton button = new JButton("Click to Build File");
frame2.setSize(400, 400);
frame2.add(button);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setVisible(true);
button.setActionCommand(Integer.toString(1));
thehandler handler = new thehandler();
button.addActionListener(handler);
}
public class thehandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
buttonpressed = Integer.parseInt(e.getActionCommand());
String newLine = System.getProperty("line.separator");
String Motor2_half = "digitalWrite(Motor2, HIGH);" + newLine
+ "delay(500)" + newLine + "digitalWrite(Motor2, LOW)";
String Motor2_one = "digitalWrite(Motor2, HIGH);" + newLine
+ "delay(1000);" + newLine + "digitalWrite(Motor2, LOW);";
String Servo1_dispense = "digitalWrite(Servo1, HIGH);" + newLine
+ "delay(1000)" + newLine + "digitalWrite(Servo1, LOW);";
String Motor2_back = "digitalWrite(Motor2back, High" + newLine
+ "delay(6000)" + newLine + "digitalWrite(Motor2back, Low)";
String Motor1_forward = "digitalWrite(Motor1, HIGH);" + newLine
+ "delay(1000);" + newLine + "digitalWrite(Motor1, LOW);";
String dispenseCycle = (Motor2_one + newLine + Servo1_dispense
+ " //Domino" + newLine);
String skipCycle = (Motor2_one + newLine);
String backCycle = (Motor1_forward + newLine + Motor2_back + newLine);
while (buttonpressed == 1) {
for (int x = 0; x < 20; x++) {
Code = oldcode + "//Line " + (x + 1);
oldcode = Code;
yloop: for (int y = 0; y < 40; y++) {
boolean empty = true;
for (int check = y; check < 39; check++) {
if (ButtonGrid.clicked[x][check] == 1) {
empty = false;
System.out.println(x + " not empty");
}
}
if (ButtonGrid.clicked[x][y] == 1 && y == 0) {
Code = oldcode + newLine + Servo1_dispense
+ " //Domino" + newLine;
} else if (ButtonGrid.clicked[x][y] == 1) {
Code = oldcode + newLine + dispenseCycle + newLine;
}
else if (ButtonGrid.clicked[x][y] == 0
&& empty == false) {
Code = oldcode + newLine + skipCycle + newLine;
} else {
Code = oldcode + newLine + backCycle + newLine;
oldcode = Code;
break yloop;
}
oldcode = Code;
}
}
try {
BufferedWriter out = new BufferedWriter(new FileWriter(
"C:\\ArduinoCode.txt"));
out.write(Code);
out.close();
} catch (IOException g) {
System.out.println("Exception ");
}
return;
}
}
}
// button
public static void main(String[] args) {
new ButtonGrid();
new Arduinowriter();
}
}
Note: I am a very beginner. This code has taken many many hours to write and I figured everything out using google and youtube. If anything in the code or what I have said is unclear or doesn't make sense, please forgive me and just ask.
Invoke frame.setVisible(true) after you set the layout manager and everything else that affects its "visual" state.

JFrame FileChooser get file directory

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

Categories