Every time I try to run my file to display a graph it gets the majority of teh program done, up until to the GraphAtOrigin Class. This is where an error is thrown, saying the "IndexOutOfBoundsException: Index 0 out of bounds for length 0". So I believe there is something wrong with the wat I converted the domainList String ArrayList to the domainNumList Double ArrayListsome or a problem when I try to get the double array from the CreateGraphInterior Class. What do I need to do to prevent this exception and allow the code to run?
I have already tried casting the String ArrayList to a Double ArrayList with varies techniques, but if you have a better way let me know.
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class GraphProject {
public static JTextField depStart = new JTextField(10);
public static JTextField depEnd = new JTextField(10);
public static JTextField indStart = new JTextField(10);
public static JTextField indEnd = new JTextField(10);
public static JFrame main = new JFrame("Input The Graph Scale");
public static JButton submit = new JButton("Submit");
// for the input of Title, subtitle, and units
public static JFrame getInfo = new JFrame("Input The Graph Information");
public static JTextField gTitle = new JTextField(10);
public static JTextField gSubTitle = new JTextField(10);
public static JTextField depAxisUnit = new JTextField(10);
public static JTextField indAxisUnit = new JTextField(10);
public static JButton submitInfo = new JButton("Submit");
public static boolean selected = false;
public static boolean noSelected = false;
public static int dataLength;
public static double domainMax;
public static double rangeMax;
public static ArrayList<String> rangeList = new ArrayList<String>();
public static ArrayList<String> domainList = new ArrayList<String>();
public static void main(String[] args)throws Exception {
// Used to print out the data from the txt file
/*
ArrayList<String> result = new ArrayList<>();
FileReader fr = new FileReader("DataSetValues.txt");
int i;
while((i=fr.read()) != -1){
System.out.print((char)i);
}
*/
readData1();
readData2();
ObtainGraphInfo getGraphInfo = new ObtainGraphInfo();
getGraphInfo.graphInfo();
}
// Creates the Option Pane for user to input axis start and end positions
public static void axisPositions(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boolean yes = false;
boolean no = false;
JCheckBox startAtOrigin = new JCheckBox("Yes", yes);
startAtOrigin.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
selected = true;
makeGraph();
System.out.println("run the method to make the points graph at origin (0,0)");
main.dispose();
}
}
});
JCheckBox dontStartAtOrigin = new JCheckBox("No", no);
dontStartAtOrigin.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
noSelected = true;
makeGraph();
System.out.println("run the method to stop the points from graphing at the origin (0,0)");
main.dispose();
}
}
});
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
main.setContentPane(gui);
main.setLocationRelativeTo(null);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Do you want the points to begin graphing "));
controls.add(startAtOrigin);
labels.add(new JLabel(" with the origin (0,0)? "));
controls.add(dontStartAtOrigin);
/*labels.add(new JLabel("Independent Axis Start Position: "));
controls.add(indStart);
labels.add(new JLabel("Independent Axis End Position: "));
controls.add(indEnd);*/
// Codes for the action performed when the submit button is pressed
submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){
submit = (JButton)e.getSource();
main.dispose();
makeGraph();
}
});
gui.add(submit, BorderLayout.SOUTH);
main.getRootPane().setDefaultButton(submit);
main.pack();
submit.setVisible(false);
main.setVisible(true);
}
// Read the data from txt file and put it into an arrayList then separate into domain and range arrayLists
public static ArrayList<String> readData1() throws Exception{
ArrayList<String> dataList = new ArrayList<String>();
File file = new File("C://Users//wildc//Desktop//ToMac//Computer Science//Java Programs//GraphProjectFolder//testValues.txt");
Scanner scanData = new Scanner(file);
try{
while (scanData.hasNext()){
dataList.add(scanData.next());
}
int position = 0;
for (int counter = 0; counter < ((dataList.size()/2) + 1) ; counter ++ ) {
domainList.add(dataList.get(position));
position = (position + 2);
}
scanData.close();
//Creating domainList
} catch(Exception e) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran 1");
}
System.out.println(domainList.size() + " This is the Domain SIzeS");
System.out.println(domainList + "This is the domain List");
System.out.println(dataList + "This is the data list");
dataLength = domainList.size();
domainMax = Double.parseDouble(Collections.max(domainList));
System.out.println(domainMax + " : Domain max");
return domainList;
}
public static ArrayList<String> readData2() throws Exception{
ArrayList<String> dataList = new ArrayList<String>();
File file = new File("C://Users//wildc//Desktop//ToMac//Computer Science//Java Programs//GraphProjectFolder//testValues.txt");
Scanner scanData = new Scanner(file);
try{
while (scanData.hasNext()){
dataList.add(scanData.next());
}
scanData.close();
//Creating rangeList
int position = 1;
for (int counter = 0; counter < ((dataList.size()/2) + 1) ; counter ++ ) {
rangeList.add(dataList.get(position));
position = (position + 2);
}
// Was used to replace a certain element with another (incomplete)
}catch(Exception e) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran 2");
}
rangeMax = Double.parseDouble(Collections.max(rangeList));
System.out.println(rangeMax + " : Range max");
return rangeList;
}
//Displaying the frame for the graph to be on
public static void makeGraph(){
JFrame graph = new JFrame();
graph.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
graph.setSize(1000,1000);
graph.setTitle("Test Graph Scales");
graph.setLocationRelativeTo(null);
CreateGraphOutline graphFrame = new CreateGraphOutline();
CreateGraphInterior verticalLines = new CreateGraphInterior();
graph.add(graphFrame);
graph.setVisible(true);
graph.add(verticalLines);
graph.setVisible(true);
// TestFile testingAction = new TestFile();
//String[] testing = {"1","2","3"};
// testingAction.main(testing);
CreateGraphAttributes graphAttributes = new CreateGraphAttributes();
graph.add(graphAttributes);
GraphAtOrigin graphWithOriginStart = new GraphAtOrigin();
if (selected == true) {
graph.add(graphWithOriginStart);
graph.setVisible(true);
}
/*GraphNotAtOrigin graphNotWithOriginStart = new GraphAtOrigin();
if (noSelected == true) {
graph.add(graphNotWithOriginStart);
graph.setVisible(true);
}
makeGraph();
}*/
}}
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
import java.util.*;
public class CreateGraphAttributes extends JComponent{
public static String whereToStart;
public static String graphTitle;
public static String graphSubTitle;
public static String depUnit;
public static String indUnit;
public static String depTitle;
public static String indTitle;
public static FontMetrics metrics;
public void paintComponent(Graphics image) {
Graphics2D graph = (Graphics2D) image;
ObtainGraphInfo graphSpecifics = new ObtainGraphInfo();
ArrayList graphInformation = (ArrayList)graphSpecifics.setGraphAttributes();
graphTitle = graphInformation.get(0).toString();
graphSubTitle = graphInformation.get(1).toString();
depUnit = graphInformation.get(2).toString();
indUnit = graphInformation.get(3).toString();
depTitle = graphInformation.get(4).toString();
indTitle = graphInformation.get(5).toString();
// System.out.println(depAxisStartText + "," + indAxisStartText);
// title
Rectangle titleSpace = new Rectangle(200,50,600,200);
Font titleFont = new Font("Serif", Font.BOLD | Font.PLAIN, 22);
titleText(graph, graphTitle, titleSpace, titleFont);
// subtitle
Rectangle subTitleSpace = new Rectangle(200,100,600,150);
Font subTitleFont = new Font("Serif", Font.PLAIN, 14);
subTitleText(graph, graphSubTitle, subTitleSpace, subTitleFont);
// dependent axis 500, 700
Rectangle depTitleSpace = new Rectangle(200,600,550,150);
depAxisText(graph, depTitle, depUnit, depTitleSpace, subTitleFont);
// independent axis 10, 400
Rectangle indTitleSpace = new Rectangle(0,200,100,400);
indAxisText(graph, indTitle, indUnit, indTitleSpace, subTitleFont);
Point bottomLeftPoint = new Point(200,600);
Point bottomRightPoint = new Point(800,600); // 600px difference
Point leftBottomPoint = new Point(200,600);
Point leftTopPoint = new Point(200,200); // 400px difference
Point rightBottomPoint = new Point(800,600);
Point rightTopPoint = new Point(800,200);
Point topLeftPoint = new Point(200,200);
Point topRightPoint = new Point(800,200); // 600px difference
}
public void titleText(Graphics2D g, String text, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Draw the String
g.drawString(text, x, y);
}
public void subTitleText(Graphics2D g, String text, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Draw the String
g.drawString(text, x, y);
}
public void depAxisText(Graphics2D g, String text, String text2, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Create correct text structure
text = (text + " (" + text2 + ")");
// Draw the String
g.drawString(text, x, y);
}
public void indAxisText(Graphics2D g, String text, String text2, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Create correct text structure
text = (text + " (" + text2 + ")");
// Draw the String
g.drawString(text, x, y);
}
}
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
public class CreateGraphOutline extends JComponent{
public void paintComponent(Graphics image, boolean selected) {
Graphics2D graph = (Graphics2D) image;
Point bottomLeftPoint = new Point(200,600);
Point bottomRightPoint = new Point(800,600); // 600px difference
Line2D.Double depAxis = new Line2D.Double(bottomLeftPoint,bottomRightPoint);
BasicStroke lineThickness = new BasicStroke(4);
graph.setStroke(lineThickness);
graph.setColor(Color.BLACK);
graph.draw(depAxis);
Point leftBottomPoint = new Point(200,600);
Point leftTopPoint = new Point(200,200); // 400px difference
Line2D.Double indAxis = new Line2D.Double(leftBottomPoint,leftTopPoint);
graph.draw(indAxis);
Point rightBottomPoint = new Point(800,600);
Point rightTopPoint = new Point(800,200);
Line2D.Double rightIndAxis = new Line2D.Double(rightBottomPoint,rightTopPoint);
graph.draw(rightIndAxis);
Point topLeftPoint = new Point(200,200);
Point topRightPoint = new Point(800,200); // 600px difference
Line2D.Double topDepAxis = new Line2D.Double(topLeftPoint,topRightPoint);
graph.draw(topDepAxis);
}
}
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class ObtainGraphInfo {
public static JFrame getInfo = new JFrame("Input The Graph Information");
public static JTextField gTitle = new JTextField(10);
public static JTextField gSubTitle = new JTextField(10);
public static JTextField depAxisUnit = new JTextField(10);
public static JTextField indAxisUnit = new JTextField(10);
public static JTextField depAxisTitle = new JTextField(10);
public static JTextField indAxisTitle = new JTextField(10);
public static JButton submitInfo = new JButton("Submit");
public static GraphProject mainFile = new GraphProject();
public static ArrayList gAttributes;
public static void main(String[] args) {
}
// Prompt the user for the title, subtitle, and units of the Graph
public static void graphInfo(){
getInfo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
getInfo.setContentPane(gui);
getInfo.setLocationRelativeTo(null);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Graph Title: "));
controls.add(gTitle);
labels.add(new JLabel("Graph Sub-Title: "));
controls.add(gSubTitle);
labels.add(new JLabel("Dependent Axis Unit: "));
controls.add(depAxisUnit);
labels.add(new JLabel("Independent Axis Unit: "));
controls.add(indAxisUnit);
labels.add(new JLabel("Dependent Axis Title: "));
controls.add(depAxisTitle);
labels.add(new JLabel("Independent Axis Title: "));
controls.add(indAxisTitle);
// Codes for the action performed when the submit button is pressed
submitInfo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){
submitInfo = (JButton)e.getSource();
if (gTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (gSubTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
if (depAxisUnit.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
if (indAxisUnit.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (depAxisTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (indAxisTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
String graphTitle = gTitle.getText();
String graphSubTitle = gSubTitle.getText();
String dependentAxisUnit = depAxisUnit.getText();
String independentAxisUnit = indAxisUnit.getText();
String dependentAxisTitle = depAxisTitle.getText();
String independentAxisTitle = indAxisTitle.getText();
ArrayList graphAttributes = new ArrayList<String>();
graphAttributes.add(graphTitle);
graphAttributes.add(graphSubTitle);
graphAttributes.add(dependentAxisUnit);
graphAttributes.add(independentAxisUnit);
graphAttributes.add(dependentAxisTitle);
graphAttributes.add(independentAxisTitle);
getInfo.dispose();
makeGraphAttributes(graphAttributes);
mainFile.axisPositions();
}
}
}
}
}
}}});
gui.add(submitInfo, BorderLayout.SOUTH);
getInfo.getRootPane().setDefaultButton(submitInfo);
getInfo.pack();
getInfo.setVisible(true);
}
public static void makeGraphAttributes(ArrayList<String> graphAttributes){
gAttributes = (ArrayList) graphAttributes.clone();
System.out.println(gAttributes);
setGraphAttributes();
}
public static ArrayList<String> setGraphAttributes(){
return gAttributes;
}
}
// This is the Text File Used
0.281 0.0487
0.396 0.727
0.522 0.974
0.639 0.121
0.774 0.145
// This class creates the Double ArrayList
public class CreateGraphInterior extends JComponent{
public static ArrayList<Double> domainNumList = new ArrayList<Double>();
public static ArrayList<Double> rangeNumList = new ArrayList<Double>();
public static ArrayList<String> domainList = new ArrayList<String>();
public static ArrayList<String> rangeList = new ArrayList<String>();
public static GraphProject main = new GraphProject(); // this is where the original domainList and rangeList are found
public static int dataSize;
public static double domMax;
public static double ranMax;
public void paintComponent(Graphics image) {
main.dataLength = dataSize;
main.domainMax = domMax;
main.rangeMax = ranMax;
makeLists();
Graphics2D graph = (Graphics2D) image;
int domAxisPos = 200;
for (int counter = 0; counter < 9; counter++ ) {
Point topPoint = new Point(domAxisPos,200);
Point bottomPoint = new Point(domAxisPos,620);
Line2D.Double verticalLines = new Line2D.Double(bottomPoint,topPoint);
BasicStroke lineThickness = new BasicStroke(2);
graph.setStroke(lineThickness);
graph.setColor(Color.BLACK);
graph.draw(verticalLines);
domAxisPos = domAxisPos + 75;
}
int ranAxisPos = 600;
for (int counter = 0; counter < 9; counter++ ) {
Point leftPoint = new Point(180,ranAxisPos);
Point rightPoint = new Point(800,ranAxisPos);
Line2D.Double horizontalLines = new Line2D.Double(leftPoint,rightPoint);
BasicStroke lineThickness = new BasicStroke(2);
graph.setStroke(lineThickness);
graph.setColor(Color.GRAY);
graph.draw(horizontalLines);
ranAxisPos = ranAxisPos - 50;
}
if (main.selected == true) {
GraphAtOrigin graphWithOrigin = new GraphAtOrigin();
}
if (main.noSelected == true) {
System.out.println("Its false");
ranAxisPos = 600;
double domLabel = 0;
for (int counter = 0; counter < 9; counter++ ) {
graph.drawString(Double.toString(domLabel), domAxisPos, 650);
domLabel = domLabel + 2.0;
domAxisPos = domAxisPos - 50;
}
}
}
public static void makeLists(){
try{
domainList = main.readData1();
System.out.println(domainList + " This is domain list");
rangeList = main.readData2();
System.out.println(rangeList + " This is range list");
int count = 0;
for (int counter = 0; counter < (main.dataLength + 1) ; counter++) {
try {
//Convert String to Double, and store it into Double array list.
String domNumber = domainList.get(count);
double domNumber2 = Double.parseDouble(domNumber);
String ranNumber = rangeList.get(count);
double ranNumber2 = Double.parseDouble(ranNumber);
domainNumList.add(domNumber2);
rangeNumList.add(ranNumber2);
count = count + 1;
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran");
}
}}catch(Exception e){
System.out.println("Error arose");
}
}
}
// This is where I try to use the Double ArrayList
public class GraphAtOrigin extends JComponent{
public static GraphProject main = new GraphProject();
public static CreateGraphInterior graphInterior = new CreateGraphInterior();
// make regular unit into pixel unit
public static double oneDomPX = (domMax / 600);
public static double oneRanPX = (ranMax / 400);
public static ArrayList<Double> domainNumList = new ArrayList<Double>();;
public static ArrayList<Double> rangeNumList = new ArrayList<Double>();;
public static void plotPoints(){
domainNumList = graphInterior.domainNumList; // error occurs here
rangeNumList = graphInterior.rangeNumList;
int domPointPos = 0;
int ranPointPos = 0;
for (int counter = 0; counter < (main.dataLength + 1); counter++) {
// X data point
double domNum = domainNumList.get(domPointPos);
//A what to add to 200
double domAdd = domNum / oneDomPX;
// newX make the point relavent to the graphs location
double domPoint = domAdd + 200;
// make domPoint integer to be used on point method
int newDomPoint = (int)domPoint;
// subtract half the thickness of point to make it graph at the points center
newDomPoint = newDomPoint - 3;
// X data point
double ranNum = graphInterior.rangeNumList.get(ranPointPos);
//A what to add to 200
double ranAdd = ranNum / oneRanPX;
// newX make the point relavent to the graphs location
double ranPoint = 600 - ranAdd;
// make domPoint integer to be used on point method
int newRanPoint = (int)ranPoint;
// subtract half the thickness of point to make it graph at the points center
newRanPoint = newRanPoint - 3;
graph.fillOval(newDomPoint,newRanPoint,6,6);
domPointPos++;
ranPointPos++;
}
}
}
The output should then allow the for loops to execute and draw data points, but the exception is thrown and the program doesn't complete.
I suspect the problem is at:
for (int counter = 0; counter < (main.dataLength + 1) ; counter++) {
If the dataLength is 0 then this will run once and perform a get(0) which will throw the exception you have shown.
However if all you want to do is to convert a list of strings to a list of doubles, then you could use:
domainList.stream().map(Double::valueOf).collect(Collectors.toList());
If you wish to quietly skip invalid strings then there is a long explanation of the regexp to use in the javadoc for Double. A simple version might be:
Pattern doublePattern = Pattern.compile("\\d+(\\.\\d+)?");
List<Double> result = domainList.stream()
.filter(doublePattern::matches).map(Double::valueOf)
.collect(Collectors.toList());
I am trying to create a java applet that uses text fields to add strings to a linked list. I can not get the search button to work. I am trying to get the string specified by the user in the text field and then search the list and print how many times the word has been found if any.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
import java.util.ListIterator;
/**
* Created by joshuaogunnote on 31/10/2015.
*/
public class Applet2 extends JApplet {
private String text;
private int text1;
JTextField value1, value2;
LinkedList<String> list = new LinkedList<String>();
public JLabel jLabel;
public int count = 0;
I have created this search_count variable to count up how many times the word has been found.
public int search_count = 0;
public void init() {
JLabel prompt = new JLabel("Please enter a word");
JLabel prompt1 = new JLabel("Please enter a certain letter");
value1 = new JTextField(10);
value2 = new JTextField(10);
JPanel textPanel = new JPanel();
textPanel.add(prompt);
textPanel.add(value1);
add(textPanel, BorderLayout.NORTH);
textPanel.add(prompt1);
textPanel.add(value2);
JPanel centrePanel = new JPanel();
text = "";
jLabel = new JLabel(text);
centrePanel.add(jLabel);
add(centrePanel, BorderLayout.CENTER);
JButton but = new JButton("Add word");
JButton but1 = new JButton("Clear");
JButton but2 = new JButton("Remove first occurrence");
JButton but3 = new JButton("Remove all occurrences");
JButton but4 = new JButton("Display all words begging with certain letter");
JButton but5 = new JButton("Search");
JPanel butPanel = new JPanel();
butPanel.add(but);
butPanel.add(but1);
butPanel.add(but5);
butPanel.add(but2);
butPanel.add(but3);
butPanel.add(but4);
add(butPanel, BorderLayout.SOUTH);
but.addActionListener(new ButtonHandler(this));
but1.addActionListener(new ButtonHandler1(this));
but5.addActionListener(new ButtonHandler2(this));
}
class ButtonHandler implements ActionListener {
private Applet2 theApplet;
public ButtonHandler(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
text = theApplet.value1.getText();
try {
text1 = Integer.parseInt(text);
jLabel.setText("ERROR - The string " + "'" + text1 + "'" + " is not a valid word");
} catch (NumberFormatException e1) {
if (text.length() != 0) {
jLabel.setText("Word " + "'" + text + "'" + " has been added to the list");
count = count + 1;
} else {
jLabel.setText("ERROR - Please enter a word");
}
}
}
}
class ButtonHandler1 implements ActionListener {
private Applet2 theApplet;
public ButtonHandler1(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
list.clear();
jLabel.setText("List has been cleared");
count = 0;
}
}
class ButtonHandler2 implements ActionListener {
private Applet2 theApplet;
public ButtonHandler2(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
String text = theApplet.value1.getText();
Here I am trying to use a for loop to iterate through all the strings in the list and increment search_count if a match has been found. It does not however produce the correct answer. I am also trying to produce an ERROR message when the user tries to search for a word that is not in the list. How do I get the search_count variable and how do I get the ERROR message to show at the correct time?
for (int i = 0; i < list.size(); i++) {
if(text.equals(list.get(i))){
search_count = search_count + 1;
} else {
jLabel.setText("ERROR - word is not in the list")
}
jLabel.setText("Word " + "'" + text + "'" + " was found " + search_count + " time(s) in the list");
if (text.length() == 0) {
jLabel.setText("Please enter a word - The total number of words in the list are: " + count);
}
}
}
}
It seems you did not declare count as a variable before you used it in the loop. If the output is not what you want / expect, the condition of the loop gives you something else then what you think it does.
int count = 0;
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.
I've been having problems running this program it compiles but doesn't run properly. When I run it and attempt to perform the calculations it spits out a bunch errors. I think it has to with variable types. Here is the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class area extends JFrame implements ActionListener, ItemListener{
//row 1
JPanel row1 = new JPanel();
JLabel select = new JLabel("Please select what you would like to caculate the area and volume of.");
//row 2
JPanel row2 = new JPanel();
JCheckBox circle = new JCheckBox("Circle", false);
JCheckBox cube = new JCheckBox("Cube", false);
//row 3
JPanel row3 = new JPanel();
JLabel radlab = new JLabel("Radius of the circle (in cm)");
JTextField rad = new JTextField(3);
JLabel sidelab = new JLabel("A side of the cube (in cm)");
JTextField side = new JTextField(3);
//row4
JPanel row4 = new JPanel();
JButton solve = new JButton("Solve!");
//row 5
JPanel row5 = new JPanel();
JLabel areacallab = new JLabel("Area");
JTextField areacal = new JTextField(10);
JLabel volumelab = new JLabel("Volume");
JTextField volume = new JTextField(10);
public area(){
setTitle("Area Caculator");
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//disables all text areas
rad.setEnabled(false);
side.setEnabled(false);
areacal.setEnabled(false);
volume.setEnabled(false);
//add listeners
circle.addItemListener(this);
cube.addItemListener(this);
solve.addActionListener(this);
FlowLayout one = new FlowLayout(FlowLayout.CENTER);
setLayout(one);
row1.add(select);
add(row1);
row2.add(circle);
row2.add(cube);
add(row2);
row3.add(radlab);
row3.add(rad);
row3.add(sidelab);
row3.add(side);
add(row3);
row4.add(solve);
add(row4);
row5.add(areacallab);
row5.add(areacal);
row5.add(volumelab);
row5.add(volume);
add(row5);
}
public void circlepick(){
//cube.setCurrent(false);
cube.setEnabled(false);
rad.setEnabled(true);
}
public void cubepick(){
circle.setEnabled(false);
side.setEnabled(true);
}
#Override
public void itemStateChanged(ItemEvent event) {
Object item = event.getItem();
if (item == circle){
circlepick();
}
else if (item == cube){
cubepick();
}
}
#Override
public void actionPerformed(ActionEvent evt){
//String radi = rad.getText();
//String sid = side.getText();
//circlesolve();
//cubesolve();
String radi = rad.getText();
String sid = side.getText();
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
double cirarea = Math.PI * Math.pow(radius, 2);
double cirvolume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
double cubearea = Math.pow(length, 2);
double cubevolume = Math.pow(length, 3);
areacal.setText("" + cirarea + cubearea + "");
volume.setText("" + cirvolume + cubevolume + "");
}
public static void main(String[] args) {
area are = new area();
}
}
Here are the errors is printing out when attempting to perform the math (sorry it really long).
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1038)
at java.lang.Double.parseDouble(Double.java:548)
at area.actionPerformed(area.java:112)
...
Thanks so much in advance for an help!
When calling the functions:
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
either radi or sid is am Empty String, thats what
java.lang.NumberFormatException: empty String
tells you.
You might consider adding a System.out.println(raid + ", " + sid) before parsing to check what values are empty Strings and make sure, that the Strings are not empty.
Double.parseDouble(String s) throws a NumberFormatException when the given String s can not be parsed into a double value.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I populate jcombobox from a textfile?
OK, I have an issue here that I cannot quiet figure out. I have a file that has variables on each line of: 5.35, 5.5, 5.75 in a file called apr.txt. I am reading the file and need to populate the file into a JComboBox. So far I have the file being read fine but cannot figure how to populate it into the JComboBox. This must be something easy. Can someone help point me in the proper direction?
Thank you for your help in advance.
import java.awt.*;
import java.text.NumberFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.JComboBox;
public class MortgageCalculatorGUI9 extends JFrame implements ActionListener
{
// Declarations
//double [] Interest = {5.35, 5.5, 5.75};
int [] Length = {7, 15, 30};
double [] file_data = new double[3];
JLabel mortgagelabel = new JLabel( "Principal Amount:$ " );
JLabel paymentLabel = new JLabel( "Monthly Payment: " );
JLabel intRateLabel = new JLabel( "Interest Rate %: " );
JLabel termLabel = new JLabel( "Length of Loan of Loan in Years: " );
JTextField mortgagePrincipal = new JTextField(7);
JTextField Payment = new JTextField(7);
//JTextField intRateText = new JTextField(3);
JComboBox intRateBox = new JComboBox();
JTextField termText = new JTextField(3);
JButton b7_535 = new JButton( "7 years at 5.35%" );
JButton b15_55 = new JButton( "15 years at 5.50%" );
JButton b30_575 = new JButton( "30 years at 5.75%");
JButton exitButton = new JButton( "Exit" );
JButton clearButton = new JButton( "Clear All" );
JButton calculateButton = new JButton( "Calculate Loan" );
JTextArea LoanPayments = new JTextArea(20,50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public MortgageCalculatorGUI9()
{
//GUI setup
super("Mortgage Calculator 1.0.5");
setSize(800, 400);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(3,1)); Container grid = getContentPane();
grid.setLayout(new GridLayout(4,0,4,4)); pane.add(grid);
pane.add(scroll);
grid.add(mortgagelabel);
grid.add(mortgagePrincipal);
grid.add(intRateLabel);
//grid.add(intRateText);
grid.add (intRateBox);
grid.add(termLabel);
grid.add(termText);
grid.add(paymentLabel);
grid.add(Payment);
grid.add(b7_535);
grid.add(b15_55);
grid.add(b30_575);
grid.add(calculateButton);
grid.add(clearButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
//add GUI functionality
calculateButton.addActionListener (this);
exitButton.addActionListener(this);
clearButton.addActionListener(this);
b7_535.addActionListener(this);
b15_55.addActionListener(this);
b30_575.addActionListener(this);
mortgagePrincipal.addActionListener(this);
//intRateText.addActionListener(this);
intRateBox.addActionListener (this);
termText.addActionListener(this);
Payment.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object command = e.getSource();
if (command == exitButton)
{
System.exit(0);
}
else if (command == b7_535)
{
calcLoan(Length[0], file_data[0]);
}
else if (command == b15_55)
{
calcLoan(Length[1], file_data[1]);
}
else if (command == b30_575)
{
calcLoan(Length[2], file_data[2]);
}
else if (command == calculateButton )
{
double terms = 0;
double rates = 0;
try
{
terms = Double.parseDouble(termText.getText());
//rates = Double.parseDouble(intRateText.getText());
read_File ();
}
catch (Exception ex)
{
LoanPayments.setText("Invalid term or rate Amount");
return;
}
calcLoan(terms, rates);
}
else if (command == clearButton)
{
mortgagePrincipal.setText("");
Payment.setText("");
//intRateText.setText("");
termText.setText("");
LoanPayments.setText("");
}
}
//Input File
public void read_File()
{
File inFile = new File("apr.txt");
try
{
BufferedReader istream = new BufferedReader(new FileReader(inFile));
for(int x=0;x<6;x++)
{
file_data[x]=Double.parseDouble (istream.readLine());
}
}
catch (Exception ex)
{
LoanPayments.setText ("Could Not Read From File.");
return;
}
}
//this is what needs to be done
private void calcLoan(double terms, double rates)
{
termText.setText(String.valueOf(terms) );
//intRateText.setText(String.valueOf(rates));
double amount = 0;
try
{
amount = Double.parseDouble(mortgagePrincipal.getText());
}
catch (Exception ex)
{
LoanPayments.setText("Invalid mortgage Amount");
return;
}
double interestRate = rates;
// Calculations
double intRate = (interestRate / 100) / 12;
int Months = (int)terms * 12;
double rate = (intRate / 12);
double payment = amount * intRate / (1 - (Math.pow(1/(1 + intRate), Months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
double[] balanceArray = new double[Months];
double[] interestArray = new double[Months];
double[] monthArray = new double[Months];
NumberFormat Money = NumberFormat.getCurrencyInstance();
Payment.setText(Money.format(payment));
LoanPayments.setText("Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while(currentMonth < Months)
{
//create loop calculations
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t" + Money.format(MonthlyAmt) + "\t" + Money.format(MonthlyInterest) + "\t" + Money.format(remainingPrincipal) + "\n");
balanceArray[currentMonth] = MonthlyAmt;
interestArray[currentMonth] = MonthlyInterest;
monthArray[currentMonth] = currentMonth;
}
}
public static void main(String[] args)
{
MortgageCalculatorGUI9 frame= new MortgageCalculatorGUI9();
}
}
Have you looked at the JComboBox API for a suitable method? If you start there, you'll likely get the right answer faster than asking in StackOverflow (hint it starts with "add... and ends with ...Item") ;)