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++)
{
..........
............
}
}
Related
Every time a new swing windows opens in code that is executed in a for loop.
I have some code that is runned in a for loop.
The for loop gives every time a new value to my multidimensional array.
But, every time my for loop creates open's a new windows but does not close the old window.
How can I solve this issues? I want to close the old windows and refresh my window with the new actual values or that only one Windows is opened and that the new values of the for loop refreshes the values inside the table based on the multidimensional array names data.
Because now more than 200 (every second a new windows is opened) windows are opened and after 1 minute I don’t see new values appearing on my window and the computer freezes.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.Timer;
public class UAppWin {
private static final int Status_COL = 1;
String[][] data = new String[3][3];
int dptr;
String[] cols = { "Feature", "Status", "Value" };
public UAppWin(String label, int nphases) {
System.out.println("UApp \"" + label + "\" (" + nphases + " phases)");
}
void newCycle(int phasenr) {
System.out.println("UApp =============================");
dptr = 0;
}
void addEntry(int index, double tim, String label, int status, double dval) {
System.out.println("Uapp [" + index + "] " + label + "(" + status + ") " + dval);
data[dptr][0] = label;
data[dptr][1] = "" + status;
data[dptr][2] = "" + dval;
dptr++;
}
void addMessage(String msg) {
System.out.println("Uapp alert: " + msg);
// rode balk met bericht
}
void deleteMessage() {
}
void endCycle() {
System.out.println("UApp =============================");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
}
});
}
private JTable getTable() {
DefaultTableModel model = new DefaultTableModel(data, cols);
return new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(300, 150);
}
};
}
private static JTable getNewRenderedTable(final JTable table) {
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
String Status = (String) table.getModel().getValueAt(row, Status_COL);
if ("0".equals(Status)) {
setBackground(Color.GREEN);
setForeground(Color.BLACK);
} else if ("2".equals(Status)) {
setBackground(Color.RED);
setForeground(Color.BLACK);
} else {
setBackground(Color.YELLOW);
setForeground(Color.BLACK);
}
return this;
}
});
return table;
}
}
The second part of the code edited:
public class HmOpIntf {
static final String DFLT_IP_ADDR = "127.0.0.1";
static final int DFLT_IP_PORT = 9502;
static final int DFLT_MB_UNIT = 1;
static final int DFLT_POLL_TM = 2;
public static ModbusClient connectPLC(String ipAddr, int port, int unitNr)
{
ModbusClient mc = null;
System.out.println("Connecting to " + ipAddr + " port " + port + " unit " + unitNr);
try {
mc = new ModbusClient(ipAddr, port);
mc.Connect();
mc.setUnitIdentifier((byte)unitNr);
mc.WriteSingleCoil(0, true);
} catch (Exception e) {
System.err.println("*** connectPLC: exception caught");
return null;
}
System.out.println("Connected!");
return mc;
}
public static void disconnectPLC(ModbusClient mc)
{
mc = null;
}
public static String MyConvertRegistersToString(int[] regs, int startIx, int len) {
char[] ca = new char[len];
for (int i = 0; i < len; i++) {
ca[i] = (char) regs[startIx + i];
}
return new String(ca);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ModbusClient mc = null;
String ipAddr = DFLT_IP_ADDR;
int ipPort = DFLT_IP_PORT;
int mbUnit = DFLT_MB_UNIT;
int pollTime = DFLT_POLL_TM;
int tlBase = 2000; /* Offset in PLC's holding registry */
int tlBlocksz = 84;
String[] tlLabel = {"T4 mould", "T injection valve"}; /* Default */
int trafLightNum = tlLabel.length;
String[] colors = { "green", "yellow", "red" };
int status;
// Notifications.infoBox("Hello world!", "Welcome message");
if (args != null && args.length > 0) {
if (args.length < 4) {
System.err.println("*** Error (" + args.length +"): arguments are: ip-addr port unit polltime label-1 ...");
System.exit(1);
}
ipAddr = args[0];
ipPort = Integer.parseInt(args[1]);
mbUnit = Integer.parseInt(args[2]);
pollTime = Integer.parseInt(args[3]);
}
if (args.length > 4) {
trafLightNum = args.length - 4;
tlLabel = new String[trafLightNum];
for (int i = 0; i < trafLightNum; i++) {
tlLabel[i] = args[i + 4];
}
}
// Scope sc = new Scope();
// sc.runScope();
if ((mc = connectPLC(ipAddr, ipPort, mbUnit)) == null) {
System.out.println("*** Failed to connect to PLC");
System.exit(1);
}
TrafficLight tlLast = null;
int[] values = new int[tlBlocksz];
TrafficLight[] tl = new TrafficLight[trafLightNum];
Scope[] sc = new Scope[trafLightNum];
Notifications nots = new Notifications(trafLightNum);
int locX, locY;
for (int i = 0; i < tl.length; i++) {
tl[i] = new TrafficLight();
tl[i].setLbl(tlLabel[i]);
tl[i].setVisible(true);
if (tlLast != null) {
locX = tlLast.getLocation().x;
locY = tlLast.getLocation().y + tlLast.getHeight();
} else {
locX = tl[i].getLocation().x;
locY = tl[i].getLocation().y;
}
tl[i].setLocation(locX, locY);
sc[i] = new Scope(tlLabel[i], locX + tl[i].getWidth(), locY, 320, 290 /* tl[i].getHeight()-80 */ );
sc[i].setGrid(10, 5);
tlLast = tl[i];
}
UAppWin uw = new UAppWin("RTM Facility", 5);
int phase = 1;
// tl2.setVisible(true); tl2.setLocation(tl.getWidth(), 0);
try {
double t = 0.0;
int[] dreg = new int[2];
for (;;) {
uw.newCycle(phase);
for (int i = 0; i < tl.length; i++) {
values = mc.ReadHoldingRegisters(tlBase + i * tlBlocksz, values.length);
status = values[0];
if (status >= 0 && status < colors.length) {
// System.out.println(i + ": " + colors[status]);
if (status == 0) tl[i].greenOn();
else if (status == 1) tl[i].yellowOn();
else tl[i].redOn();
}
else
System.out.println("Status value " + i + " out of range: " + status);
dreg[0] = values[1]; dreg[1] = values[2];
double dval = (double) ModbusClient.ConvertRegistersToFloat(dreg);
sc[i].addValue(t, dval);
sc[i].drawSignal();
// w.addEntry(int i, float t, String label, int status (o = groen, 1 = yellow, 2 = red), float dval);
uw.addEntry(i, t, tlLabel[i], status, dval);
int msglen = values[3];
if (msglen > 0) {
String msg = MyConvertRegistersToString(values, 4, msglen);
System.out.println("DEBUG: received message for " + tlLabel[i] + ": " + msg);
nots.notify(i, msg);
uw.addMessage(msg);
}
else {
nots.notify(i, null);
uw.deleteMessage();
}
// System.out.println("Received for set " + i + ": status=" + status + " dval=" + dval + " msglen=" + msglen);
}
uw.endCycle();
t += 1.0;
Thread.sleep(pollTime * 500);
}
} catch (Exception e) {
System.out.println("*** Failed to communicate with PLC - exit");
System.exit(1);
}
try {
mc.Disconnect();
} catch (IOException e) {
System.out.println("*** Failed to disconnect from PLC");
}
}
}
The UappWin seems to be tied to a window. So when you create it, also create a JFrame. Then nothing else would need to change except the run method and declaring the JFrame.
public class UAppWin {
private JFrame frame;
public UAppWin(String label, int nphases) {
//System.out.println("UApp \"" + label + "\" (" + nphases + " phases)");
JLabel label = new JLabel("UApp \"" + label + "\" (" + nphases + " phases)");
frame = new JFrame("title");
frame.add(label);
frame.setVisible(true);
}
Then when you create the window.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
frame.setContentPane( new JScrollPane( getNewRenderedTable( getTable() ) );
frame.setVisible(true);
}
});
Recently I have been working on a program that can convert TeX-generated PDFs to a certain form of text that retains some semantically meaningful style information such as subscripts and superscripts.
When debugging it seems that there might be something very unusual going on with the PDFTextStripper class.
Here is my TeXUtil class that does most of the work.
import com.google.common.base.CharMatcher;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Stack;
public class TeXUtil {
private Stack<SSStatus> ssstatus;
private boolean accentMode;
private String fs;
private boolean mathMode;
private SymbolDB db;
private Hashtable<String, String> maccDict;
float endY;//Positions
float endX;
float Y;
int height;//Height
//boolean test;
public TeXUtil() throws IOException {
ssstatus = new Stack<SSStatus>();
fs = "rm";
accentMode = false;//as in the state of being right after an accent
mathMode = false;
db = new SymbolDB();
maccDict = new Hashtable<String, String>();
maccDict.put("\\vec","\\vec");
maccDict.put("\\widehat","\\widehat");
maccDict.put("\\widetilde","\\widetilde");
maccDict.put("\\^","\\hat");
maccDict.put("\\v","\\check");
maccDict.put("\\u","\\breve");
maccDict.put("\\`","\\grave");
maccDict.put("\\~","\\tilde");
maccDict.put("\\=","\\bar");
maccDict.put("\\.","\\dot");
maccDict.put("\\","\\ddot");
maccDict.put("\\'","\\acute");
endY = 0;
endX = 0;
Y = 0;
height = 0;
//test = false;
System.out.println("TeXUtil initialized!");
}
private static String fontShortName(PDFont font) {
String[] segments = font.getName().split("\\+");
return segments[segments.length - 1];
}
private static int fontHeight(PDFont font) {
CharMatcher matcher = CharMatcher.inRange('0', '9');
return Integer.parseInt(matcher.retainFrom(fontShortName(font)));
}
private static String fontClass(PDFont font) {
CharMatcher matcher = CharMatcher.inRange('A', 'Z');
return (matcher.retainFrom(fontShortName(font))).toLowerCase();
}
private String textToTeX(String shortFontName, int code) throws JSONException {
JSONObject info = db.getInfo(shortFontName, code);
return info.getString("value");
}
public String fullTextToTeX(PDFont font, int code, float newEndX, float newY, float newEndY){
String shortFontName = fontClass(font);
try {
JSONObject info = db.getInfo(shortFontName, code);
String teXCode = info.getString("value");
StringBuilder preamble1 = new StringBuilder("");
StringBuilder preamble2 = new StringBuilder("");
StringBuilder postamble = new StringBuilder("");
boolean text = info.getBoolean("text");
boolean math = info.getBoolean("math");
boolean tacc = info.getBoolean("tacc");
boolean macc = info.getBoolean("macc");
String newFont = info.getString("font");
int newHeight = fontHeight(font);
//Font change, rm is seen as having no font
if (!newFont.equals(fs)) {
if (!fs.equals("rm"))
preamble1.insert(0, '}');
if (!newFont.equals("rm")) {
preamble2.append('\\');
preamble2.append(newFont);
preamble2.append('{');
}
preamble1.insert(0, " fs = " + fs + " nFs = " + newFont + "\n");
fs = newFont;
}
if (height == 0) {
//preamble2.append(" Meow! am = " + accentMode + " fs = " + fs + " mm = " + mathMode + "\n");
}
//Subscripts/Superscripts
if (height > newHeight && newEndX > endX) {//New subscript/superscript
if (newEndY < endY) {//New superscript
//ssstatus.push(SSStatus.SUP);
preamble2.insert(0, "^{");
}
else if (newY > Y) {//New subscript
//ssstatus.push(SSStatus.SUB);
preamble2.insert(0, "_{");
}
//else {
// System.out.println("Please investigate the situation: texcode = " + teXCode + "endY = " + endY + " Y=" + Y + " endX=" + endX + " newEndY=" + newEndY + " newY=" + newY + " newEndX= " + newEndX);
//}
}
else if (height < newHeight && height != 0) {
//ssstatus.pop();
preamble1.append('}');
}
height = newHeight;
endX = newEndX;
endY = newEndY;
Y = newY;
//Enter or leave math mode
if (mathMode && !math && !macc) {
mathMode = false;
preamble1.append('$');
}
else if (!mathMode && !text && !tacc) {
mathMode = true;
preamble2.insert(0,'$');
}
//Accents
if (accentMode) {//If accent mode is ever entered we need to leave it at once
postamble.append('}');
accentMode = false;
}
if ((mathMode && macc) || (!mathMode && tacc)) {//Right now assume that anything that can be an accent is an accent
postamble.append('{');
if (mathMode)
teXCode = maccDict.get(teXCode);
accentMode = true;
}
if (teXCode.charAt(0) == '\\')
return preamble1.toString() + preamble2.toString() + teXCode + ' ' + postamble.toString();
else
return preamble1.toString() + preamble2.toString() + teXCode + postamble.toString();
}
catch(JSONException e) {
return "\\" + shortFontName + "{" + code + "}";
}
}
}
Here is the main class.
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import com.google.common.base.CharMatcher;
import org.json.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Stack;
public class TEX2TXT {
public static void main(String args[]) throws IOException {
TeXUtil util = new TeXUtil();
//Loading an existing document
File file = new File("/Users/CatLover/Documents/Tex/Examples/c4.pdf");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper() {
protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
TeXUtil util = new TeXUtil();
StringBuilder builder = new StringBuilder();
for(TextPosition position: textPositions) {
float Y = position.getY();
float endY = position.getEndY();
float endX = position.getEndX();
PDFont font = position.getFont();
int[] codes = position.getCharacterCodes();
for(int code: codes) {
builder.append(util.fullTextToTeX(font, code, endX, Y, endY));
}
}
writeString(builder.toString());
}
};
//Retrieving text from PDF document
String text = pdfStripper.getText(document);
System.out.println(text);
//Closing the document
document.close();
}
What's really weird is that TeXUtil is constructed every time any white space between words appear while TeXUtil() should be called only once. I'm not sure why this is the case. Since the PDFs are produced by LaTeX and LaTeX does not put white space characters in PDFs but instead leave space between characters to implicitly represent white spaces this may affect how PDFBox works.
You're constructing a new TeXUtil in the first line of your PDFTextStripper subclass's writeString method. If you just remove that line, it should be able to still reference the util defined in your main method (though depending on the version of java you're using, you may have to make it final).
I have written a Java program that analyze .soft file of data on gene expressions and write it to txt
package il.ac.tau.cs.sw1.bioinformatics;
import org.apache.commons.math3.stat.inference.TestUtils;
import java.io.*;
import java.util.Arrays;
/**
*
* Gene Expression Analyzer
*
* Command line arguments:
* args[0] - GeoDatasetName: Gene expression dataset name (expects a corresponding
input file in SOFT format to exist in the local directory).
* args[1] - Label1: Label of the first sample subset
* args[2] - Label2: Label of the second sample subset
* args[3] - Alpha: T-test confidence level : only genes with pValue below this
threshold will be printed to output file
*
* Execution example: GeneExpressionAnalyzer GDS4085 "estrogen receptor-negative" "estrogen receptor-positive" 0.01
*
* #author software1-2014
*
*/
public class GeneExpressionAnalyzer {
public static void main(String args[]) throws IOException {
// Reads the dataset from a SOFT input file
String inputSoftFileName = args[0] + ".soft";
GeneExpressionDataset geneExpressionDataset = parseGeneExpressionFile (inputSoftFileName);
System.out.printf ("Gene expression dataset loaded from file %s. %n",inputSoftFileName);
System.out.printf("Dataset contains %d samples and %d gene probes.%n%n",geneExpressionDataset.samplesNumber, geneExpressionDataset.genesNumber);
// Writes the dataset to a tabular format
String tabularFileName = args[0] + "-Tabular.txt";
writeDatasetToTabularFile(geneExpressionDataset,tabularFileName);
System.out.printf ("Dataset saved to tabular file - %s.%n%n",tabularFileName);
// Identifies differentially expressed genes between two sample groups and writes the results to a text file
String label1 = args[1];
String label2 = args[2];
double alpha = Double.parseDouble(args[3]);
String diffGenesFileName = args[0] + "-DiffGenes.txt";
int numOfDiffGenes = writeTopDifferentiallyExpressedGenesToFile(diffGenesFileName,geneExpressionDataset, alpha, label1, label2);
System.out.printf ("%d differentially expressed genes identified using alpha of %f when comparing the two sample groups [%s] and [%s].%n",numOfDiffGenes, alpha, label1, label2);
System.out.printf ("Results saved to file %s.%n",diffGenesFileName);
}
private static float[] StringtoFloat(String[] temp) {
float[] array = new float[temp.length];
for (int i = 0; i < temp.length; i++){
array[i]= Float.parseFloat(temp[i]);
}
return array;
}
private static double[] CutToCounter(double[] array, int counter) {
if (array.length == counter){
return array;
}
double[] args = new double[counter+1];
for (int i = 0; i < args.length; i++){
args[i] = array[i];
}
return args;
}
private static int min(double[] pValues) {
double val = 2;
int index = -1;
for (int i = 0; i < pValues.length; i++){
if (pValues[i] < val && pValues[i] != 3.0){
val = pValues[i];
index = i;
}
}
return index;
}
private static String changeformat(float[] array) {
String[] args = new String[array.length];
for (int i = 0; i < array.length; i++){
args[i] = String.format("%.2f", array[i]);
}
return Arrays.toString(args);
}
/**
*
* parseGeneExpressionFile - parses the given SOFT file
*
*
* #param filename A gene expression file in SOFT format
* #return a GeneExpressionDataset object storing all data parsed from the input file
* #throws IOException
*/
public static GeneExpressionDataset parseGeneExpressionFile (String filename) throws IOException {
GeneExpressionDataset dataset = new GeneExpressionDataset();
BufferedReader buf = new BufferedReader(new FileReader(filename));
String line = buf.readLine();
String[] geneids = null;
String[] genesymbols = null;
float[][] datamatrix = null;
String[][] subsetinfo = new String[10][2];
String[][] subsetsample = new String[10][];
int i = 0;
int j = 0;
boolean bol = false;
while (line != null){
if (line.startsWith("!dataset_sample_count")){
dataset.samplesNumber = Integer.parseInt(line.substring(24));
}
else if (line.startsWith("!dataset_sample_count")){
dataset.genesNumber = Integer.parseInt(line.substring(25));
geneids = new String[dataset.genesNumber];
genesymbols = new String[dataset.genesNumber];
}
else if (line.startsWith("^SUBSET")){
subsetinfo[i][0] = line.substring(10);
i++;
}
else if (line.startsWith("!subset_sample_description")){
subsetinfo[i][1] = line.substring(22);
}
else if (line.startsWith("!subset_sample_id")){
subsetsample[i-1] = line.substring(20).split(",");
}
else if (line.startsWith("!dataset_table_begin")){
datamatrix = new float[dataset.genesNumber][dataset.samplesNumber];
}
else if (line.startsWith("ID_REF")){
String[] array1 = line.split("\t");
dataset.sampleIds = (String[]) Arrays.copyOfRange(array1, 2, array1.length);
bol = true;
}
else if (bol && !line.startsWith("!dataset_table_end")){
String[] array2 = line.split("\t");
geneids[j] = array2[0];
genesymbols[j] = array2[1];
String[] temp = (String[]) Arrays.copyOfRange(array2, 2, array2.length);
datamatrix[j] = StringtoFloat(temp);
j++;
}
}
buf.close();
dataset.geneIds = geneids;
dataset.geneSymbols = genesymbols;
dataset.dataMatrix = datamatrix;
String[] lables = new String[dataset.samplesNumber];
int k = 0;
for (String sample : dataset.sampleIds) {
for (int m = 0; m < subsetsample.length; m++) {
if (Arrays.binarySearch(subsetsample[m], sample) != -1) {
lables[k] = subsetsample[m][1];
k += 1;
} else {
continue;
}
}
}
dataset.labels = lables;
return dataset;
}
/**
* writeDatasetToTabularFile
* writes the dataset to a tabular text file
*
* #param geneExpressionDataset
* #param outputFilename
* #throws IOException
*/
public static void writeDatasetToTabularFile(GeneExpressionDataset geneExpressionDataset, String outputFilename) throws IOException {
File NewFile = new File(outputFilename);
BufferedWriter buf = new BufferedWriter(new FileWriter(NewFile));
String Lables = "\t" + "\t" + "\t" + "\t" + Arrays.toString(geneExpressionDataset.labels);
String Samples = "\t" + "\t" + "\t" + "\t" + Arrays.toString(geneExpressionDataset.sampleIds);
buf.write(Lables + "\r\n" + Samples + "\r\n");
for (int i = 0; i < geneExpressionDataset.genesNumber; i++){
buf.write(geneExpressionDataset.geneIds[i] + "\t"+ geneExpressionDataset.geneSymbols[i] + "\t" +
changeformat(geneExpressionDataset.dataMatrix[i]) + "\r\n");
}
buf.close();
}
/**
*
* writeTopDifferentiallyExpressedGenesToFile
*
* #param outputFilename
* #param geneExpressionDataset
* #param alpha
* #param label1
* #param label2
* #return numOfDiffGenes The number of differentially expressed genes detected, having p-value lower than alpha
* #throws IOException
*/
public static int writeTopDifferentiallyExpressedGenesToFile(String outputFilename,
GeneExpressionDataset geneExpressionDataset, double alpha,
String label1, String label2) throws IOException {
double pValues[] = new double[geneExpressionDataset.genesNumber];
int counter = 0;
for (int i = 0; i < pValues.length; i++){
double pval = calcTtest(geneExpressionDataset, i, label1, label2);
if (pval < alpha){
pValues[i] = pval;
counter++;
}
else{
continue;
}
}
File tofile = new File(outputFilename);
BufferedWriter buf = new BufferedWriter(new FileWriter(tofile));
int j = 0;
while (min(pValues) != -1){
String PVal = String.format("%.6f", pValues[min(pValues)]);
String gene_id = geneExpressionDataset.geneIds[min(pValues)];
String gene_symbol = geneExpressionDataset.geneSymbols[min(pValues)];
String line = String.valueOf(j) + "\t" + PVal + "\t" + gene_id + "\t" + gene_symbol;
buf.write(line + "\r\n");
pValues[min(pValues)] = 3.0;
j++;
}
buf.close();
return counter;
}
/**
*
* getDataEntriesForLabel
*
* Returns the entries in the 'data' array for which the corresponding entries in the 'labels' array equals 'label'
*
* #param data
* #param labels
* #param label
* #return
*/
public static double[] getDataEntriesForLabel(float[] data, String[] labels, String label) {
double[] array = new double[data.length];
int counter = 0;
for (int i = 0; i < data.length; i++){
if (labels[i].equals(label)){
array[counter] = data[i];
counter++;
}
else{
continue;
}
}return CutToCounter(array, counter);
}
/**
* calcTtest - returns a pValue for the t-Test
*
* Returns the p-value, associated with a two-sample, two-tailed t-test comparing the means of the input arrays
*
* //http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/stat/inference/TTest.html#tTest(double[], double[])
*
* #param geneExpressionDataset
* #param geneIndex
* #param label1
* #param label2
* #return
*/
private static double calcTtest(GeneExpressionDataset geneExpressionDataset, int geneIndex, String label1, String label2) {
double[] sample1 = getDataEntriesForLabel(geneExpressionDataset.dataMatrix[geneIndex], geneExpressionDataset.labels, label1);
double[] sample2 = getDataEntriesForLabel(geneExpressionDataset.dataMatrix[geneIndex], geneExpressionDataset.labels, label2);
return TestUtils.tTest(sample1, sample2);
}
/**
*
* GeneExpressionDataset
* A class representing a gene expression dataset
*
* #author software1-2014
*
*/
public static class GeneExpressionDataset {
public int samplesNumber; //number of dataset samples
public int genesNumber; // number of dataset gene probes
public String[] sampleIds; //sample ids
public String[] geneIds; //gene probe ids
public String[] geneSymbols; //gene symbols
public float[][] dataMatrix; //expression data matrix
public String[] labels; //sample labels
}
}
now, it won't compile and the error message is this:
"GeneExpressionAnalyzer.java:2: error: package org.apache.commons.math3.stat.inference does not exist
import org.apach.commons.math3.stat.interference.TestUtils;
GeneExpressionAnalyzer.java:277: error: cannot find symbol
return TestUtils.tTest;
symbol: variable TestUtils
location: class GeneExpressionAnalyzer
2 errors"
I don't get what went wrong, obviously i've added the .jar file that contains the path to TestUtils.
(here it is: http://apache.spd.co.il//commons/math/binaries/commons-math3-3.2-bin.zip)
any insights?
If you are working with eclipse,
Manually download the jar file from here
After that in eclipse open the package explorer -> right click on your project
Build Path -> Configure Build Path, A window will open.
Under the Libraries tab -> click Add External JARs. select the jar file you have downloaded Click Ok.
That's all. Now the problem might be gone
Does it work from the command line?
I've shortened your class to
import org.apache.commons.math3.stat.inference.TestUtils;
import java.io.*;
import java.util.Arrays;
public class Test {
public static void main(String args[]) throws IOException {
System.out.printf ("test...");
}
}
I copied the Test.java file and the commons-math3-3.2.jar to the same directory and here is my output from the command line:
C:\temp\test>dir
Répertoire de C:\temp\test
24/04/2014 14:41 <REP> .
24/04/2014 14:41 <REP> ..
24/04/2014 14:38 1 692 782 commons-math3-3.2.jar
24/04/2014 14:41 230 Test.java
2 fichier(s) 1 693 012 octets
2 Rép(s) 23 170 342 912 octets libres
C:\temp\test>javac Test.java
Test.java:1: package org.apache.commons.math3.stat.inference does not exist
import org.apache.commons.math3.stat.inference.TestUtils;
^
1 error
C:\temp\test>javac -cp commons-math3-3.2.jar Test.java
C:\temp\test>dir
Répertoire de C:\temp\test
24/04/2014 14:41 <REP> .
24/04/2014 14:41 <REP> ..
24/04/2014 14:38 1 692 782 commons-math3-3.2.jar
24/04/2014 14:41 500 Test.class
24/04/2014 14:41 230 Test.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
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.