How to pass a file into another class when uploaded with JFileChooser - java
I am trying to take in a file from a JFileChooser that I can then pass into my TextStatistics class. I can't seem to keep reference to the file... Any help would be greatly appreciated.
Thanks!
ProcessText.java:
public class ProcessText extends JPanel implements ActionListener {
static private final String newline = "\n";
JButton openButton;
JButton calculate;
JTextArea log;
JFileChooser fc;
public ProcessText() {
super(new BorderLayout());
log = new JTextArea(5, 20);
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
JPanel buttonPanel = new JPanel(); // use FlowLayout
buttonPanel.add(openButton);
buttonPanel.add(calculate);
// Add the buttons and the log to this panel.
add(buttonPanel, BorderLayout.PAGE_START);
add(logScrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
File file = null;
TextStatistics stat = null;
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(ProcessText.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
stat = new TextStatistics(file);
}
}
if (e.getSource() == calculate) {
log.append(stat.toString());
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = ProcessText.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("FileChooserDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add content to the window.
frame.add(new ProcessText());
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event dispatch thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
TextStatistics.java
public class TextStatistics implements TextStatisticsInterface {
public Scanner fileScan;
public int[] countLetters = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // gives the starting values for count of each letter.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //initial amount of each letter. countLetters[0] corresponds to 'a'
//countLetters[1] to 'b' and so on.
public int[] length = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //keeps word frequency lengths
0, 0, 0, 0, 0, 0, 0 };
int lineCount = 0; //keeps track of lines
int wordCount = 0; //keeps track of words
int charCount = 0; //keeps track of characters
double avg = 0;
double avgFinal = 0; //average word length
String strLine = "";
String largestWord;
File file;
ArrayList<Integer> line; //line with longest word length
/**
* reads in one file at a time and one line at a time to determine the
* statistics described above.
*
* #author Ryleigh More
*/
public TextStatistics(File file) {
Scanner scan;
try {
scan = new Scanner(file);
this.file = file;
line = new ArrayList<Integer>();
int largestIndex = 0;
while (scan.hasNextLine()) {
strLine = scan.nextLine().toLowerCase();
lineCount++;
charCount += strLine.length() + 1;
StringTokenizer tokenizer = new StringTokenizer(strLine,
" , .;:'\"&!?-_\n\t12345678910[]{}()##$%^*/+-");
for (int i = 0; i < strLine.length(); i++) {
char theLetter = strLine.charAt(i);
if (theLetter >= 'a' && theLetter <= 'z')
countLetters[theLetter - 'a']++;
while (tokenizer.hasMoreTokens()) {
String theWord = tokenizer.nextToken();
int currentWordLength = theWord.length();
if (currentWordLength > largestIndex) {
largestWord = theWord;
largestIndex = currentWordLength;
line.clear();
}
if (largestWord.equals(theWord)) {
line.add(lineCount);
}
if (currentWordLength < 23 && currentWordLength > 0) {
length[currentWordLength]++;
}
wordCount++;
}
}
}
for (int j = 1; j < length.length; j++)
avg += (length[j] * j);
avgFinal = avg / wordCount;
scan.close();
} catch (FileNotFoundException e) {
System.out.println(file + " does not exist");
}
}
/**
* puts all the statistics in a String for printing by the ProcessText
* class.
*
* #return s
* #author Ryleigh Moore
*/
public String toString() {
DecimalFormat two = new DecimalFormat("#0.00");
String s = "Statistics for " + file + "\n"
+ "======================================================\n"
+ lineCount + " Lines\n" + wordCount + " Words\n" + charCount
+ " Characters\n" + "-----------------------------------------"
+ "\na= " + countLetters[0] + "\t n= " + countLetters[13]
+ "\nb= " + countLetters[1] + "\t o= " + countLetters[14]
+ "\nc= " + countLetters[2] + "\t p= " + countLetters[15]
+ "\nd= " + countLetters[3] + "\t q= " + countLetters[16]
+ "\ne= " + countLetters[4] + "\t r= " + countLetters[17]
+ "\nf= " + countLetters[5] + "\t s= " + countLetters[18]
+ "\ng= " + countLetters[6] + "\t t= " + countLetters[19]
+ "\nh= " + countLetters[7] + "\t u= " + countLetters[20]
+ "\ni= " + countLetters[8] + "\t v= " + countLetters[21]
+ "\nj= " + countLetters[9] + "\t w= " + countLetters[22]
+ "\nk= " + countLetters[10] + "\t x= " + countLetters[23]
+ "\nl= " + countLetters[11] + "\t y= " + countLetters[24]
+ "\nm= " + countLetters[12] + "\t z: " + countLetters[25]
+ "\n-----------------------------------------"
+ "\n Length Frequency" + "\n ------- ---------";
for (int q = 1; q < length.length; q++) {
if (length[q] > 0)
s += "\n\t" + q + " =\t" + length[q];
}
s += "\nThe average word length = " + two.format(avgFinal)
+ "\nThe longest word is '" + largestWord + "' and is on line "
+ line
+ "\n======================================================";
return s;
}
public void actionPerformed(ActionEvent e) {
File file = null;
TextStatistics stat = null;
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(ProcessText.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
stat = new TextStatistics(file);
}
}
if (e.getSource() == calculate) {
log.append(stat.toString());
}
}
The thing is, when you press the openButton, it creates the new TextStatisics but that's it. It doesn't append the text the the JTextArea. You only do that with the press of calculate. So when openButton is pressed, the local TextStatistics is created, then nothing is don't with it, so it's tossed out. When calculate is pressed, the log tries to append a null TextStatistics.
So you can either append the TextStatistics stat to the log inside of the if (e.getSource() == openButton) { or make TextStatistics stats a global class member that will persist between button presses. So when openButton is pressed, TextStatisitcs stat will persist to a calculate button press.
Every time actionPerformed runs, it makes a new variable stat and sets it to null. But you actually want two different calls to actionPerformed to use the same copy of the variable.
I would recommend moving the declaration TextStatistics stat = null; out of actionPerformed and putting it at the top of the class, before all the methods, so that stat becomes a field of the class. That way, its value will survive from one actionPerformed call to the next.
Related
Need code to perform binary search tree with graphics on java - insertion and deletion
I need to perform binary search tree operations - insert, delete, search on java with graphics. The UI must look like this: https://i.stack.imgur.com/o4yyU.png I've written the code for insertion and have made the UI. But I feel the code I've written is quite primitive and also read that this would be easier if I used Buffered Images and I tried that but am unable to implement it. I'm also having trouble with the delete function - removing the nodes and repainting the tree. Some sample code for the delete function sure would help me a lot. So any help with the delete function and making the insertion code easier to work with is much appreciated. import java.awt.*; import java.applet.*; import java.awt.event.*; import javax.swing.*; public class WithUI extends JFrame{ /** * */ private static final long serialVersionUID = 1L; JPanel p1,p2,p3; JTextField ins,del,find; JButton ins_but,del_but,find_but,print_but; JLabel bst_heading; //DrawPanel panel = new DrawPanel(); String p = " "; int mov1 = 0; int mov2 = 0; class Node{ Node left = null; Node right = null; int value; Node(int val){ this.value = val; } } WithUI(){ //Creating UI p1 = new JPanel(); p2 = new JPanel(); p3 = new JPanel(); ins = new JTextField(7); del = new JTextField(7); find = new JTextField(7); ins_but = new JButton("Insert"); del_but = new JButton("Delete"); find_but = new JButton("Find"); print_but = new JButton("Print"); bst_heading = new JLabel("Binary Search Tree"); Font f1 = new Font("Calibri",Font.BOLD,70); bst_heading.setFont(f1); bst_heading.setForeground(Color.yellow); p1.setBackground(Color.green.darker().darker()); p1.setBounds(0,0,800,100); p1.add(bst_heading); p2.setLayout(new FlowLayout(FlowLayout.LEFT)); p2.add(ins); p2.add(ins_but); p2.add(del); p2.add(del_but); p2.add(find); p2.add(find_but); p2.add(print_but); p2.setBackground(Color.LIGHT_GRAY); p2.setBounds(0,100,800,50); p3.add(p1); p3.add(p2); p3.setBounds(0,0,800,150); add(p3); setLayout(null); //add(panel); setFocusable(true); //Creating main node Node nodeMain = new Node(15); nodeMain.left = null; nodeMain.right = null; JLabel mainLabel = new JLabel(String.valueOf(nodeMain.value)); // LABEL1 add(mainLabel); mainLabel.setBackground(Color.green.darker().darker()); mainLabel.setOpaque(true); mainLabel.setBounds(400,200,25,25); mainLabel.setForeground(Color.yellow); ins_but.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int left = 400; int down = 200; int val = Integer.parseInt(ins.getText()); JLabel label = new JLabel(ins.getText()); label.setForeground(Color.yellow); String s = insertNode(val, nodeMain, left, down); String[] nums = s.split("\\s+"); add(label); int[] numsInt = { 400, 200, 400, 200 }; numsInt[0] = Integer.parseInt(nums[0]); numsInt[1] = Integer.parseInt(nums[1]); numsInt[2] = Integer.parseInt(nums[2]); numsInt[3] = Integer.parseInt(nums[3]); label.setBounds(numsInt[0], numsInt[1], 25, 25); label.setBackground(Color.green.darker().darker()); label.setOpaque(true); Graphics g = getGraphics(); g.drawLine(numsInt[2] + 25, numsInt[3] + 55, numsInt[0] + 20, numsInt[1] + 30); // messy part System.out.println(nums[2] + " " + nums[3] + " " + nums[0] + " " + nums[1]); System.out.println(numsInt[0] + " " + numsInt[1] + " " + numsInt[2] + " " + numsInt[3] + " "); System.out.println(); } }); } /*public void paint(Graphics g) { g.setColor(Color.green.darker().darker()); g.drawOval(400, 200, 50, 50); g.drawString(Integer.toString(num),450,250); }*/ public static void main(String[] args) { JFrame frame = new WithUI(); frame.setSize(800, 800); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } String insertNode(int value, Node nodeMain, int left, int down) { Node newNode = new Node(value); if (nodeMain.value > newNode.value && nodeMain.left != null) { if (left == 400 && down == 200) insertNode(newNode.value, nodeMain.left, left - 100, down + 60); else insertNode(newNode.value, nodeMain.left, left - 30, down + 30); } else if (nodeMain.value < newNode.value && nodeMain.right != null) { if (left == 400 && down == 200) insertNode(newNode.value, nodeMain.right, left + 100, down + 60); else insertNode(newNode.value, nodeMain.right, left + 30, down + 30); } else if (nodeMain.left == null && nodeMain.value > newNode.value) { nodeMain.left = newNode; if (left == 400 && down == 200) p = String.valueOf(left - 100) + " " + String.valueOf(down + 60) + " " + String.valueOf(left) + " " + String.valueOf(down); else p = String.valueOf(left - 30) + " " + String.valueOf(down + 30) + " " + String.valueOf(left) + " " + String.valueOf(down); return p; } else if (nodeMain.right == null && nodeMain.value < newNode.value) { nodeMain.right = newNode; if (left == 400 && down == 200) p = String.valueOf(left + 100) + " " + String.valueOf(down + 60) + " " + String.valueOf(left) + " " + String.valueOf(down); else p = String.valueOf(left + 30) + " " + String.valueOf(down + 30) + " " + String.valueOf(left) + " " + String.valueOf(down); return p; } return p; } }
Every time a new swing windows opens in code that is executed in a for loop
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); } });
Android GraphView and Mediaplayer falling out of synchronization
I'm working on a project, where I need to show the pitches of the words (from the song) in a GraphView. I wrote a program that would get the pitches from a song and create a .txt file from it. Then I wrote a class, that reads the file and creates a list from it. So in the end I would have a list that consists of words and word contains pitches. In the MakePitchesList you can see what the pitches output from a song looks like. I have 0,14:23281,61 on every line. The first part of the line is timeOccurance meaning, when this pitch was heard and the second part is the pitch itself. So in this example the timeOccurance would be 0,14 and pitch at that given time 23281,61. Here are the three classes that make a wordsList out of a pitch .txt file. public class Pitch{ float occuranceTime; float pitch; public void setOccuranceTime(float occuranceTime) { this.occuranceTime = occuranceTime; } public float getOccuranceTime() { return occuranceTime; } public void setPitch(float pitch) { this.pitch = pitch; } public float getPitch() { return pitch; } } public class MakePitchesList { String[] pitches; List<Pitch> listOfPitches = new ArrayList<Pitch>(); public List<Pitch> getListOfPitches(){ getPitches(); for (String pitchString: pitches) { Pitch pitch = new Pitch(); makeListOfPitches(pitch, pitchString); } return listOfPitches; } public void makeListOfPitches(Pitch pitch, String pitchString){ pitch.setPitch(getPitchesInfo(pitchString, 1)); pitch.setOccuranceTime(getPitchesInfo(pitchString, 0)); listOfPitches.add(pitch); } public String[] getPitches() { pitches = pitchesRaw.split("\\r?\\n"); return pitches; } private float getPitchesInfo(String pitch, int position){ String[] frequencyAndTime = pitch.split("\\:"); if(position == 0){ return Float.parseFloat(frequencyAndTime[0].replace(',', '.')); } if(position == 1){ return Float.parseFloat(frequencyAndTime[1].replace(',', '.')); } else return 0; } String pitchesRaw = "0,14:23281,61\n" + "0,23:53,65\n" + "0,37:72,53\n" + "0,56:86,09\n" + "0,60:88,58\n" + "0,65:87,45\n" + "0,70:87,11\n" + "0,74:89,56\n" + "0,79:96,22\n" + "0,84:23288,24\n" + "0,88:103,92\n" + "0,93:107,46\n" + "0,98:108,02\n" + "1,02:107,51\n" + "1,07:104,92\n" + "1,11:105,94\n" + "1,16:106,40\n" + "1,21:104,43\n" + "1,25:104,93\n" + "1,30:108,01\n" + "1,35:316,81\n" + "1,39:103,98\n" + "1,44:23297,42\n" + "1,49:23357,42\n" + "1,53:23359,74\n" + "1,58:23393,04\n" + "1,63:23244,18\n" + "1,67:23220,51\n" + "1,72:23250,06\n" + "1,76:23288,84\n" + "1,81:23241,81\n" + "1,86:23295,22\n" + "1,90:23268,04\n" + "1,95:23252,78\n" + "2,00:23224,22\n" + "2,04:23429,71\n" + "2,09:23214,58\n" + "2,14:23240,70\n" + "2,18:23237,71\n" + "2,23:23231,22\n" + "2,28:23222,77\n" + "2,32:23239,73\n" + "2,37:23235,98\n" + "2,41:23222,16\n" + "2,46:23224,01\n" + "2,51:23214,26\n" + "2,55:23223,20\n" + "2,60:23234,11\n" + "2,65:23221,65\n" + "2,69:23213,45\n" + "2,74:23217,44\n" + "2,79:23235,93\n" + "2,83:11122,79\n" + "2,88:23234,58\n" + "2,93:23229,52\n" + "2,97:23255,48\n" + "3,02:23254,44\n" + "3,07:23355,41\n" + "3,44:105,48\n" + "3,48:115,45\n" + "3,53:117,78\n" + "3,58:127,36\n" + "3,62:131,24\n" + "3,67:130,33\n" + "3,72:131,93\n" + "3,76:127,32\n" + "3,81:117,18\n" + "3,85:117,80\n" + "3,90:117,15\n" + "3,95:121,04\n" + "3,99:131,22\n" + "4,04:130,38\n" + "4,09:130,34\n" + "4,13:129,57\n" + "4,18:120,38\n" + "4,23:121,06\n" + "4,32:100,12\n" + "4,37:23483,16\n" + "4,41:112,95\n" + "4,46:23448,04\n" + "4,50:23396,09\n" + "4,55:23292,90\n" + "4,60:117,21\n" + "4,64:116,58\n" + "4,69:116,62\n" + "4,74:119,18\n" + "4,78:131,19\n" + "4,83:130,34\n" + "4,88:129,59\n" + "4,92:132,64\n" + "4,97:129,68\n" + "5,02:132,71\n" + "5,06:133,57\n" + "5,11:128,94\n" + "5,15:131,09\n" + "5,20:132,75\n" + "5,25:129,68\n" + "5,29:131,26\n" + "5,34:131,22\n" + "5,39:130,38\n" + "5,43:146,01\n" + "5,48:140,43\n" + "5,57:23450,16\n" + "5,62:130,46\n" + "5,67:132,02\n" + "5,71:23243,22\n" + "5,76:23456,28\n" + "5,85:23246,64\n" + "5,90:23274,97\n" + "5,94:23310,30\n" + "5,99:23229,71\n" + "6,08:23214,33\n" + "6,13:23221,53\n" + "6,18:23263,48\n" + "6,22:23213,17\n" + "6,27:23235,04\n" + "6,32:23222,02\n" + "6,36:23214,90\n" + "6,41:23230,05\n" + "6,46:23212,55\n" + "6,50:23221,33\n" + "6,55:23226,70\n" + "6,59:23217,07\n" + "6,64:23272,07\n" + "6,69:11102,74\n" + "6,73:23263,38\n" + "6,78:23217,53\n" + "6,97:23243,63\n" + "7,11:23214,11\n" + "7,15:23229,58\n" + "7,20:23225,70\n" + "7,24:23244,82\n" + "7,29:23243,09\n" + "7,34:23249,66\n" + "7,38:23226,67\n" + "7,43:23246,31\n" + "7,48:23258,55\n" + "7,52:23230,34\n" + "7,57:23225,60\n" + "7,62:23280,25\n" + "7,66:23238,08\n" + "7,71:23221,47\n" + "7,85:117,87\n" + "7,89:117,19\n" + "7,94:117,21\n" + "7,99:117,21\n" + "8,03:116,57\n" + "8,08:119,10\n" + "8,13:44,01\n" + "8,17:129,52\n" + "8,22:132,72\n" + "8,27:143,19\n" + "8,31:141,13\n" + "8,36:139,35\n" + "8,45:132,82\n" + "8,50:129,76\n" + "8,54:130,43\n" + "8,68:94,20\n" + "8,78:132,70\n" + "8,82:130,43\n" + "8,87:129,60\n" + "8,92:130,56\n" + "8,96:128,92\n" + "9,01:119,19\n" + "9,06:118,45\n" + "9,10:103,41\n" + "9,15:103,41\n" + "9,20:103,89\n" + "9,24:106,46\n" + "9,29:214,93\n" + "9,33:23427,95\n" + "9,38:23356,01\n" + "9,43:106,41\n" + "9,47:100,57\n" + "9,52:106,39\n" + "9,57:104,40\n" + "9,61:99,70\n" + "9,66:106,42\n" + "9,71:103,50\n" + "9,75:104,47\n" + "9,80:106,97\n" + "9,85:99,68\n" + "9,89:23454,22\n" + "9,94:23299,56\n" + "9,98:23275,30\n" + "10,03:23222,72\n" + "10,08:23246,09\n" + "10,12:23221,14\n" + "10,17:23240,54\n" + "10,22:23246,81\n" + "10,26:23224,74\n" + "10,31:23249,41\n" + "10,36:23214,79\n" + "10,40:23213,46\n" + "10,45:23259,51\n" + "10,50:23217,39\n" + "10,54:23215,36\n" + "10,59:23224,87\n" + "10,63:23242,27\n" + "10,68:23270,82\n" + "10,73:23243,19\n" + "10,77:23222,75\n" + "10,82:23268,78\n" + "10,87:23321,62\n" + "10,91:23259,65\n" + "11,05:23226,24\n" + "11,10:23222,92\n" + "11,15:23218,83\n" + "11,19:23211,71\n" + "11,24:11112,28\n" + "11,28:23261,03\n" + "11,33:23265,31\n" + "11,38:23245,92\n" + "11,42:57,09\n" + "11,61:103,45\n" + "11,66:103,91\n" + "11,70:102,02\n" + "11,75:107,96\n" + "11,80:105,43\n" + "11,84:104,46\n" + "11,89:116,64\n" + "11,94:115,99\n" + "11,98:114,77\n" + "12,03:121,72\n" + "12,07:123,16\n" + "12,12:125,12\n" + "12,17:128,85\n" + "12,21:120,37\n" + "12,26:116,52\n" + "12,31:130,55\n" + "12,35:131,06\n" + "12,40:131,89\n" + "12,45:128,88\n" + "12,49:23397,75\n" + "12,59:118,45\n" + "12,63:116,54\n" + "12,68:119,70\n" + "12,72:115,45\n" + "12,77:115,30\n" + "12,82:119,86\n" + "12,86:116,59\n" + "12,91:114,13\n" + "12,96:119,04\n" + "13,00:118,47\n" + "13,05:115,38\n" + "13,10:128,92\n"; } public class MakeWordsList { List<Pitch> pitches; public List<List<Pitch>> getWordsList(List<Pitch> pitchList) { return makeWordsList(pitchList); } List<Pitch> oneWord = new ArrayList<>(); List<List<Pitch>> wordList = new ArrayList<>(); public List<List<Pitch>> makeWordsList(List<Pitch> pitchList){ pitches = pitchList; int pauseCounter = 0; for (int i = 0; i < pitchList.size(); i++) { if(pitchList.get(i).getPitch() > 10000){ pauseCounter++; } else { if(pauseCounter > 0){ if(pauseCounter >= 5){ wordList.add(oneWord); oneWord = new ArrayList<>(); } pauseCounter = 0; } oneWord.add(pitchList.get(i)); } } if(oneWord.size() > 0){ wordList.add(oneWord); } return wordList; } } Now from that wordsList I create a scrollable GraphView that on paper would look something like this. Now I have set the boundaries for the GraphView: MinX = -0.8; MaxX = 0.4. This way I'm showing 1 sec at a time on screen. Then I start a thread so it would change the coordinates of the GraphView by 0.1 every 100ms, which should add up as 1 every sec. Here it is in code: public class MainActivity extends AppCompatActivity { final static double GRAPH_STARTING_X = -0.8; final static double GRAPH_ENDING_X = 0.4; List<java.util.List<Pitch>> wordsList; private Viewport graphViewPort; private Handler handler; private Runnable runnable; private GraphView graph; private DataPoint[] points; private LineGraphSeries<DataPoint> series; private int seriesNr; private double orderNr = GRAPH_STARTING_X; private ImageButton playRecordButton; private List<Pitch> pitchesList; private int songIndex; private MediaPlayer mediaPlayer; private boolean isPlaying = false; #SuppressLint("ClickableViewAccessibility") #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Get Textview and Button playRecordButton = (ImageButton) findViewById(R.id.playRecord); //Initialize pitches and words MakePitchesList listOfPithes = new MakePitchesList(); MakeWordsList listOfWords = new MakeWordsList(); pitchesList = listOfPithes.getListOfPitches(); wordsList = listOfWords.getWordsList(pitchesList); //Initialize graph graph = (GraphView) findViewById(R.id.graph); initGraph(); //ViewPort graphViewPort = graph.getViewport(); //Handler handler = new Handler(); playRecordButton.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { if(!isPlaying){ playMedia(songIndex); //Start moving graph //Moved to PlayMedia - setOnPreparedListen // drawAndMoveGraph(); isPlaying = true; } else if(isPlaying){ //Move graph to starting position resetGraph(); //Stop Playing audio stopAudio(); isPlaying = false; } } }); } //Moves the graph every 100ms by 0.1 which results in 1 every second private void drawAndMoveGraph() { runnable = new Runnable() { public void run() { graphViewPort.setMinX(orderNr); graphViewPort.setMaxX(orderNr + 1); graph.invalidate(); if (pitchesList.size() != orderNr) { orderNr = orderNr + 0.1; } handler.postDelayed(this, 100); } }; runnable.run(); } //Load up and paint the graph private void initGraph() { for (int i = 0; i < wordsList.size(); i++) { seriesNr = 0; points = new DataPoint[wordsList.get(i).size()]; for (Pitch pitch : wordsList.get(i)) { points[seriesNr] = new DataPoint(pitch.getOccuranceTime(), pitch.getPitch()); seriesNr++; } series = new LineGraphSeries<>(points); series.setThickness(15); graph.addSeries(series); } //VocalTestPoints - Just for vocal testing PointsGraphSeries<DataPoint> series = new PointsGraphSeries<>(new DataPoint[]{ new DataPoint(0, 50), new DataPoint(0, 75), new DataPoint(0, 100), new DataPoint(0, 125), new DataPoint(0, 150), new DataPoint(0, 175), new DataPoint(0, 200), new DataPoint(0, 225), new DataPoint(0, 250), new DataPoint(0, 275), }); series.setSize(5); series.setColor(Color.YELLOW); graph.addSeries(series); // set manual X bounds graph.getViewport().setYAxisBoundsManual(true); graph.getViewport().setMinY(-50); graph.getViewport().setMaxY(400); graph.getViewport().setXAxisBoundsManual(true); graph.getViewport().setMinX(GRAPH_STARTING_X); graph.getViewport().setMaxX(GRAPH_ENDING_X); graph.getViewport().setScrollable(true); } // Play the chosen song and start moving the graph private void playMedia(int songIndex) { Uri uri = Uri.parse("android.resource://com.example.thermaltakei7.testsinging/" + R.raw.perfect); mediaPlayer = new MediaPlayer(); //Reset so that the MediaPlayer is not pointing to another data source mediaPlayer.reset(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(getApplicationContext(), uri); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { #Override public void onPrepared(MediaPlayer mp) { mediaPlayer.start(); drawAndMoveGraph(); } }); } //Stop audio from playing private void stopAudio() { mediaPlayer.stop(); mediaPlayer.release(); } //Reset graph to its initial position private void resetGraph() { handler.removeCallbacks(runnable); graphViewPort.setMinX(GRAPH_STARTING_X); graphViewPort.setMaxX(GRAPH_ENDING_X); graph.invalidate(); orderNr = GRAPH_STARTING_X; } } To sum up what the code does: it gets the wordsList from the pitches, initializes the graph, starts listening button click. When button is clicked, it starts moving graph as described above and plays audio. The problem is that the audio and moving graphView go out of sync. For the first 10sec or so it works like it should but then the lines start falling behind. I would really appreciate if someone took their time to understand all of this mess. Maybe picture of the actual final graphView will also help. . Blue line is the first incoming word. The audio's timing and line should meet at "0". I have also created a small sample that only contains the classes and topics mentioned above. It can be accessed from here: https://github.com/richardboss/testSinging This code containst a song in its raw folder so it's a bit bigger than it should be, but this was the fastest way to show a demo of what I was trying to say. Any ideas, suggestions, help is really welcome. Or comments on the code style.
Java prediction error Random not working? [closed]
Closed. This question needs debugging details. It is not currently accepting answers. Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question. Closed 5 years ago. Improve this question Hello I have been working on a program that predicts numbers. I have went through the code several times now and edited it. For some reason teamOneScored is ALWAYS higher than teamTwoScored. This does not make any sense to me. What is the error that is occurring? Here is my CompareEngine Class: package compare; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Random; import data.Main; public class CompareEngine { public static void Comparison(int firstTeamTotal, int secondTeamTotal, int[] firstPositionAmount, int[] secondPositionAmount, int[] firstPosition, int[] secondPosition) { System.out.println(" Comparisons:"); System.out.println("----------------------------------------"); System.out.println(Main.firstTeam + " vs. " + Main.secondTeam); System.out.println("----------------------------------------"); System.out.println(firstTeamTotal + " Total " + " " + secondTeamTotal); System.out.println(""); System.out.println(firstPosition[0]-1+"-"+firstPosition[1]+"-"+firstPosition[2] + " Formation " + (secondPosition[0]-1) +"-"+secondPosition[1]+"-"+secondPosition[2]); System.out.println(""); System.out.println(firstPosition[0] + " Defenders " + " " + secondPosition[0]); System.out.println(firstPositionAmount[0] + " Defense Total " + " " + secondPositionAmount[0]); System.out.println(""); System.out.println(firstPosition[1] + " Midfielders " + " " + secondPosition[1]); System.out.println(firstPositionAmount[1] + " Midfield Total " + " " + secondPositionAmount[1]); System.out.println(""); System.out.println(firstPosition[2] + " Attackers " + " " + secondPosition[2]); System.out.println(firstPositionAmount[2] + " Attack Total " + " " + secondPositionAmount[2]); } public static void RunGame(int firstTeamTotal, int secondTeamTotal, int[] firstPositionAmount, int[] secondPositionAmount, int[] firstPosition, int[] secondPosition) throws IOException { int depth; System.out.println("What depth do you want to run?"); depth = Main.read.nextInt(); int firstShotCount = 0; int secondShotCount = 0; int firstDefense = firstPositionAmount[0] + firstPositionAmount[1]/2; int secondDefense = secondPositionAmount[0] + secondPositionAmount[1]/2; int firstAttack = firstPositionAmount[2] + firstPositionAmount[1]/2; int secondAttack = secondPositionAmount[2] + secondPositionAmount[2]/2; while(firstAttack*3 > secondDefense) { firstShotCount = firstShotCount + 1; firstAttack = firstAttack - 5; } while(secondAttack*3 > firstDefense) { secondShotCount = secondShotCount + 1; secondAttack = secondAttack - 5; } System.out.println(firstShotCount); System.out.println(secondShotCount); PossessionControl(Main.firstTeam, Main.secondTeam); int[] teamOneScored = new int[99]; int[] teamTwoScored = new int[99]; int[] oneShotOn = new int[99]; int[] twoShotOn = new int[99]; int[] OnePossession = new int[99]; int[] TwoPossession = new int[99]; Random random = new Random(); for(int i = 0; i < depth; i++) { for(int x = 0; firstShotCount >= x; x++) { int shot = random.nextInt(10 - 1 + 1) + 1; if (shot > 8) { teamOneScored[i] = teamOneScored[i] + 1; } if (shot > 4) { oneShotOn[i] = oneShotOn[i] + 1; } } for(int y = 0; secondShotCount >= y; y++) { int shot = random.nextInt(10 - 1 + 1) + 1; if (shot > 8) { teamTwoScored[i] = teamTwoScored[i] + 1; } if (shot > 4) { twoShotOn[i] = twoShotOn[i] + 1; } } System.out.println(teamOneScored[i] + ":" + teamTwoScored[i]); } } static File firstDataFile = new File("src/playerdata/" + Main.firstTeam); static File secondDataFile = new File("src/playerdata/" + Main.secondTeam); static int teamOnePossessionTotal = 0; static int teamTwoPossessionTotal = 0; public static void PossessionControl(String firstTeam, String secondTeam) throws IOException { BufferedReader br1 = new BufferedReader(new FileReader(firstDataFile)); String line = ""; for(int i = 1; i+1 < 13; i++) { line = br1.readLine(); teamOnePossessionTotal = teamOnePossessionTotal + PossessionStatTotal(line); } br1.close(); BufferedReader br2 = new BufferedReader(new FileReader(secondDataFile)); for(int i = 1; i+1 < 13; i++) { line = br2.readLine(); teamTwoPossessionTotal = teamTwoPossessionTotal + PossessionStatTotal(line); } br2.close(); } public static int PossessionStatTotal(String line) { int value = 0; String[] stats = line.split("-"); String position = stats[1]; if(!(position.equals("GK"))) { String passing = stats[5]; String positioning = stats[7]; String ballControl = stats[9]; value = (int) ((int) (Integer.valueOf(passing)*.5) + Integer.valueOf(positioning)*.2 + Integer.valueOf(ballControl)*.1); } return value; } } Here is my Main Class: package data; import java.io.IOException; import java.util.Scanner; public class Main { public static String currentTeam; public static void main(String[] args) throws IOException { compareTeams(); //setOveralls(); } public static void setOveralls() throws IOException { Scanner read = new Scanner(System.in); System.out.println("Which team do you like?"); currentTeam = read.nextLine(); read.close(); PlayerOverall.eraseOverallFile(); PlayerOverall.getPlayerInfo(13, currentTeam); } public static String firstTeam; public static String secondTeam; public static Scanner read = new Scanner(System.in); public static void compareTeams() throws IOException { System.out.println("What is the first team?"); firstTeam = read.nextLine(); System.out.println("What is the second team?"); secondTeam = read.nextLine(); compare.CompareTeams.compare(firstTeam, secondTeam); } } Here is the PlayerOverall Class, this just determines their Overall. package data; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class PlayerOverall { //NOTE TO SELF -- CHANGE OUT OF HARD CODE VVVVVVVVVVV static File dataFile = new File("src/playerdata/" + Main.currentTeam); static File overallFile = new File("src/overalls/" + Main.currentTeam); public static String getPlayerInfo(int numLine, String currentTeam) throws IOException { BufferedReader br = new BufferedReader(new FileReader(dataFile)); String line = ""; for(int i = 1; i+1 < numLine; i++) { line = br.readLine(); evaluatePlayer(line); } br.close(); return line; } public static void evaluatePlayer(String line) throws IOException { String[] stats = line.split("-"); String position = stats[1]; int overall = 0; if(position.equals("GK")) { int height = Integer.parseInt(stats[2]); int diving = Integer.parseInt(stats[3]); int catching = Integer.parseInt(stats[4]); int shooting = Integer.parseInt(stats[5]); int reflexes = Integer.parseInt(stats[6]); int positioning = Integer.parseInt(stats[7]); overall = (int) ((int) ((int) ((int) ((int) ((int) (height*.05) + diving*.2) + catching*.2) + shooting*.1) + reflexes*.2) + positioning*.25); setOverall(position, overall); //OVERALL WORKS CORRECT NOW DO THE ADDITION OF OVERALL TO THE FILE!! } else { int speed = Integer.parseInt(stats[2]); int acceleration = Integer.parseInt(stats[3]); int distance = Integer.parseInt(stats[4]); int passing = Integer.parseInt(stats[5]); int shooting = Integer.parseInt(stats[6]); int positioning = Integer.parseInt(stats[7]); int defending = Integer.parseInt(stats[8]); int ballControll = Integer.parseInt(stats[9]); if(position.equals("LB") || position.equals("RB")) { overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.2) + acceleration*.2) + distance*.1) + passing*.1) + shooting*.1) + positioning*.15) + defending*.15) + ballControll*.1); } else if(position.equals("CB")) { overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.095) + acceleration*.1) + distance*.1) + passing*.1) + shooting*.05) + positioning*.2) + defending*.3) + ballControll*.1); } else if(position.equals("CM")) { overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.05) + acceleration*.05) + distance*.15) + passing*.2) + shooting*.1) + positioning*.2) + defending*.1) + ballControll*.1) + 10; } else if(position.equals("LM") || position.equals("RM")) { overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.2) + acceleration*.2) + distance*.1) + passing*.1) + shooting*.133) + positioning*.1) + defending*.033) + ballControll*.133) + 5; } else if(position.equals("ST")) { int stength = Integer.parseInt(stats[10]); overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.133) + acceleration*.133) + distance*.033) + passing*.05) + shooting*.225) + positioning*.225) + defending*.0) + ballControll*.1) + stength*.1) + 5; } setOverall(position, overall); } } public static void setOverall(String position, int overall) throws IOException { try (FileWriter fw = new FileWriter(overallFile, true)) { fw.append(position + "-" + overall +"\n"); } } public static void eraseOverallFile() throws IOException { FileWriter fw = new FileWriter(overallFile); fw.write(""); fw.close(); } } The files I am getting for are just regular files. They look like this: Lukas Hradecky-GK-63-81-81-74-89-82 Jetro Willems-LB-83-86-80-79-76-72-76-81 David Abraham-CB-76-83-68-74-70-76-80-61 Simon Falette-CB-60-71-77-57-50-74-84-56 Timmy Chandler-RB-80-76-83-74-68-71-77-74 Marco Fabian-CM-70-76-75-78-80-77-36-85 Jonathan De Guzman-CM-78-79-70-78-80-78-51-83 Mijat Gacinovic-RM-78-78-74-70-68-69-61-81 Ante Rebic-LM-76-79-71-62-78-72-40-75 Sebastien Haller-ST-75-79-73-64-77-77-35-79-91 Kevin Prince Boateng-ST-74-74-67-79-82-78-70-83-83 You can name this file whatever you like. Make another file in the appropriate location and it will generate everything else needed. Thank you for your help!
I think you missed the minimal in [mcve]. TL;DR ... but spotted: int firstDefense = firstPositionAmount[0] + firstPositionAmount[1]/2; int secondDefense = secondPositionAmount[0] + secondPositionAmount[1]/2; int firstAttack = firstPositionAmount[2] + firstPositionAmount[1]/2; int secondAttack = secondPositionAmount[2] + secondPositionAmount[2]/2; Indices are: 0 1 0 1 2 1 2 2 This seems inconsistent. Perhaps last should be a 1?
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.