Populate JComboBox from Text file java - java

This is my code for populating JcomboBox.
I try to select a text file from JFileChooser, then read and put into an array list and put it in the combo box. But my problem is, even i put it in the array list and show it(system.out.println(list)), but still can't populate to the combobox. What can i do for that?
public class Read2 extends JFrame implements ActionListener{
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 500;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JComboBox cb;
private JButton b;
private JPanel J;
int len = 0;
int room = 1;
int line = 1;
int north = 0;
int east = 0;
int west = 0;
int south = 0;
int up = 0;
int down = 0;
//String s="";
String s2="";
Room newRoom;
HashMap<Integer,Room> Map = new HashMap<Integer,Room>();
public Read2(){
Container contentPane;
//set the frame properties
setTitle ("Creat your own map");
setSize (FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setLayout(new BorderLayout());
J= new JPanel();
J.setLayout(new BorderLayout());
cb = new JComboBox();
b = new JButton ("insert");
b.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
//String fileName="";//ask hillary for import
JFileChooser fc = new JFileChooser();
int r = fc.showOpenDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
File filename = fc.getSelectedFile();
//File directory = fc.getCurrentDirectory();
FileInputStream inputfile = null;
try {
inputfile = new FileInputStream(filename);
FileReader in = new FileReader(filename.getAbsoluteFile());
BufferedReader br=new BufferedReader(in);
String s1 ="";
String s= "";
while ((s1=br.readLine())!=null){
switch(line % 8){
case 1:
s = s1;
break;
case 2:
s2 = s1;
break;
case 3:
north = Integer.parseInt(s1);
break;
case 4:
east = Integer.parseInt(s1);
break;
case 5:
south = Integer.parseInt(s1);
break;
case 6:
west = Integer.parseInt(s1);
break;
case 7:
up = Integer.parseInt(s1);
break;
case 0:
down = Integer.parseInt(s1);
newRoom = new Room(s,s2, north, east, south, west, up, down);
Map.put(room, newRoom);
room++;
break;
}
line++;
//System.out.println(s1);
}
List<String> list = new ArrayList<String>();
//System.out.println(list);
if(list !=null){
//list = new ArrayList<String>();
//list = new ArrayList<String>();
for(int i = 1; i <=Map.size(); i++){
String d = Map.get(i).getImg();
list.add(d);
}
cb= new JComboBox(list.toArray());
//find out the problem for this and it will be solved
System.out.println(list);
inputfile.close();
}
}catch( IOException e){}
System.out.println("Could not find file");
}
}});
J.add(b, BorderLayout.NORTH);
J.add(cb,BorderLayout.CENTER);
contentPane.add(J,BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Read2 r = new Read2();
r.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}

You're creating a new JComboBox with the file results, but the UI still contains the old one. Just remove the old one and add the new one.

Related

How to change String ArrayList into a Double ArrayList?

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());

Can I set array in class from inside action listener? JAVA

Basically all I need to do is get array1 and array2 from each of my buttonlisteners and I have no clue how to do this as it is.. Right now the TextMatch button doesn't work because array1 and array2 are empty, is there a way to set them from the buttonlistener classes?
All I need is a way to set array1 and array2 as ss and sstwo so I can implement my TextTools.match() method
MAIN PROGRAM:
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab11 extends JPanel
{
private SuperString [] array1, array2;
private StringBuilder string, string2, string3, string4; //loads SuperStrings faster by appending all at once
private JRadioButton occurrence, alphabetical;
private JPanel text;
private JComboBox<Integer> input;
private JLabel label, file1,file2, unique, unique2,textmatch;
private JButton load, go,go2, TextMatch;
private CountLinkedList<SuperString> words, words3; //Change impliments CountList to extends BinaryCountTree
private OrderedLinkedList<SuperString> words2, words4;//Change impliments CountList to extends BinaryCountTree
private String filename,filename2;
private int width = 450;
private int height = 550;
private TextArea textarea,textarea2;
Scanner scan;
public Lab11()
{
TextListener textlistener = new TextListener();
ButtonListener listener = new ButtonListener();
Button2Listener listener2 = new Button2Listener();
Integer [] select = {1,2,3,4};
input = new JComboBox<Integer>(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File 1: ");
go2 = new JButton("Select Text File 2: ");
TextMatch = new JButton("TextMatch");
textmatch = new JLabel("");
label = new JLabel("N: " );
unique = new JLabel("");
unique2 = new JLabel("");
file1 = new JLabel("");
file1.setFont(new Font("Helvetica",Font.PLAIN,24));
unique.setFont(new Font("Helvetica",Font.PLAIN,24));
file2 = new JLabel("");
file2.setFont(new Font("Helvetica",Font.PLAIN,24));
unique2.setFont(new Font("Helvetica",Font.PLAIN,24));
occurrence= new JRadioButton("Occurrence");
occurrence.setMnemonic(KeyEvent.VK_O);
occurrence.addActionListener(listener);
occurrence.addActionListener(listener2);
occurrence.setSelected(true);
alphabetical = new JRadioButton("Alphabetical");
alphabetical.setMnemonic(KeyEvent.VK_A);
alphabetical.addActionListener(listener);
alphabetical.addActionListener(listener2);
ButtonGroup group = new ButtonGroup();
group.add(occurrence);
group.add(alphabetical);
go.addActionListener(listener);
go2.addActionListener(listener2);
input.addActionListener(listener);
input.addActionListener(listener2);
TextMatch.addActionListener(textlistener);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(1000,700));
text.add(textarea);
text.add(textarea2);
add(occurrence);
add(alphabetical);
add(label);
add(input);
add(go);
add(file1);
add(unique);
add(go2);
add(file2);
add(unique2);
add(TextMatch);
add(textmatch);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
string = new StringBuilder();
string2 = new StringBuilder();
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text1= file.getName();
file1.setText(text1);
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
words2 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words.add(ss );
words2.add(ss2 );
}
}
SuperString[] array1 = new SuperString[words.size()];
SuperString[] ss = new SuperString[words.size()];
SuperString[] ss2 = new SuperString[words2.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word: words)
{
ss[i] = word;
array1[i] = word;
i++;
}
int j=0;
for(SuperString word: words2)
{
ss2[j] = word;
j++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
count++;
string.append(Integer.toString(count)+ " "+ word+ "\n");
}
if(occurrence.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string.toString());
string.replace(0,string.length()*2, "");
}
for(SuperString word : ss2)
{
count2++;
string2.append(Integer.toString(count2)+ " "+ word.toString()+ "\n");
}
if(alphabetical.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string2.toString());
string2.replace(0,string2.length()*2, "");
}
unique.setText("Unique Count: "+ Integer.toString(words.size()));
}
}
public class Button2Listener implements ActionListener
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
string3 = new StringBuilder();
string4 = new StringBuilder();
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text2= file.getName();
file2.setText(text2);
filename2 = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words3 = new CountLinkedList<SuperString>();
words4 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words3.add(ss );
words4.add(ss2 );
}
textarea2.setText("");
}
SuperString[] array2 = new SuperString[words3.size()];
SuperString[] sstwo = new SuperString[words3.size()];
SuperString[] ss2two = new SuperString[words4.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word2: words3)
{
sstwo[i] = word2;
array2[i] = word2;
i++;
}
int j=0;
for(SuperString word2: words4)
{
ss2two[j] = word2;
j++;
}
Arrays.sort(sstwo, new SuperStringCountOrder());
for(SuperString word2 : sstwo)
{
count++;
string3.append(Integer.toString(count)+ " "+ word2+ "\n");
}
if(occurrence.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string3.toString());
}
for(SuperString word2 : ss2two)
{
count2++;
string4.append(count2+" "+ " "+word2+"\n");
}
if(alphabetical.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string4.toString());
}
unique2.setText("Unique Count: "+ Integer.toString(words3.size()));
}
}
public class TextListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() ==TextMatch)
{
textmatch.setText("The match is: "+ TextTools.match(array1,array2));
}
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 11");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Lab11());
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
TEXT MATCH PROGRAM:
import java.util.Arrays;
public class TextTools
{
public static double match(SuperString[] X, SuperString[] Y)
{
double length1 = 0, length2 = 0;
Arrays.sort(X);
Arrays.sort(Y);
for(SuperString token : X)
{
double value = token.count();
length1 += value*value;
}
length1 = Math.sqrt(length1);
for(SuperString token : Y)
{
double value = token.count();
length2 += value*value;
}
length2 = Math.sqrt(length2);
double total = 0;
int j=0;
for(int i=0;i<X.length;i++)
{
while(j < Y.length && X[i].compareTo(Y[j])>0 )
j++;
if(j == Y.length)
return total/(length1*length2);
if(X[i].compareTo(Y[j]) == 0)
total += X[i].count()*Y[j].count();
}
return total/(length1*length2);
}
}
Turns out I'm erasing over my array1 and array2 by re declaring SuperString in the actionlistener

How do I make my code find out which button was pressed within a reasonable amount of time?

Alright, this one is a bit of a doozy, its about 240 lines long, but on to my point. The point is that it doesn't work. I'm pretty new to coding in general and some help would be really appreciated. I know where the problem is, it's in the last bits of it in the for loops, I went under the false presumption that if you click a JButton, it is then selected. How do I implement the .setSelected method to my program without rewriting the entire code? This code is a make-shift jeopardy of sorts btw.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import sun.audio.*;
import java.io.*;
public class Jeopardy implements ActionListener
{
public static JFrame frame = new JFrame("Jeopardy!");
public static JButton[] row1Buttons = new JButton[6];
public static JButton[] row2Buttons = new JButton[6];
public static JButton[] row3Buttons = new JButton[6];
public static JButton[] row4Buttons = new JButton[6];
public static JButton[] row5Buttons = new JButton[6];
//Creates 5 arrays, each with 6 JButtons in each (otherwise mass confusion
//is going to ensue because I would have to individually add 30 JButtons to the pane,
//all of which I would have to remember what they contain.)
public static JPanel pane = new JPanel();
public static JLabel[] labels = new JLabel[6];
//Creates an array of 6 JLabels
public static void main(String[] args)
{
frame.setSize(800, 600);
frame.setVisible(true);
frame.toFront();
frame.setContentPane(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("ComicSans", Font.PLAIN, 20);
Color colour = new Color(0, 0, 240);
for(int a = 0; a < row1Buttons.length; a++)
{
row1Buttons[a] = new JButton("$200");
row2Buttons[a] = new JButton("$400");
row3Buttons[a] = new JButton("$600");
row4Buttons[a] = new JButton("$800");
row5Buttons[a] = new JButton("$1000");
//Gives text to all 30 JButtons
row1Buttons[a].addActionListener(new Jeopardy());
row2Buttons[a].addActionListener(new Jeopardy());
row3Buttons[a].addActionListener(new Jeopardy());
row4Buttons[a].addActionListener(new Jeopardy());
row5Buttons[a].addActionListener(new Jeopardy());
//adds action listener to all 30
row1Buttons[a].setBackground(colour);
row2Buttons[a].setBackground(colour);
row3Buttons[a].setBackground(colour);
row4Buttons[a].setBackground(colour);
row5Buttons[a].setBackground(colour);
//sets background colour
row1Buttons[a].setForeground(Color.yellow);
row2Buttons[a].setForeground(Color.yellow);
row3Buttons[a].setForeground(Color.yellow);
row4Buttons[a].setForeground(Color.yellow);
row5Buttons[a].setForeground(Color.yellow);
}
labels[0] = new JLabel("Mathematics");
labels[1] = new JLabel("Computer Science");
labels[2] = new JLabel("Historical Events");
labels[3] = new JLabel("Chemistry");
labels[4] = new JLabel("TBD");
labels[5] = new JLabel("TBD");
for(int k = 0; k < labels.length; k++)
{
labels[k].setForeground(Color.yellow);
}
pane.setLayout(new GridLayout(6, 6, 6, 6));
for(int b = 0; b < labels.length; b++)
{
pane.add(labels[b]);
pane.add(row1Buttons[b]);
pane.add(row2Buttons[b]);
pane.add(row3Buttons[b]);
pane.add(row4Buttons[b]);
pane.add(row5Buttons[b]);
}
pane.setBackground(Color.blue);
}
public void actionPerformed(ActionEvent event)
{
String[] answerRow1 = new String[6];
String[] answerRow2 = new String[6];
String[] answerRow3 = new String[6];
String[] answerRow4 = new String[6];
String[] answerRow5 = new String[6];
String[] questionsRow1 = new String[6];
//Write $200 questions
questionsRow1[0] = "Question";
questionsRow1[1] = "Question";
questionsRow1[2] = "Question";
questionsRow1[3] = "Question";
questionsRow1[4] = "Question";
questionsRow1[5] = "Question";
String[] questionsRow2 = new String[6];
//Write $400 questions
questionsRow2[0] = "Question";
questionsRow2[1] = "Question";
questionsRow2[2] = "Question";
questionsRow2[3] = "Question";
questionsRow2[4] = "Question";
questionsRow2[5] = "Question";
String[] questionsRow3 = new String[6];
//Write $600 questions
questionsRow3[0] = ("The function y=3(2)^x will have this for a y value when x = 3.");
questionsRow3[1] = "Question";
questionsRow3[2] = "Question";
questionsRow3[3] = "Question";
questionsRow3[4] = "Question";
questionsRow3[5] = "Question";
String[] questionsRow4 = new String[6];
//Write $800 questions
questionsRow4[0] = "Question";
questionsRow4[1] = "Question";
questionsRow4[2] = "Question";
questionsRow4[3] = "Question";
questionsRow4[4] = "Question";
questionsRow4[5] = "Question";
String[] questionsRow5 = new String[6];
//Write $1000 questions
questionsRow5[0] = "Question";
questionsRow5[1] = "Question";
questionsRow5[2] = "Question";
questionsRow5[3] = "Question";
questionsRow5[4] = "Question";
questionsRow5[5] = "Question";
for(int j = 0; j < questionsRow1.length; j++)
{
if(row1Buttons[j].getModel().isPressed())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
answerRow1[j] = JOptionPane.showInputDialog(null, questionsRow1[j]);
}
}
for(int a = 0; a < questionsRow2.length; a++)
{
if(row2Buttons[a].isSelected())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
JOptionPane.showInputDialog(null, questionsRow2[a]);
}
}
for(int r = 0; r < questionsRow3.length; r++)
{
if(row3Buttons[r].isSelected())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
JOptionPane.showInputDialog(null, questionsRow3[r]);
}
}
for(int e = 0; e < questionsRow4.length; e++)
{
if(row4Buttons[e].isSelected())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception exception)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
JOptionPane.showInputDialog(null, questionsRow4[e]);
}
}
for(int d = 0; d < questionsRow5.length; d++)
{
if(row5Buttons[d].isSelected())
{
try
{
InputStream in = new FileInputStream("sounds/x.wav");
AudioStream openSound = new AudioStream(in);
AudioPlayer.player.start(openSound);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "You don't have the sound clip for this");
}
JOptionPane.showInputDialog(null, questionsRow5[d]);
}
}
}
}
The problem is that you make the frame visible and then add your components. Instead, call setVisible() at the end of your constructor, after you pack() the frame.
public static void main(String[] args) {
...
pane.setBackground(Color.blue);
frame.pack();
frame.setVisible(true);
}
try to create a new class for buttons
public class Response_Button extends JButton {
public Response_Button(final JPanel container, final String name) {
this.setText(name);
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(container, "clicked " + name);
}
});
}
like this each button will respond through it's own method
This is what fixes it:
if(event.getSource()== row1Buttons[j])
Yes, that makes it so that it will do all of the category in one fell swoop, but it doesn't matter. Thanks for all who tried and gave positive and helpful answers.
EDIT: nope, it doesn't do it all in one go, I just labeled it wrong.

Getting Null Pointed exception error but runs fine? Java JComboBox (DropDown box)

So Integer N here is controlled by a JComboBox basically a drop down menu 1-4. My problem is that I get a nullpointerexception error when I initially set N from the box..any ideas how to fix this? I tested it by printing out what N was in both actionlistener instances and it's null in the first one and it's correct in the second one.
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab10 extends JPanel
{
private StringBuilder string, string2, string3, string4; //loads SuperStrings faster by appending all at once
private JRadioButton occurrence, alphabetical;
private JPanel text;
private JComboBox<Integer> input;
private JLabel label, file1,file2, unique, unique2;
private JButton load, go,go2;
private CountLinkedList<SuperString> words, words3; //Change impliments CountList to extends BinaryCountTree
private OrderedLinkedList<SuperString> words2, words4;//Change impliments CountList to extends BinaryCountTree
private String filename,filename2;
private int width = 450;
private int height = 550;
private TextArea textarea,textarea2;
Scanner scan;
public Lab10()
{
string = new StringBuilder();
string2 = new StringBuilder();
string3 = new StringBuilder();
string4 = new StringBuilder();
ButtonListener listener = new ButtonListener();
Button2Listener listener2 = new Button2Listener();
Integer [] select = {1,2,3,4};
input = new JComboBox<Integer>(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File 1: ");
go2 = new JButton("Select Text File 2: ");
label = new JLabel("N: " );
unique = new JLabel("");
unique2 = new JLabel("");
file1 = new JLabel("");
file1.setFont(new Font("Helvetica",Font.PLAIN,24));
unique.setFont(new Font("Helvetica",Font.PLAIN,24));
file2 = new JLabel("");
file2.setFont(new Font("Helvetica",Font.PLAIN,24));
unique2.setFont(new Font("Helvetica",Font.PLAIN,24));
occurrence= new JRadioButton("Occurrence");
occurrence.setMnemonic(KeyEvent.VK_O);
occurrence.addActionListener(listener);
occurrence.addActionListener(listener2);
occurrence.setSelected(true);
alphabetical = new JRadioButton("Alphabetical");
alphabetical.setMnemonic(KeyEvent.VK_A);
alphabetical.addActionListener(listener);
alphabetical.addActionListener(listener2);
ButtonGroup group = new ButtonGroup();
group.add(occurrence);
group.add(alphabetical);
go.addActionListener(listener);
go2.addActionListener(listener2);
input.addActionListener(listener);
input.addActionListener(listener2);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(1000,700));
text.add(textarea);
text.add(textarea2);
add(occurrence);
add(alphabetical);
add(label);
add(input);
add(go);
add(file1);
add(unique);
add(go2);
add(file2);
add(unique2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text1= file.getName();
file1.setText(text1);
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
words2 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words.add(ss );
words2.add(ss2 );
}
textarea.setText("");
}
SuperString[] ss = new SuperString[words.size()];
SuperString[] ss2 = new SuperString[words2.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
int j=0;
for(SuperString word: words2)
{
ss2[j] = word;
j++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
count++;
string.append(Integer.toString(count)+ " "+ word+ "\n");
}
if(occurrence.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string.toString());
}
for(SuperString word : ss2)
{
count2++;
string2.append(Integer.toString(count2)+ " "+ word.toString()+ "\n");
}
if(alphabetical.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string2.toString());
}
unique.setText("Unique Count: "+ Integer.toString(words.size()));
}
}
public class Button2Listener implements ActionListener
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text2= file.getName();
file2.setText(text2);
filename2 = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words3 = new CountLinkedList<SuperString>();
words4 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words3.add(ss );
words4.add(ss2 );
}
textarea2.setText("");
}
SuperString[] sstwo = new SuperString[words3.size()];
SuperString[] ss2two = new SuperString[words4.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word2: words3)
{
sstwo[i] = word2;
i++;
}
int j=0;
for(SuperString word2: words4)
{
ss2two[j] = word2;
j++;
}
Arrays.sort(sstwo, new SuperStringCountOrder());
for(SuperString word2 : sstwo)
{
count++;
string3.append(Integer.toString(count)+ " "+ word2+ "\n");
}
if(occurrence.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string3.toString());
}
for(SuperString word2 : ss2two)
{
count2++;
string4.append(count2+" "+ " "+word2+"\n");
}
if(alphabetical.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string4.toString());
}
unique2.setText("Unique Count: "+ Integer.toString(words3.size()));
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Lab10());
frame.pack();
frame.setVisible(true);
}
}
Your question doesn't make sense as written:
Integer N = input.getSelectedIndex()+1;
System.out.println(N);
The println cannot possibly tell you that N is null.
If the expression on the RHS of the = executes without an exception, then N is guaranteed to be non-null. The getSelectedIndex() call returns an int, and the result of the addition will be an int. That will then be autoboxed to an Integer, and autoboxing can NEVER give you a null.
If the expression on the RHS of the = throws an exception, then the println statement won't be executed.
In other words, what you are describing is Impossible.
So what I think is actually happening is one of the following:
Your code is throwing a NullPointerException in the first statement because input is null, and you have misdiagnosed that as meaning that N is null.
This code is sufficiently different from your actual code that it is not possible to understand what is really going on.
You have made a mistake in the compiling / running / deploying of your code, such that you are running a stale binary.
Your code isn't compilable the way it is now. You can't have multiple public classes in the same file. Also, to access the selected index from a JComboBox, this is what your actionPerformed method should look like.
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
int n = cb.getSelectedIndex();
//etc
}

Checkbox Compilation Error

I am to stimulate a java applet of a menu with checkboxes and checkboxgroups, with calories listed next to each food choice. My problem is I cannot figure out why I keep getting this error message when i compile it:
AnAppletWithCheckboxes.java:188: illegal forward reference
int crepeVal = Integer.parseInt(textField.getText());
I get that for every line that I have is converting the textField into an int, so hence there are 17 errors. Any idea of why will be appreciated!
Here is my Code:: it is very long because there are plenty checkboxes and textFields. I commented Out My place of Error! :
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AnAppletWithCheckboxes extends Applet implements ItemListener {
public void init() {
setLayout(new GridLayout(1, 0));
CheckboxGroup dinnerType = new CheckboxGroup();
standard = new Checkbox("standard", dinnerType, false);
standard.addItemListener(this);
deluxe = new Checkbox("deluxe", dinnerType, true);
deluxe.addItemListener(this);
CheckboxGroup appetizers = new CheckboxGroup();
crepe = new Checkbox("crepe", appetizers, false);
crepe.addItemListener(this);
quiche = new Checkbox("quiche", appetizers, false);
quiche.addItemListener(this);
dumpling = new Checkbox("dumpling", appetizers, false);
dumpling.addItemListener(this);
textField = new TextField("300");
textField.setEditable(false);
textField2 = new TextField("330");
textField2.setEditable(false);
textField3 = new TextField("98");
textField3.setEditable(false);
CheckboxGroup soupOrSalad = new CheckboxGroup();
soup = new Checkbox("Soup", soupOrSalad, false);
soup.addItemListener(this);
CheckboxGroup soups = new CheckboxGroup();
cream = new Checkbox("cream", soups, false);
cream.addItemListener(this);
broth = new Checkbox("broth", soups, false);
broth.addItemListener(this);
gumbo = new Checkbox("gumbo", soups, false);
gumbo.addItemListener(this);
textField4 = new TextField("190");
textField4.setEditable(false);
textField5 = new TextField("20");
textField5.setEditable(false);
textField6 = new TextField("110");
textField6.setEditable(false);
salad = new Checkbox("Salad", soupOrSalad, false);
salad.addItemListener(this);
CheckboxGroup salads = new CheckboxGroup();
tossed = new Checkbox("tossed", salads, false);
tossed.addItemListener(this);
caesar = new Checkbox("caesar", salads, false);
caesar.addItemListener(this);
croutons = new Checkbox("croutons");
croutons.addItemListener(this);
lite = new Checkbox("lite dressing");
lite.addItemListener(this);
textField7 = new TextField("35");
textField7.setEditable(false);
textField8 = new TextField("90");
textField8.setEditable(false);
textField9 = new TextField("60");
textField9.setEditable(false);
textField10 = new TextField("50");
textField10.setEditable(false);
CheckboxGroup entrees = new CheckboxGroup();
chicken = new Checkbox("chicken", entrees, false);
chicken.addItemListener(this);
beef = new Checkbox("beef", entrees, false);
beef.addItemListener(this);
lamb = new Checkbox("lamb", entrees, false);
lamb.addItemListener(this);
fish = new Checkbox("fish", entrees, false);
fish.addItemListener(this);
textField11 = new TextField("200");
textField11.setEditable(false);
textField12 = new TextField("170");
textField12.setEditable(false);
textField13 = new TextField("65");
textField13.setEditable(false);
textField14 = new TextField("150");
textField14.setEditable(false);
CheckboxGroup deserts = new CheckboxGroup();
pie = new Checkbox("pie", deserts, false);
pie.addItemListener(this);
fruit = new Checkbox("fruit", deserts, false);
fruit.addItemListener(this);
sherbet = new Checkbox("sherbet", deserts, false);
sherbet.addItemListener(this);
textField15 = new TextField("80");
textField15.setEditable(false);
textField16 = new TextField("60");
textField16.setEditable(false);
textField17 = new TextField("107");
textField17.setEditable(false);
calories = new Button("Calories");
calTextField = new TextField("0"+total);
calTextField.setEditable(false);
setLayout(new GridLayout(0, 1));
Panel p = new Panel();
add(p);
p.add(standard);
p.add(deluxe);
appetizerPanel = new Panel();
add(appetizerPanel);
label = new Label("Appetizer");
appetizerPanel.add(label);
appetizerPanel.add(crepe);
appetizerPanel.add(textField);
appetizerPanel.add(quiche);
appetizerPanel.add(textField2);
appetizerPanel.add(dumpling);
appetizerPanel.add(textField3);
soupPanel = new Panel();
add(soupPanel);
soupPanel.add(soup);
soupPanel.add(cream);
soupPanel.add(textField4);
soupPanel.add(broth);
soupPanel.add(textField5);
soupPanel.add(gumbo);
soupPanel.add(textField6);
saladPanel = new Panel();
add(saladPanel);
saladPanel.add(salad);
saladPanel.add(tossed);
saladPanel.add(textField7);
saladPanel.add(caesar);
saladPanel.add(textField8);
saladPanel.add(croutons);
saladPanel.add(textField9);
saladPanel.add(lite);
saladPanel.add(textField10);
entreePanel = new Panel();
add(entreePanel);
label2 = new Label("Entree");
entreePanel.add(label2);
entreePanel.add(chicken);
entreePanel.add(textField11);
entreePanel.add(beef);
entreePanel.add(textField12);
entreePanel.add(lamb);
entreePanel.add(textField13);
entreePanel.add(fish);
entreePanel.add(textField14);
desertPanel = new Panel();
add(desertPanel);
label3 = new Label("Desert");
desertPanel.add(label3);
desertPanel.add(pie);
desertPanel.add(textField15);
desertPanel.add(fruit);
desertPanel.add(textField16);
desertPanel.add(sherbet);
desertPanel.add(textField17);
caloriesPanel = new Panel();
add(caloriesPanel);
caloriesPanel.add(calories);
caloriesPanel.add(calTextField);
}
public void LabelChange(Label b) {
if (b ==label3)
b.setForeground(Color.lightGray);
else
label3.setForeground(Color.black);
}
/* This is where i get those errors!! */
int crepeVal = Integer.parseInt(textField.getText());
int quicheVal = Integer.parseInt(textField2.getText());
int dumplingVal = Integer.parseInt(textField3.getText());
int creamVal = Integer.parseInt(textField4.getText());
int brothVal = Integer.parseInt(textField5.getText());
int gumboVal = Integer.parseInt(textField6.getText());
int tossedVal = Integer.parseInt(textField7.getText());
int caesarVal = Integer.parseInt(textField8.getText());
int croutonsVal = Integer.parseInt(textField9.getText());
int liteVal = Integer.parseInt(textField10.getText());
int chickenVal = Integer.parseInt(textField11.getText());
int beefVal = Integer.parseInt(textField12.getText());
int lambVal = Integer.parseInt(textField13.getText());
int fishVal = Integer.parseInt(textField14.getText());
int pieVal = Integer.parseInt(textField15.getText());
int fruitVal = Integer.parseInt(textField16.getText());
int sherbetVal = Integer.parseInt(textField17.getText());
public boolean action(Event evt, Object whatAction){
if(!(evt.target instanceof Button)){
return false;
}
else {
calorieCount();
return true;
}
}
public void calorieCount () {
if (crepe.getState())
crepeVal += total;
else
crepeVal = 0;
if (quiche.getState())
quicheVal += total;
else
quicheVal = 0;
if (dumpling.getState())
dumplingVal += total;
else
dumplingVal= 0;
if (cream.getState())
creamVal += total;
else
creamVal = 0;
if (broth.getState())
brothVal += total;
else
brothVal = 0;
if (gumbo.getState())
gumboVal += total;
else
gumboVal = 0;
if (tossed.getState())
tossedVal += total;
else
tossedVal = 0;
if (caesar.getState())
caesarVal += total;
else
caesarVal = 0;
if (croutons.getState())
croutonsVal += total;
else
croutonsVal = 0;
if (lite.getState())
liteVal += total;
else
liteVal = 0;
if (chicken.getState())
chickenVal += total;
else
chickenVal = 0;
if (beef.getState())
beefVal += total;
else
beefVal = 0;
if (lamb.getState())
lambVal += total;
else
lambVal = 0;
if (fish.getState())
fishVal += total;
else
fishVal = 0;
if (pie.getState())
pieVal += total;
else
pieVal = 0;
if (fruit.getState())
fruitVal += total;
else
fruitVal = 0;
if (sherbet.getState())
sherbetVal += total;
else
sherbetVal = 0;
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == standard || e.getSource() == deluxe)
handleDinnerType((Checkbox)e.getSource());
else if (e.getSource() == soup || e.getSource() == salad)
handleSoupSaladChoice((Checkbox)e.getSource());
}
void handleDinnerType(Checkbox selectedType) {
boolean enabled;
if (selectedType == standard){
enabled = false;
LabelChange(label3);
}
else{
enabled = true;
LabelChange(label);
}
soup.setEnabled(enabled);
salad.setEnabled(enabled);
pie.setEnabled(enabled);
fruit.setEnabled(enabled);
sherbet.setEnabled(enabled);
cream.setEnabled(enabled);
broth.setEnabled(enabled);
gumbo.setEnabled(enabled);
tossed.setEnabled(enabled);
caesar.setEnabled(enabled);
croutons.setEnabled(enabled);
lite.setEnabled(enabled);
}
void handleSoupSaladChoice(Checkbox selectedCourse) {
boolean soupEnabled, saladEnabled;
if (selectedCourse == soup) {
soupEnabled = true;
saladEnabled = false;
soup.setForeground(Color.BLACK);
salad.setForeground(Color.lightGray);
}
else {
soupEnabled = false;
saladEnabled = true;
soup.setForeground(Color.lightGray);
salad.setForeground(Color.BLACK);
}
cream.setEnabled(soupEnabled);
broth.setEnabled(soupEnabled);
gumbo.setEnabled(soupEnabled);
tossed.setEnabled(saladEnabled);
caesar.setEnabled(saladEnabled);
croutons.setEnabled(saladEnabled);
lite.setEnabled(saladEnabled);
}
Label
label, label2, label3;
Panel
appetizerPanel, soupPanel, saladPanel, entreePanel, desertPanel, caloriesPanel;
Checkbox
standard, deluxe,
soup, salad,
crepe, quiche, dumpling,
cream, broth, gumbo,
tossed, caesar,
croutons, lite,
chicken, beef, lamb, fish,
pie, fruit, sherbet;
Button calories;
int total = 0;
TextField
textField, textField2, textField3,
textField4, textField5, textField6,
textField7, textField8, textField9,
textField10, textField11, textField12,
textField13, textField14, textField15,
textField16, textField17, calTextField;
}
In Java, you are not allowed to refer to a field a in an initializer of another field b if b is declared before a in the source code. That is, this is allowed:
int b = 3;
int a = b;
but this is not allowed:
int a = b;
int b = 3;
By the way, if Java had some magic way of figuring out that textField had to be initialized before crepeVal, you would still get a NullPointerException since textField is null after object construction.

Categories