How to change String ArrayList into a Double ArrayList? - java
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());
Related
I'm using JOptionPane to get user input and display a message. Is there a way for the input and message windows to both close when OK is clicked?
When the program runs, it shows a window filling up with tiny (5x5) rectangles of various colors, with the red and green RGB values corresponding to the rectangles' position on the screen. The blue RGB value is random but applies to all the rectangles. I ask the user with an input dialog to guess the random value, then I use a message dialog to tell them how far off they are. Here's the program: import java.util.*; import java.util.concurrent.*; import java.awt.*; import java.awt.font.*; import java.awt.event.*; import java.applet.*; import java.text.*; import javax.swing.*; public class TwoColorSpectrum extends Applet { public void paint(Graphics squares) { squares.setColor(Color.white); squares.fillRect(0, 0, 1280, 750); Random rectStr = new Random(); int randomRed, randomGreen, randomBlue, randomX, randomY, rectNum; do { rectNum = rectStr.nextInt(9999999); } while(rectNum < 5000000); Random color3 = new Random(); randomBlue = color3.nextInt(255); for(int h = 1; h <= rectNum; h++) { Random xPosition = new Random(); randomX = xPosition.nextInt(1275); double pcx = randomX / 1275.0; double dRandomR = pcx * 255.0; randomRed = (int)(dRandomR); Random yPosition = new Random(); randomY = yPosition.nextInt(745); double pcy = randomY / 745.0; double dRandomG = pcy * 255.0; randomGreen = (int)(dRandomG); Color randomColor = new Color(randomRed, randomGreen, randomBlue); squares.setColor(randomColor); squares.fillRect(randomX, randomY, 4, 4); } //asking the user what blue value it is JPanel panel = new JPanel(); JLabel label = new JLabel("Enter a value from 0 to 255."); JTextField field = new JTextField(10); JButton button = new JButton("Am I right?"); final int WIDTH = 350; final int HEIGHT = 100; class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String str; int num; str = field.getText(); num = Integer.parseInt(str); int absOff = Math.abs((randomBlue - num)); if(absOff != 0) { JOptionPane.showMessageDialog(null, "You were " + absOff + " off! The blue value is " + randomBlue + ".", "How much " + "were you off?", JOptionPane.PLAIN_MESSAGE); } else { JOptionPane.showMessageDialog(null, "That's right! The blue " + "value is " + randomBlue + ".", "How much " + "were you off?", JOptionPane.PLAIN_MESSAGE); } } } JFrame frame = new JFrame(); frame.setTitle("Guess the Color!"); frame.setSize(WIDTH, HEIGHT); button.addActionListener(new ButtonListener()); panel = new JPanel(); panel.add(label); panel.add(field); panel.add(button); frame.add(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } How can I make it so that the message dialog only shows up once, then disappears when the OK button is pressed?
Populate JComboBox from Text file 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.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
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.
Exceptions with JAVA loan calculator using JFrame?
I think I almost got it if I can just get rid of a few exceptions the program gives me when I try to run it. Here's the code I have: package RandomMathGame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class RandomMathGame { public static void main(String[] args) { RandomProblemGenerator randomProblems = new RandomProblemGenerator(10); final int numberProblems = 10; int correctScore = 0; JPanel panel = new JPanel(); int answer; int correctAnswer; JLabel[] mathProblems = new JLabel[numberProblems]; final JTextField[] mathAnswers = new JTextField[numberProblems]; JLabel[] correctYesNo = new JLabel[numberProblems]; final JLabel score = new JLabel(correctScore + "/10"); JButton submit = new JButton("Submit"); for (int i = 1; i <= numberProblems; i++) { final int X = randomProblems.createNumberX(); final int Y = randomProblems.createNumberY(); mathProblems[i] = new JLabel("" + X + " * " + Y + " = "); mathAnswers[i] = new JTextField(); answer = Integer.parseInt(mathAnswers[i].getText()); correctAnswer = X * Y; if (answer == correctAnswer) { correctYesNo[i] = new JLabel("Correct answer; good job!"); correctScore = correctScore + 1; } else { correctYesNo[i] = new JLabel("Incorrect answer; try again!"); } panel.add(mathProblems[i]); panel.add(mathAnswers[i]); panel.add(correctYesNo[i]); } final int temp = correctScore; submit.addActionListener(new ActionListener() { #Override public void actionPerformed(ActionEvent e) { score.setText("Score: " + temp + "/10"); } }); panel.add(submit); panel.add(score); JFrame gameFrame = new JFrame(); gameFrame.setTitle("Random Math Game"); gameFrame.setSize(150, 150); gameFrame.setVisible(true); gameFrame.setContentPane(panel); } } And these are the exceptions it's giving me when I run it: Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:504) at java.lang.Integer.parseInt(Integer.java:527) at RandomMathGame.RandomMathGame.main(RandomMathGame.java:33) Java Result: 1 I'm crunched for time, so any help would be much appreciated.
You are trying to get from a field you just created which is blank. mathAnswers[i] = new JTextField(); answer = Integer.parseInt(mathAnswers[i].getText()); So in this you are just checking from wrong place. Seems like on first step you want to create the text fields and the second line should be there at some other event. Hope it helps
String answerStr = mathAnswers[i].getText(); if(answerStr.isEmpty()){ correctYesNo[i] = new JLabel("Not a valid answer/answer field empty!"); } else { answer = Integer.parseInt(answerStr); correctAnswer = X * Y; //Rest of your code goes here } Hope this helps you!
answer = Integer.parseInt(mathAnswers[i].getText()); Is what's causing the error. This is because one of your textfields is blank. Do some validation before accepting user input, unless you want your application to go awry.
java.lang.IndexOutOfBoundsException: Index: 6, Size: 6 JAVA, ARRAY
I realize this is an unbelievably common issue and have looked very very thoroughly but have had no luck! It seems I am having an outOfBounds Exception issue. My code is as follows wuth errors just after! Thanks again :) UPDATE: Thanks for all of your many fast responses. Although it says there's an issue with Analysis Panel, I didn't know exactly if this was the cause as I have other classes which use it with no issues! But below is the other code. Thanks again! public class AnalysisPanel extends JPanel { private JTextArea overview_text = GuiComponentGenerator.getJTextArea(""); private JTextArea csv_text = GuiComponentGenerator.getJTextArea(""); private JComboBox analyser_choices; private String[] analyser_class_names; private LinkedHashMap<String, ImageAnalysis> analyser_outputs = new LinkedHashMap(); private JTextField[] weka_directory_texts; private JTextField[] weka_tag_texts; private JTextField weka_output_file_path_text = GuiComponentGenerator .getJTextField(""); private JTextField weka_relation_text = GuiComponentGenerator .getJTextField(""); public AnalysisPanel() { GuiComponentGenerator.setLook(this); analyser_class_names = ResourceAndClassDirectories .getClassNamesInDirectory(ResourceAndClassDirectories.IMAGE_ANALYSERS_CLASS_STEM); ArrayList<String> choices = new ArrayList( Arrays.asList(analyser_class_names)); choices.add(0, "All"); analyser_choices = GuiComponentGenerator.getJComboBox(choices); analyser_choices.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { updateTextBoxes(); } }); setLayout(new BorderLayout()); add(BorderLayout.NORTH, GuiComponentGenerator.getJPanel(analyser_choices)); add(BorderLayout.CENTER, getTextsPanel()); add(BorderLayout.SOUTH, getWekaPanel()); } private JPanel getWekaPanel() { JPanel weka_panel = GuiComponentGenerator.getJPanel(new BorderLayout()); JPanel details_panel = GuiComponentGenerator.getJPanel(new GridLayout( 6, 1)); JPanel top_panel = GuiComponentGenerator .getJPanel(new GridLayout(1, 2)); JPanel left_top_panel = GuiComponentGenerator.getJPanel(new BorderLayout()); JPanel right_top_panel = GuiComponentGenerator.getJPanel(new BorderLayout()); left_top_panel.add(BorderLayout.WEST, GuiComponentGenerator.getJLabel("Relation:")); left_top_panel.add(BorderLayout.CENTER, weka_relation_text); right_top_panel.add(BorderLayout.WEST, GuiComponentGenerator.getJLabel("Output to:")); right_top_panel.add(BorderLayout.CENTER, weka_output_file_path_text); top_panel.add(left_top_panel); top_panel.add(right_top_panel); weka_panel.add(BorderLayout.NORTH, top_panel); weka_directory_texts = new JTextField[5]; weka_tag_texts = new JTextField[5]; JPanel labels_panel = GuiComponentGenerator.getJPanel(new GridLayout(1, 2)); labels_panel.add(GuiComponentGenerator.getCentreAlignedJLabel("Tag")); labels_panel.add(GuiComponentGenerator .getCentreAlignedJLabel("Image directory")); details_panel.add(labels_panel); for (int pos = 0; pos < 5; pos++) details_panel.add(getDetailsPanel(pos)); weka_panel.add(BorderLayout.NORTH, top_panel); weka_panel.add(BorderLayout.CENTER, details_panel); JPanel weka_bordered_panel = GuiComponentGenerator .getLeftBorderedJPanel(weka_panel, "Weka"); return weka_bordered_panel; } private JPanel getDetailsPanel(int pos) { JPanel details_panel = GuiComponentGenerator.getJPanel(new GridLayout( 1, 2)); final JTextField weka_directory_text = GuiComponentGenerator .getJTextField(""); JTextField weka_tag_text = GuiComponentGenerator.getJTextField(""); weka_directory_texts[pos] = weka_directory_text; weka_tag_texts[pos] = weka_tag_text; JPanel right_panel = GuiComponentGenerator .getJPanel(new BorderLayout()); right_panel.add(BorderLayout.CENTER, weka_directory_text); JButton choose_directory_button = GuiComponentGenerator .getJButton(GuiComponentGenerator.FILE_DIALOG_ICON); right_panel.add(BorderLayout.EAST, choose_directory_button); choose_directory_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { File directory = FileChooserDialog.getFile( ResourceAndClassDirectories.SOURCE_DIRECTORY, "", true); if (directory != null) weka_directory_text.setText(directory.getPath()); } }); details_panel.add(weka_tag_text); details_panel.add(right_panel); return details_panel; } public String[] getWekaRunDetails() { String[] wrd = { weka_relation_text.getText(), weka_output_file_path_text.getText() }; return wrd; } public ArrayList<String[]> getWekaImageDetails() { ArrayList<String[]> image_details = new ArrayList(); for (int pos = 0; pos < 5; pos++) { String[] details = { weka_directory_texts[pos].getText(), weka_tag_texts[pos].getText() }; image_details.add(details); } return image_details; } private JPanel getTextsPanel() { JPanel texts_panel = GuiComponentGenerator .getJPanel(new BorderLayout()); csv_text.setRows(3); csv_text.setFont(new Font("Courier", Font.PLAIN, 14)); texts_panel.add(BorderLayout.NORTH, GuiComponentGenerator .getLeftBorderedJPanel( GuiComponentGenerator.getJScrollPane(csv_text), "CSV")); texts_panel.add(BorderLayout.CENTER, GuiComponentGenerator .getLeftBorderedJPanel( GuiComponentGenerator.getJScrollPane(overview_text), "Overview")); return texts_panel; } public String getChosenImageAnalyser() { return (String) analyser_choices.getSelectedItem(); } public void performAnalyses(final TaggedBufferedImage tbi) { Thread thread = new Thread() { public void run() { analyser_outputs.clear(); String choice = (String) analyser_choices.getSelectedItem(); csv_text.setText(""); if (choice.equals("All")) { for (String analyser_class_name : analyser_class_names) performAnalysis(analyser_class_name, tbi); } else performAnalysis(choice, tbi); updateTextBoxes(); } }; thread.start(); } private void updateTextBoxes() { String overview = ""; String csv_headings = "|"; String csv_values = "|"; String choice = (String) analyser_choices.getSelectedItem(); for (String analyser_class_name : analyser_class_names) { if (choice.equals("All") || choice.equals(analyser_class_name)) { ImageAnalysis image_analysis = analyser_outputs .get(analyser_class_name); if (image_analysis != null) { overview += analyser_class_name + "\n\n" + image_analysis.overview + "\n-----------------\n"; System.out.println("In Analysis Panel: image analsis csv headings " + image_analysis.csv_headings.size()); for (int pos = 0; pos < image_analysis.csv_headings.size(); pos++) { String heading = image_analysis.csv_headings.get(pos); String value = image_analysis.csv_values.get(pos); while (heading.length() < value.length()) heading += " "; while (value.length() < heading.length()) value += " "; csv_values += value + "|"; csv_headings += heading + "|"; } } } } overview_text.setText(overview); csv_text.setText(csv_headings + "\n" + csv_values); } private void performAnalysis(String analyser_class_name, TaggedBufferedImage tbi) { try { overview_text.setText("Analysing " + analyser_class_name); Class c = Class .forName(ResourceAndClassDirectories.IMAGE_ANALYSERS_CLASS_STEM + "." + analyser_class_name); ImageAnalyserInterface analyser = (ImageAnalyserInterface) c .newInstance(); ImageAnalysis image_analysis = analyser.analyseImage(tbi); analyser_outputs.put(analyser_class_name, image_analysis); } catch (Exception ex) { ex.printStackTrace(); } } } Update: Now working, although the issue was in the below, it needed to be changed in the Colour file itself! Thanks all :)
If there are 6 elements in the array, then index 5 will be the final index, as it is zero indexed - that is, 0,1,2,3,4,5 is 6 elements
Well based on the title you are trying to access index 6 in an array of size 6. This is not possible since arrays in Java run from index 0 to size-1. Your max possible index is therefore 5 in an array of size 6.