Why can't my CSV File display the content onto my graph? - java

Well basically what my program does is that I have a csv file that reads in the
milliseconds (which I converted) and a letter that represents a zone. I am trying to display it as a bar chart but I have different tabs that each letter (zone) goes to. My
issue is trying to send the letter (from file) to the specific zone which I made in tabs. Maybe I am missing something but I am not sure. Any help will be much appreciated.
Here is my code:
#SuppressWarnings({ "serial", "deprecation" })
public class InductionTreeGraph extends JFrame {
static TimeSeries ts = new TimeSeries("data", Millisecond.class);
public static void add(JTabbedPane jtp, String label, int mnemonic, AbstractButton button1)
{
int count = jtp.getTabCount();
JButton button = new JButton(label);
button.setBackground(Color.WHITE);
jtp.addTab(label, null, button, null);
jtp.setMnemonicAt(count, mnemonic);
}
public InductionTreeGraph() throws Exception {
final XYDataset dataset = (XYDataset) createDataset();
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(1000, 400));
setContentPane(chartPanel);
JFrame frame = new JFrame("Induction Zone Chart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTabbedPane jtp = new JTabbedPane();
jtp.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
String zones[] = {"Zone A", "Zone B", "Zone C", "Zone S",
"Zone SH","Zone W"};
int mnemonic[] = {KeyEvent.VK_A, KeyEvent.VK_B, KeyEvent.VK_C,
KeyEvent.VK_S, KeyEvent.VK_H,KeyEvent.VK_W};
for (int i = 0, n=zones.length; i<n; i++)
{
AbstractButton button1 = null;
InductionTreeGraph.add(jtp, zones[i], mnemonic[i], button1);
}
final JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Update") {
public void actionPerformed(ActionEvent e) {
chartPanel.repaint();
}
}));
frame.add(jtp, BorderLayout.NORTH);
frame.add(p, BorderLayout.SOUTH);
frame.getContentPane().add(chartPanel);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
#SuppressWarnings("deprecation")
private XYDataset createDataset() {
final TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(ts);
TreeMap<String,TreeMap<Integer,Integer[]>> zoneMap = getInductions("","");
// Iterate through all zones and print induction rates for every minute into
// every hour by zone...
Iterator<String> zoneIT = zoneMap.keySet().iterator();
while (zoneIT.hasNext())
{
String zone = zoneIT.next();
TreeMap<Integer,Integer[]> hourCountsInZoneMap = zoneMap.get(zone);
System.out.println("ZONE " + zone + " : ");
Iterator<Integer> hrIT = hourCountsInZoneMap.keySet().iterator();
while (hrIT.hasNext())
{
int hour = hrIT.next();
Integer [] indRatePerMinArray = hourCountsInZoneMap.get(hour);
for (int i=0; i< indRatePerMinArray.length; i++)
{
System.out.print(hour + ":");
System.out.print(i < 10 ? "0" + i : i);
System.out.println(" = " + indRatePerMinArray[i] + " induction(s)");
}
}
}
return dataset;
}
#SuppressWarnings("deprecation")
private JFreeChart createChart(XYDataset dataset) {
final JFreeChart chart = ChartFactory.createXYBarChart(
"Induction Zone Chart",
"Hour",
true,
"Inductions Per Minute",
(IntervalXYDataset) dataset,
PlotOrientation.VERTICAL,
false,
true,
false
);
XYPlot plot = (XYPlot)chart.getPlot();
XYBarRenderer renderer = (XYBarRenderer)plot.getRenderer();
renderer.setBarPainter(new StandardXYBarPainter());
renderer.setDrawBarOutline(false);
ValueAxis axis = plot.getDomainAxis();
axis.setAutoRange(true);
axis.setFixedAutoRange(60000.0);
// Set an Induction target of 30 per minute
Marker target = new ValueMarker(30);
target.setPaint(java.awt.Color.blue);
target.setLabel("Induction Rate Target");
plot.addRangeMarker(target);
return chart;
}
private TreeMap<String, TreeMap<Integer, Integer[]>> getInductions(String mills, String zone) {
// TreeMap of Inductions for Every Minute in Day Per Zone...
// Key = Zone
// Value = TreeMap of Inductions per Minute per Hour:
// Key = Hour
// Value = Array of 60 representing Induction Rate Per Minute
// (each element is the induction rate for that minute)
TreeMap<String, TreeMap<Integer, Integer[]>> zoneMap = new TreeMap<String, TreeMap<Integer, Integer[]>>();
// Input file name...
String fileName = "/home/a002384/ECLIPSE/IN070914.CSV";
try
{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
try
{
// Read a line from the csv file until it reaches to the end of the file...
while ((line = br.readLine()) != null)
{
// Parse a line of text in the CSV...
String [] indData = line.split("\\,");
long millisecond = Long.parseLong(indData[0]);
String zone1 = indData[1];
// The millisecond value is the number of milliseconds since midnight.
// From this, we can derive the hour and minute of the day as follows:
int secOfDay = (int)(millisecond / 1000);
int hrOfDay = secOfDay / 3600;
int minInHr = secOfDay % 3600 / 60;
// Obtain the induction rate TreeMap for the current zone.
// If this is a "newly-encountered" zone, create a new TreeMap.
TreeMap<Integer, Integer[]> hourCountsInZoneMap;
if (zoneMap.containsKey(zone1))
hourCountsInZoneMap = zoneMap.get(zone1);
else
hourCountsInZoneMap = new TreeMap<Integer, Integer[]>();
// Obtain the induction rate array for the current hour in the current zone.
// If this is a new hour in the current zone, create a new array,
// and initialize this array with all zeroes.
// The array is size 60, because there are 60 minutes in the hour.
// Each element in the array represents the induction rate for that minute.
Integer [] indRatePerMinArray;
if (hourCountsInZoneMap.containsKey(hrOfDay))
indRatePerMinArray = hourCountsInZoneMap.get(hrOfDay);
else
{
indRatePerMinArray = new Integer[60];
Arrays.fill(indRatePerMinArray, 0);
}
// Increment the induction rate for the current minute by one.
// Each line in the csv file represents a single induction at a
// single point in time.
indRatePerMinArray[minInHr]++;
// Add everything back into the TreeMaps if these are newly-created.
if (!hourCountsInZoneMap.containsKey(hrOfDay))
hourCountsInZoneMap.put(hrOfDay, indRatePerMinArray);
if (!zoneMap.containsKey(zone1))
zoneMap.put(zone1, hourCountsInZoneMap);
}
}
finally
{
br.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return zoneMap;
}
#SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
try {
InductionTreeGraph dem = new InductionTreeGraph();
dem.pack();
dem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while(true) {
double millisecond = 2;
double num = millisecond;
System.out.println(num);
ts.addOrUpdate(new Millisecond(), num);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

My very first suggestion is about this line:
setContentPane(chartPanel);
Don't mess with content pane. Use this line instead:
getContentPane().add(chartPanel);
The prooblem I see in your code is that InductionTreeGraph extends from JFrame and you are setting this chartPanel as this frame's content pane, but then you use a new JFrame local variable (called frame) and add this chartPanel to this frame as well:
JFrame frame = new JFrame("Induction Zone Chart");
...
frame.getContentPane().add(chartPanel);
Swing components are intended to be used "as is" so it's preferable composition over inheritance. Having said this you should consider remove extends JFrame on your class declaration and add all your components (chart panel, buttons, etc) to this local frame instead.
Related
You may want to take a look to the example shown in this Q&A. This or any #trashgod's examples in Stack Overflow about JFreeChart (f.e. this one) might help you to better structure your code.

Related

JFreeChart show one single value

I have a chart where I display the values of a table (stock and date). The stock is displayed in the y axis and the dates in the x axis.
As long as the query returns 2 entries, it is shown normally as a line, but if the query returns only one entry, nothing is shown (there should be a point there).
Any suggestions on how to fix this would be highly appreciated.
2 entries: enter image description here
1 entry: enter image description here
Code (the chart is built in an action listener):
historyButton.addActionListener(e -> {
// stock list and dates list retrieved from database
int articleNr = Integer.parseInt(articleIDText.getText());
List<Integer> displayStockHistory;
List<String> displayDatesStockHistory;
try {
displayStockHistory = business.displayStockHistory(articleNr);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
try {
displayDatesStockHistory = business.displayDatesStockHistory(articleNr);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
// add db values to the dataset
for(int i = 0; i < displayStockHistory.size(); i++){
dataset.addValue(displayStockHistory.get(i), "Articles in Stock", displayDatesStockHistory.get(i));
}
// compose chart
JFreeChart chart = ChartFactory.createLineChart(
"Stock History",
"Date",
"Stock",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false);
chart.setBackgroundPaint(c2);
chart.getTitle().setPaint(c3);
CategoryPlot p = chart.getCategoryPlot();
p.setForegroundAlpha(0.9f);
CategoryItemRenderer renderer = p.getRenderer();
//renderer.setSeriesPaint(0, c4);
renderer.setSeriesStroke( 0, new BasicStroke( 5 ) );
chart.getCategoryPlot().setBackgroundPaint(c1);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setBackground(c2);
chartScrollPane.getViewport().add(chartPanel);
chartPanel.setPreferredSize(new Dimension(2000, 270));
ChartFrame frame1 = new ChartFrame("Line graph", chart);
frame1.setVisible(true);
frame1.setSize(500, 400);
});
}
Your chosen chart factory instantiates a LineAndShapeRenderer, so one approach is to make the renderer's shapes visible for all series, as shown here; note that the API has changed:
CategoryPlot plot = (CategoryPlot) chart.getPlot();
LineAndShapeRenderer r = (LineAndShapeRenderer) plot.getRenderer();
r.setDefaultShapesVisible(true);
To enable shapes only for series having a single, non-null value, you'll have to iterate through the data explicitly:
DefaultCategoryDataset data = new DefaultCategoryDataset();
data.addValue(3, "Data1", LocalDate.now());
data.addValue(2, "Data2", LocalDate.now());
data.addValue(1, "Data2", LocalDate.now().plusDays(1));
…
for (int row = 0; row < data.getRowCount(); row++) {
int count = 0;
for (int col = 0; col < data.getColumnCount(); col++) {
count += data.getValue(row, col) != null ? 1 : 0;
}
if (count == 1) {
r.setSeriesShapesVisible(row, true);
}
}

Gantt chart: freeze legend and axes when scrolling

In the chart factory and I use there SlidingGanttCategoryDataset. But the scrolling does not appear. What am I missing?
public JFreeChartGanttChart(String applicationTitle, String chartTitle) {
super(applicationTitle);
// based on the dataset we create the chart
Map<Integer, Map<Integer, String>> labels = new LinkedHashMap<>();
JFreeChart chart = ChartFactory.createGanttChart(chartTitle,
"Vessels",
"Time",
createDataset(labels),
true,
true,
true);
// Adding chart into a chart pane
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.getDomainAxis().setUpperMargin(0.001);
plot.getRangeAxis().setLowerMargin(0.01);
plot.getRangeAxis().setUpperMargin(0.01);
plot.getDomainAxis().setLowerMargin(0.001);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(1000, 1500));
setContentPane(chartPanel);
CategoryItemRenderer renderer = plot.getRenderer();
renderer.setDefaultItemLabelGenerator(new IntervalCategoryItemLabelGenerator(){
#Override
public String generateRowLabel(CategoryDataset dataset, int row) {
return "Text ... " + row ; // not needed here
}
#Override
public String generateColumnLabel(CategoryDataset dataset, int column) {
return " Text ... " + column; // not needed here
}
#Override
public String generateLabel(CategoryDataset dataset, int row, int column) {
return labels.get(row).get(column) ; // row+ " " + column
}
});
renderer.setDefaultItemLabelsVisible(true);
renderer.setDefaultItemLabelPaint(Color.BLACK);
renderer.setDefaultItemLabelFont(new Font("arial", Font.PLAIN, 6), false);
// setDefaultPositiveItemLabelPosition - text will be inside label
renderer.setDefaultNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE6,
TextAnchor.BOTTOM_LEFT));
}
}
While it is technically possible to add a ChartPanel to a JScrollPane, rendering and scrolling hundreds or thousands of tasks scales poorly; the typical appearance is shown here. Instead, use a SlidingGanttCategoryDataset, which "presents a subset of the categories in an underlying dataset." Given an arbitrary number, N, of tasks to to be displayed MAX at a time, construct the corresponding dataset:
private static final int N = 1000;
private static final int MAX = 12;
…
private final SlidingGanttCategoryDataset dataset = new
SlidingGanttCategoryDataset(taskSeriesCollection, 0, MAX);
Then add a suitable control adjacent to the ChartPanel and listen for changes; update the dataset's first displayed index accordingly:
JSlider slider = new JSlider(JSlider.VERTICAL, 0, N - MAX, 0);
slider.addChangeListener((ChangeEvent e) -> {
dataset.setFirstCategoryIndex(slider.getValue());
});

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

Cannot display properlly axis and tooltip on jfreechart

I have problem on the Axis and the Tooltip display on JFreeChart they don't display all the values, I am trying to display the bytes based on daily use, here is an image to show exactly my problem:
There are missing some values and on the tallest red bar it doesn't show me the bytes on the tooltip. Here is my code:
final JFreeChart chart = createTrafficChart();
chartPanel = new ChartPanel(chart, true, true, true, true, true);
chartPanel.setPreferredSize(new java.awt.Dimension(750, 367));
a.gridx = 0;
a.gridy = 3;
jpContainer.add(chartPanel, a);
private JFreeChart createTrafficChart() {
// create plot ...
final IntervalXYDataset data1 = createDatasetDownload();
XYBarRenderer t= new XYBarRenderer(0.20);
t.setShadowVisible(false);
final XYItemRenderer renderer1 = t;
renderer1.setBaseToolTipGenerator(new MyTrafficToolTipGenerator());
final DateAxis domainAxis = new DateAxis("Date");
domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
final NumberAxis rangeAxis = new NumberAxis("Bytes");
setupRangeAxis(rangeAxis);
final XYPlot plot = new XYPlot(data1, domainAxis, rangeAxis, renderer1);
// add a second dataset and renderer...
final XYDataset data2 = createDatasetUpload();
final XYItemRenderer renderer2 = new StandardXYItemRenderer();
renderer2.setBaseToolTipGenerator(new MyTrafficToolTipGenerator());
plot.setDataset(1, data2);
plot.setRenderer(1, renderer2);
plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
return new JFreeChart("Traffic", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
}
And this code:
public void setupRangeAxis(NumberAxis rangeAxis) {
final TickUnits standardUnits = new TickUnits();
standardUnits.add(new MyNumberTickUnit(1));
standardUnits.add(new MyNumberTickUnit(10));
standardUnits.add(new MyNumberTickUnit(100));
standardUnits.add(new MyNumberTickUnit(1024)); // Kilo
standardUnits.add(new MyNumberTickUnit(10000));
standardUnits.add(new MyNumberTickUnit(100000));
standardUnits.add(new MyNumberTickUnit(1024*1024)); // Mega
standardUnits.add(new MyNumberTickUnit(10000000));
standardUnits.add(new MyNumberTickUnit(100000000));
standardUnits.add(new MyNumberTickUnit(1024*1024*1024)); // Giga
standardUnits.add(new MyNumberTickUnit(10000000000L));
standardUnits.add(new MyNumberTickUnit(100000000000L));
standardUnits.add(new MyNumberTickUnit(1024*1024*1024*1024)); // Tera
standardUnits.add(new MyNumberTickUnit(10000000000000L));
standardUnits.add(new MyNumberTickUnit(100000000000000L));
standardUnits.add(new MyNumberTickUnit(1000000000000000L)); // Peta
standardUnits.add(new MyNumberTickUnit(10000000000000000L));
standardUnits.add(new MyNumberTickUnit(100000000000000000L));
standardUnits.add(new MyNumberTickUnit(1000000000000000000L)); // Exa
rangeAxis.setStandardTickUnits(standardUnits);
}
Which i found here .
I also have this code:
public class MyNumberTickUnit extends NumberTickUnit{
private static final long serialVersionUID = 4281451255133640119L;
public MyNumberTickUnit(double size) {
super(size);
}
public String valueToString(double value){
return StringFormat.formatTheTraffic(value);
}
}
public class StringFormat {
public static String formatTheTraffic(double input) {
String result = "";
if (input < KILO_BYTES) {
result = input + " Byte";
} else if ((input < MEGA_BYTES) && (input >= KILO_BYTES)) {
result = new DecimalFormat("##.#").format(input / KILO_BYTES) + " KB";
} else if ((input < GIGA_BYTES) && (input >= MEGA_BYTES)) {
result = new DecimalFormat("##.#").format(input / MEGA_BYTES) + " MB";
} else if ((input < TERA_BYTES) && (input >= GIGA_BYTES)) {
result = new DecimalFormat("##.#").format(input / GIGA_BYTES) + " GB";
}
return result;
}
}
Thanks for your attention and time!
I found my problem. It was inside the formatTheTraffic method! I change it and works properly now!

Arrays not properly sorting

Good afternoon. I have created an application for an introductory java course that allows a user to sort their DVD collection by title, studio, or year. The application also allows the user to add additional DVD's to their collection, thus enlarging their arrays. The code properly compiles, but there is clearly something wrong as the titles, studio, and years are mixing themselves up. To be clear, this code is from a textbook and is part of a lab that requires the use of the exact methods, packages, etc. that you see in the code. I'm not asking for advice on how to make the code more efficient (although that is welcome as I am learning), but specifically what is wrong with the code provided causing the "scramble". Here is the code I have:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class DVD extends JFrame implements ActionListener
{
// construct components
JLabel sortPrompt = new JLabel("Sort by:");
JComboBox fieldCombo = new JComboBox();
JTextPane textPane = new JTextPane();
// initialize data in arrays
String title[] = {"Casablanca", "Citizen Kane", "Singin' in the Rain", "The Wizard of Oz"};
String studio[] = {"Warner Brothers", "RKO Pictures", "MGM", "MGM"};
String year[] = {"1942", "1941", "1952", "1939"};
// construct instance of DVD
public DVD()
{
super("Classics on DVD");
}
// create the menu system
public JMenuBar createMenuBar()
{
// create an instance of the menu
JMenuBar mnuBar = new JMenuBar();
setJMenuBar(mnuBar);
// construct and populate the File menu
JMenu mnuFile = new JMenu("File", true);
mnuFile.setMnemonic(KeyEvent.VK_F);
mnuFile.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuFile);
JMenuItem mnuFileExit = new JMenu("Exit");
mnuFileExit.setMnemonic(KeyEvent.VK_X);
mnuFileExit.setDisplayedMnemonicIndex(1);
mnuFile.add(mnuFileExit);
mnuFileExit.setActionCommand("Exit");
mnuFileExit.addActionListener(this);
// contruct and populate the Edit menu
JMenu mnuEdit = new JMenu("Edit", true);
mnuEdit.setMnemonic(KeyEvent.VK_E);
mnuEdit.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuEdit);
JMenuItem mnuEditInsert = new JMenuItem("Insert New DVD");
mnuEditInsert.setMnemonic(KeyEvent.VK_I);
mnuEditInsert.setDisplayedMnemonicIndex(0);
mnuEdit.add(mnuEditInsert);
mnuEditInsert.setActionCommand("Insert");
mnuEditInsert.addActionListener(this);
JMenu mnuEditSearch = new JMenu("Search");
mnuEditSearch.setMnemonic(KeyEvent.VK_R);
mnuEditSearch.setDisplayedMnemonicIndex(3);
mnuEdit.add(mnuEditSearch);
JMenuItem mnuEditSearchByTitle = new JMenuItem("by Title");
mnuEditSearchByTitle.setMnemonic(KeyEvent.VK_T);
mnuEditSearchByTitle.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByTitle);
mnuEditSearchByTitle.setActionCommand("title");
mnuEditSearchByTitle.addActionListener(this);
JMenuItem mnuEditSearchByStudio = new JMenuItem("by Studio");
mnuEditSearchByStudio.setMnemonic(KeyEvent.VK_S);
mnuEditSearchByStudio.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByStudio);
mnuEditSearchByStudio.setActionCommand("studio");
mnuEditSearchByStudio.addActionListener(this);
JMenuItem mnuEditSearchByYear = new JMenuItem("by Year");
mnuEditSearchByYear.setMnemonic(KeyEvent.VK_Y);
mnuEditSearchByYear.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByYear);
mnuEditSearchByYear.setActionCommand("year");
mnuEditSearchByYear.addActionListener(this);
return mnuBar;
}
// create the content pane
public Container createContentPane()
{
// populate the JComboBox
fieldCombo.addItem("Title");
fieldCombo.addItem("Studio");
fieldCombo.addItem("Year");
fieldCombo.addActionListener(this);
fieldCombo.setToolTipText("Click the drop-down arrow to display sort fields.");
// construct and populate the north panel
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(sortPrompt);
northPanel.add(fieldCombo);
// create the JTextPane and center panel
JPanel centerPanel = new JPanel();
setTabsAndStyles(textPane);
textPane = addTextToTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500, 200));
centerPanel.add(scrollPane);
// create Container and set attributes
Container c = getContentPane();
c.setLayout(new BorderLayout(10,10));
c.add(northPanel,BorderLayout.NORTH);
c.add(centerPanel,BorderLayout.CENTER);
return c;
}
// method to create tab stops and set font styles
protected void setTabsAndStyles(JTextPane textPane)
{
// create Tab Stops
TabStop[] tabs = new TabStop[2];
tabs[0] = new TabStop(200, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
tabs[1] = new TabStop(350, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
TabSet tabset = new TabSet(tabs);
// set Tab Style
StyleContext tabStyle = StyleContext.getDefaultStyleContext();
AttributeSet aset =
tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset);
textPane.setParagraphAttributes(aset, false);
// set Font styles
Style fontStyle =
StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = textPane.addStyle("regular", fontStyle);
StyleConstants.setFontFamily(fontStyle, "SansSerif");
Style s = textPane.addStyle("italic", regular);
StyleConstants.setItalic(s, true);
s = textPane.addStyle("bold", regular);
StyleConstants.setBold(s, true);
s = textPane.addStyle("large", regular);
StyleConstants.setFontSize(s, 16);
}
// method to add new text to the JTextPane
public JTextPane addTextToTextPane()
{
Document doc = textPane.getDocument();
try
{
// clear the previous text
doc.remove(0, doc.getLength());
// insert title
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));
// insert detail
for (int j = 0; j<title.length; j++)
{
doc.insertString(doc.getLength(), title[j] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(), studio[j] + "\t", textPane.getStyle("italic"));
doc.insertString(doc.getLength(), year[j] + "\t", textPane.getStyle("regular"));
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}
return textPane;
}
// event to process user clicks
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
// user clicks the sort by combo box
if (e.getSource() == fieldCombo)
{
switch(fieldCombo.getSelectedIndex())
{
case 0:
sort(title);
break;
case 1:
sort(studio);
break;
case 2:
sort(year);
break;
}
}
// user clicks Exit on the File menu
if (arg == "Exit")
System.exit(0);
// user clicks Insert New DVD on the Edit Menu
if (arg == "Insert")
{
// accept new data
String newTitle = JOptionPane.showInputDialog(null, "Please enter the new movie's title");
String newStudio = JOptionPane.showInputDialog(null, "Please enter the studio for " + newTitle);
String newYear = JOptionPane.showInputDialog(null, "Please enter the year for " + newTitle);
// enlarge arrays
title = enlargeArray(title);
studio = enlargeArray(studio);
year = enlargeArray(year);
// add new data to arrays
title[title.length-1] = newTitle;
studio[studio.length-1] = newStudio;
year[year.length-1] = newYear;
// call sort method
sort(title);
fieldCombo.setSelectedIndex(0);
}
// user clicks Title on the Search submenu
if (arg == "title")
search(arg, title);
// user clicks Studio on the Search submenu
if (arg == "studio")
search(arg, studio);
// user clicks Year on the Search submenu
if (arg == "year")
search(arg, year);
}
// method to enlarge an array by 1
public String[] enlargeArray(String[] currentArray)
{
String[] newArray = new String[currentArray.length + 1];
for (int i = 0; i<currentArray.length; i++)
newArray[i] = currentArray[i];
return newArray;
}
// method to sort arrays
public void sort(String tempArray[])
{
// loop ton control number of passes
for (int pass = 1; pass < tempArray.length; pass++)
{
for (int element = 0; element < tempArray.length - 1; element++)
if (tempArray[element].compareTo(tempArray[element + 1])>0)
{
swap(title, element, element + 1);
swap(studio, element, element + 1);
swap(year, element, element + 1);
}
}
addTextToTextPane();
}
// method to swap two elements of an array
public void swap(String swapArray[], int first, int second)
{
String hold; // temporary holding area for swap
hold = swapArray[first];
swapArray[first] = swapArray[second];
swapArray[second] = hold;
}
public void search(String searchField, String searchArray[])
{
try
{
Document doc = textPane.getDocument(); // assign text to document object
doc.remove(0,doc.getLength()); // clear previous text
// display column titles
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));
// prompt user for search data
String search = JOptionPane.showInputDialog(null, "Please enter the "+searchField);
boolean found = false;
// search arrays
for (int i = 0; i<title.length; i++)
{
if (search.compareTo(searchArray[i])==0)
{
doc.insertString(doc.getLength(), title[i] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(), studio[i] + "\t", textPane.getStyle("italic"));
doc.insertString(doc.getLength(), year[i] + "\t", textPane.getStyle("regular"));
found = true;
}
}
if (found == false)
{
JOptionPane.showMessageDialog(null, "Your search produced no results.","No results found",JOptionPane.INFORMATION_MESSAGE);
sort(title);
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}
}
// main method executes at run time
public static void main(String arg[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
DVD f = new DVD();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(f.createMenuBar());
f.setContentPane(f.createContentPane());
f.setSize(600,375);
f.setVisible(true);
}
}
Here is a screenshot to give you a sense of what I mean be "scrambled".
Obviously, all of the titles should be in the title column, studios in studio, and years in year.
As always, I appreciate the guidance.
The problem is this line
doc.insertString(doc.getLength(), year[j] + "\t", textPane.getStyle("regular"));
where you put a tab ("\t") after the year but instead you want a newline ("\n"). So the line becomes
doc.insertString(doc.getLength(), year[j] + "\n", textPane.getStyle("regular"));
Do you simply miss a newline after adding the year of a DVD to the document? I.e.
doc.insertString(doc.getLength(), year[j] + "\n", textPane.getStyle("regular"));

Categories