jfreechart mutiple datasets to svg image - java

I am using JFreeChart to populate a graph from a csv file, i have managed to create multiple datasets from the file and graphed the data.
The SVG images are being re-written to the "file.svg", so nothing looks pretty at all. Question is, how can i create a single SVG image from the multiple datasets and If only i knew how to get each chart, plot it orderly and draw all of them to a SVG file.
package freechart;
import java.util.*;
import java.text.*;
import java.io.*;
import java.awt.*;
import java.util.StringTokenizer;
import javax.swing.*;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.xy.*;
import org.jfree.data.time.*;
import org.jfree.ui.*;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
public class StockHistoryChart extends JPanel
{
private static final long serialVersionUID = 1L;
// Holds the data
public TimeSeriesCollection dataset = new TimeSeriesCollection();
public TimeSeriesCollection datasetPhysical = new TimeSeriesCollection();
public TimeSeriesCollection datasetS = new TimeSeriesCollection();
public TimeSeriesCollection datasetMM = new TimeSeriesCollection();
public TimeSeriesCollection datasetIF = new TimeSeriesCollection();
public TimeSeriesCollection datasetWP = new TimeSeriesCollection();
// Create a chart
#SuppressWarnings("unused")
private JFreeChart chart;
// Create a panels that can show our chart
#SuppressWarnings("unused")
private ChartPanel panel;
private String stockSymbol;
private String CurrentMonth;
#SuppressWarnings({ "deprecation", "resource", "unused" })
public StockHistoryChart( String filename )
{
try
{
// Get Stock Symbol
this.stockSymbol = filename.substring( 0, filename.indexOf( '.' ) );
// Create time series
TimeSeries PVC = new TimeSeries( "Physical Count", Day.class );
//TimeSeries PV = new TimeSeries( "Physical", Day.class );
TimeSeries STKC = new TimeSeries( "S Count", Day.class );
//TimeSeries STKTP = new TimeSeries( "S", Day.class );
TimeSeries MMTPC = new TimeSeries( "MM Count", Day.class );
//TimeSeries MMTP = new TimeSeries( "MM", Day.class );
TimeSeries IFSC = new TimeSeries( "IF Count", Day.class );
//TimeSeries IFSTP = new TimeSeries( "IF", Day.class );
TimeSeries WPC = new TimeSeries( "WP Count", Day.class );
//TimeSeries WPTP = new TimeSeries( "WP", Day.class );
BufferedReader br = new BufferedReader( new FileReader( filename ) );
String key = br.readLine();
String line = br.readLine();
while( line != null &&
!line.startsWith( "<!--" ) )
{
StringTokenizer st = new StringTokenizer( line, ",", false );
Day day = getDay( st.nextToken() );
double PVCValue = Double.parseDouble( st.nextToken() );
double PVValue = Double.parseDouble( st.nextToken() );
double STKCValue = Double.parseDouble( st.nextToken() );
double STKTPValue = Double.parseDouble( st.nextToken() );
double MMTPCValue = Double.parseDouble( st.nextToken() );
double MMTPValue = Double.parseDouble( st.nextToken() );
double IFSCValue = Double.parseDouble( st.nextToken() );
double IFSTPValue = Double.parseDouble( st.nextToken() );
double WPCValue = Double.parseDouble( st.nextToken() );
double WPTPValue = Double.parseDouble( st.nextToken() );
double TTCValue = Double.parseDouble( st.nextToken() );
double TTAValue = Double.parseDouble( st.nextToken() );
// Add this value to our series'
PVC.addOrUpdate( day, PVCValue );
//PV.addOrUpdate( day, PVValue );
STKC.addOrUpdate( day, STKCValue );
//STKTP.addOrUpdate( day, STKTPValue );
MMTPC.addOrUpdate( day, MMTPCValue );
//MMTP.addOrUpdate( day, MMTPValue );
IFSC.addOrUpdate( day, IFSCValue );
//IFSTP.addOrUpdate( day, IFSTPValue );
WPC.addOrUpdate( day, WPCValue );
//WPTP.addOrUpdate( day, WPTPValue );
TTC.addOrUpdate( day, TTCValue );
//TTA.addOrUpdate( day, TTAValue );
// Read the next day
line = br.readLine();
}
// Build the datasets
dataset.addSeries( PVC );
//dataset.addSeries( PV );
dataset.addSeries( STKC );
//dataset.addSeries( STKTP );
dataset.addSeries(MMTPC);
//dataset.addSeries(MMTP);
dataset.addSeries(IFSC);
//dataset.addSeries(IFSTP);
dataset.addSeries(WPC);
//dataset.addSeries(WPTP);
dataset.addSeries(TTC);
//dataset.addSeries(TTA);
datasetPhysical.addSeries(PVC);
//datasetPhysical.addSeries(PV);
datasetS.addSeries(STKC);
//datasetS.addSeries(STKTP);
datasetMM.addSeries(MMTPC);
//datasetMM.addSeries(MMTP);
datasetIF.addSeries(IFSC);
//datasetIF.addSeries(IFSTP);
datasetWP.addSeries(WPC);
//datasetWP.addSeries(WPTP);
dataset.setDomainIsPointsInTime(true);
//datasetPhysical.setDomainIsPointsInTime(true);
datasetS.setDomainIsPointsInTime(true);
//datasetS.setDomainIsPointsInTime(true);
datasetMM.setDomainIsPointsInTime(true);
//datasetMM.setDomainIsPointsInTime(true);
datasetIF.setDomainIsPointsInTime(true);
//datasetIF.setDomainIsPointsInTime(true);
datasetWP.setDomainIsPointsInTime(true);
//datasetWP.setDomainIsPointsInTime(true);
JFreeChart summary = buildChart( dataset, "Figures Summary Chart", true );
JFreeChart Physical = buildChart( datasetPhysicalVouchers, "Physical Vouchers count", false );
JFreeChart S = buildChart( datasetSTK, "S count", false );
JFreeChart MM = buildChart( datasetMM, "MM count", true );
JFreeChart IF = buildChart( datasetIFS, "IF (count & values)", false );
JFreeChart WP = buildChart( datasetWebPortal, "WP count", true );
// Create this panel
this.setLayout( new GridLayout( 2, 2 ) );
this.add( new ChartPanel( summary ) );
this.add( new ChartPanel( Physical ) );
this.add( new ChartPanel( S ) );
this.add( new ChartPanel( MM ) );
this.add( new ChartPanel( IF ) );
this.add( new ChartPanel( WP ) );
}
catch( Exception e )
{
e.printStackTrace();
} }
private JFreeChart buildChart( TimeSeriesCollection dataset, String title, boolean endPoints )
{
// Create the chart
JFreeChart chart = ChartFactory.createTimeSeriesChart(
title,
"Date", "Totals",
dataset,
true,
true,
false
);
// Setup the appearance of the chart
chart.setBackgroundPaint(Color.white);
XYPlot plot = (XYPlot) chart.getXYPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
// Display data points or just the lines?
if( endPoints )
{
XYItemRenderer renderer = plot.getRenderer();
if (renderer instanceof StandardXYItemRenderer) {
StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;
rr.setBaseShapesVisible(true);
rr.setBaseShapesFilled(true);
rr.setDrawSeriesLineAsPath(true);
rr.setSeriesPaint(0, Color.blue.brighter());
rr.setSeriesVisible(0, true); // default
rr.setSeriesVisibleInLegend(0, true); // default
}
}
// Tell the chart how we would like dates to read
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("dd-MMM-yy"));
// creating SVG
File svgFile = new File("file.svg");
Rectangle2D r2d = new Rectangle2D.Double (
100.0,
100.0,
30.0,
200.0
);
// write it to file
try {
exportChartAsSVG(chart, r2d.getBounds(), svgFile);
// TODO: notify the user the file has been saved (e.g. status bar)
System.out.println("Figured saved as " + svgFile.getAbsolutePath());
} catch (IOException e) {
System.err.println("Error saving file:\n" + e.getMessage());
}
return chart;
}
void exportChartAsSVG(JFreeChart chart, Rectangle bounds, File svgFile) throws IOException {
// Get a DOMImplementation and create an XML document
DOMImplementation domImpl =
GenericDOMImplementation.getDOMImplementation();
Document document = domImpl.createDocument(null, "svg", null);
// Create an instance of the SVG Generator
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
// draw the chart in the SVG generator
chart.draw(svgGenerator, bounds);
// Write svg file
OutputStream outputStream = new FileOutputStream(svgFile);
Writer out = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(out, true /* use css */);
outputStream.flush();
outputStream.close();
}
// Main method
public static void main( String[] args )
{
StockHistoryChart shc = new StockHistoryChart("file.csv");
JFrame frame = new JFrame(shc.CurrentMonth());
frame.getContentPane().add( shc, BorderLayout.CENTER );
frame.setSize( 640, 480 );
frame.setVisible( true );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}

I resolved this problem I was facing (not able to create a SVG file with all charts), by removing the exportChartAsSVG() and calling the SVG Generator from the main function like so;
// Get a DOMImplementation.
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document.
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
// Create an instance of the SVG Generator.
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
// Ask the shc to render into the SVG Graphics2D implementation.
shc.paint(svgGenerator);
// Create a SVG file to populate our Frame
File svgFile = new File ("svgfile.svg");
FileOutputStream fos = new FileOutputStream(svgFile);
// Finally, stream out SVG to the standard output using
// UTF-8 encoding.
boolean useCSS = true; // we want to use CSS style attributes
Writer out = new OutputStreamWriter(fos, "UTF-8");
svgGenerator.stream(out, useCSS);
out.flush();

Related

XYAreaChart the colors of the shapes on the chart merge

Using setSeriesPaint, I set the colors for the series: red and black. You can see the problem in the picture:
Instead of black, there is something in between black and red, because, apparently, there is an overlay on red. How to solve this problem?
TimeSeries all = new TimeSeries( "All" );
TimeSeries heal = new TimeSeries( "Heal" );
Document document = Jsoup.connect(. . .).get();
Elements h = document.select("tr");
int a = 0;
for(int i = h.size()-1;i>1;i--) {
String[] mas = String.valueOf(h.get(i).text()).split(" ");
SimpleDateFormat ft = new SimpleDateFormat ("dd.MM.yyyy");
Date da = ft.parse(mas[0]);
Day d = new Day(da);
all.add(d, Double.parseDouble(mas[10]));
heal.add(d, Double.parseDouble(mas[4]));
}
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(all);
dataset.addSeries(heal);
JFreeChart lineChartObject = ChartFactory.createXYAreaChart(. . .);
XYPlot plot = (XYPlot) lineChartObject.getPlot();
plot.setBackgroundPaint(Color.white);
plot.setDomainGridlinePaint(Color.black);
plot.setRangeGridlinePaint(Color.black);
DateAxis domain = new DateAxis("Дата");
plot.setDomainAxis(domain);
XYAreaRenderer movingAverageRenderer = new XYAreaRenderer();
movingAverageRenderer.setUseFillPaint(false);
movingAverageRenderer.setSeriesPaint(0, Color.red);
movingAverageRenderer.setSeriesPaint(1, Color.black);
plot.setRenderer(movingAverageRenderer);
int width = 640;
int height = 480;
File lineChart = new File( "C://gr", "graph.jpeg");
ChartUtilities.saveChartAsJPEG(lineChart ,lineChartObject, width ,height);

Closing JFrames with Windows event [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm writing a simple program where I have multiple JFrame windows but when I use multiple they stack and I've tried to set their visibility to false that isn't working so I'm trying to simulate a close so the frames don't stack on top of each other but I don't know what to use since my program isn't a window.
public void close(){
WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
on the this I keep getting a error of
incompatible types: Program1 cannot be converted to Window
If someone has a better way of doing this please let me know I cant find a better way that's working for me.
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
//http://vignette4.wikia.nocookie.net/bioshock/images/b/ba/Monu_Island-Skyline01.png/revision/latest?cb=20130521042740
public class Program1 {
public String welcome() {
Date date = new Date();
File music = new File("BioShock_Infinite_-_BioShock_Infinite_-_After_Youv.wav");
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(music));
clip.start();
} catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) {
}
JFrame welcomeJFrame = new JFrame("Welcome to Daimeon's ESCAPE!");
JLabel backgroundImageJLabel = new JLabel();
backgroundImageJLabel.setIcon(new ImageIcon("Monu_Island-Skyline01.png"));
JLabel gameNameJLabel = new JLabel("An Escape from Monument Island!");
JLabel welcomeJLabel = new JLabel("Welcome to Daimeon's Escape Game.");
JLabel currentDateJLabel = new JLabel("" + date.toString() + "");
JPanel Panel = new JPanel();
welcomeJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
currentDateJLabel.setBounds(400, 700, 800, 60);
currentDateJLabel.setFont(new Font("Andes", Font.BOLD, 60));
currentDateJLabel.setHorizontalAlignment(JLabel.CENTER);
gameNameJLabel.setBounds(350, 15, 900, 60);
gameNameJLabel.setForeground(Color.red);
gameNameJLabel.setFont(new Font("Andes", Font.BOLD, 60));
gameNameJLabel.setHorizontalAlignment(JLabel.CENTER);
welcomeJLabel.setBounds(450, 75, 700, 35);
welcomeJLabel.setFont(new Font("Andes", Font.BOLD, 30));
welcomeJLabel.setHorizontalAlignment(JLabel.CENTER);
Panel.add(backgroundImageJLabel);
backgroundImageJLabel.add(gameNameJLabel);
backgroundImageJLabel.add(welcomeJLabel);
backgroundImageJLabel.add(currentDateJLabel);
welcomeJFrame.add(Panel);
welcomeJFrame.setSize(1828, 1080);
welcomeJFrame.setLocationRelativeTo(null);
welcomeJFrame.setVisible(true);
String name = "";
name = getUsers_Name(name);
gretting(name);
return name;
}
public String getUsers_Name(String name) {
return name = JOptionPane.showInputDialog(null, "Hey there please sign-in with your name:");
}
public void gretting(String name) {
JOptionPane.showMessageDialog(null, "Well howdy there " + name + " welcome to the website."
+ "\nHeres a run down of what this is all about.");
JOptionPane.showMessageDialog(null,
name + "\n you are stuck in the Monument on Monument island trying to escape"
+ "\n from songbrid and from the sherpards men, both are trying to kill"
+ " you.");
JOptionPane.showMessageDialog(null,
"\t \t \t Basic Registration Fees\n" + "$2.50 : Dont run before you can walk "
+ "( Ages 0 - 4 )\n" + "$5.00 : Felling courageous " + "( Ages 4 - 12 )\n"
+ "$7.50 : Wont be a walk in the park " + "( Ages 13 - 17 )\n"
+ "$9.75 : Expert " + "( Ages 18+ )\n" + "$1.25 : Additional Items "
+ "( Lock Pick, Silver Eagle or Creature )",
"Fees", JOptionPane.WARNING_MESSAGE, null);
JOptionPane.showMessageDialog(null,
"Hey " + name + ",\n" + "Please continue to start\n" + "registration",
"Please Continue", JOptionPane.WARNING_MESSAGE, null);
}
public void start_regstration(ArrayList users_Information) {
int[] user_number_information = new int[5];
int addons = 0;
double[] user_dep_amount = new double[5];
users_Information.add(get_user_alias(users_Information));
users_Information.add(get_user_gender(users_Information));
users_Information.add(get_user_atrological_sign(users_Information));
user_number_information[0] = get_user_birth_year(users_Information);
user_dep_amount[0] = get_int_player_dep_amount(users_Information);
user_number_information[2] = get_addon_1(users_Information);
user_number_information[3] = get_addon_2(users_Information);
user_number_information[4] = get_addon_3(users_Information);
confirm(users_Information, user_number_information);
compute_total_addons(user_number_information);
feature_recipt(users_Information, user_number_information);
pre_total_reg_fee_recipt(users_Information, user_number_information);
user_number_information[1] = get_players_age(user_number_information);
user_dep_amount[1] = players_age_reg_fee(user_number_information);
user_dep_amount[2] = daimeons_round_to_penny(user_number_information);
final_player_fee_amount(users_Information, user_dep_amount);
exit_m();
}
public String get_user_alias(ArrayList users_Information) {
String alias;
alias = (String) JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(0) + " what is your alias?", "Alias",
JOptionPane.QUESTION_MESSAGE, null, null, "Captain");
return alias;
}
public String get_user_gender(ArrayList users_Information) {
String user_gender;
user_gender = (String) JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(1) + " what is your gender?", "Gender",
JOptionPane.QUESTION_MESSAGE, null, null, "Male");
return user_gender;
}
public String get_user_atrological_sign(ArrayList users_Information) {
close();
String astro_sign;
astro_sign = (String) JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(1) + " what's your astrological sign?",
"Astrological Sign", JOptionPane.QUESTION_MESSAGE, null, null, "Gemini");
return astro_sign;
}
public int get_user_birth_year(ArrayList users_Information) {
int bY;
String input = JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(1) + " what is your birth year?");
bY = Integer.parseInt(input);
return bY;
}
public double get_int_player_dep_amount(ArrayList users_Information) {
double user_dep;
Object input = JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(1) + " how much would you like to deposit?",
"Deposit", JOptionPane.QUESTION_MESSAGE, null, null, "1234.56");
user_dep = Double.parseDouble((String) input);
return user_dep;
}
public int get_addon_1(ArrayList users_Information) {
return 1;
}
public int extraFeatureTreasure( String alias )
{
//Title bar
JFrame getExtraFeaturesJFrame = new JFrame("User's Extra Features" );
//Set background
JLabel backgroundImageJLabel = new JLabel( );
backgroundImageJLabel.setIcon( new ImageIcon( "VV.jpg" ) );
//Treasure
JLabel treasureJLabel = new JLabel( );
//Creatures
JLabel creature1JLabel = new JLabel( );
JLabel creature2JLabel = new JLabel( );
//Key
JLabel keyJLabel = new JLabel( );
//Second panel
JPanel theSecondPanel = new JPanel( );
getExtraFeaturesJFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
treasureJLabel.setIcon( new ImageIcon( "lovee.gif" ) );
creature1JLabel.setIcon( new ImageIcon( "gun.gif" ) );
creature2JLabel.setIcon( new ImageIcon( "creature2.gif" ) );
keyJLabel.setIcon( new ImageIcon( "fashionkey.jpg" ) );
//Extra feature price label
JLabel extraFeatureTextJLabel = new JLabel( "Extra Features : $1.25 ea" );
//Treasure
JLabel treasureTextJLabel = new JLabel( "Treasure" );
JLabel treasureDescriptionText0JLabel = new JLabel( "Extra treasures are some of the" );
JLabel treasureDescriptionText1JLabel = new JLabel( "latest fashion trends!" );
//Creature
JLabel creature1TextJLabel = new JLabel( "The Guy With The Gun" );
JLabel creature2TextJLabel = new JLabel( "Unfashionable Shopaholics" );
JLabel creature1TextDescription0JLabel = new JLabel( "Beware of the creatures!" );
JLabel creature1TextDescription1JLabel = new JLabel( "if you encounter then at any point" );
JLabel creature1TextDescription2JLabel = new JLabel( "you will lose all your precious shops" );
//Key
JLabel keyTextJLabel = new JLabel( "Fashion Key" );
JLabel keyTextDescription0JLabel = new JLabel( "Fashion keys are the most" );
JLabel keyTextDescription1JLabel = new JLabel( "special features in this game" );
JLabel keyTextDescription2JLabel = new JLabel( "since they add the final touch" );
JLabel keyTextDescription3JLabel = new JLabel( "to your perfect outfit" );
//Extra feature label characteristics
extraFeatureTextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 40 ) );
extraFeatureTextJLabel.setForeground( new Color( 250, 150, 200 ));
extraFeatureTextJLabel.setHorizontalAlignment( JLabel.CENTER );
//Extra feature label characteristics
treasureTextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 25 ) );
treasureDescriptionText0JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
treasureDescriptionText1JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
//Extra feature label characteristics
creature1TextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 25 ) );
creature1TextDescription0JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
creature1TextDescription1JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
creature1TextDescription2JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
//Extra feature label characteristics
creature2TextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 25 ) );
//Extra feature label characteristics
keyTextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 25 ) );
keyTextDescription0JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
keyTextDescription1JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
keyTextDescription2JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
keyTextDescription3JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
//Extra feature label characteristics
extraFeatureTextJLabel.setBounds( 450,1,700,40 );
treasureTextJLabel.setBounds( 400,315,500,50 );
treasureJLabel.setBounds( 200,35,500,300 );
treasureDescriptionText0JLabel.setBounds( 200,345,500,50 );
treasureDescriptionText1JLabel.setBounds( 200,365,500,50 );
keyTextJLabel.setBounds( 1195,284,500,50 );
keyJLabel.setBounds( 1132,45,400,250 );
keyTextDescription0JLabel.setBounds( 770,20,400,250 );
keyTextDescription1JLabel.setBounds( 770,40,400,250 );
keyTextDescription2JLabel.setBounds( 770,60,400,250 );
keyTextDescription3JLabel.setBounds( 770,80,400,250 );
creature1TextJLabel.setBounds( 300,645,500,50 );
creature2TextJLabel.setBounds( 980,645,545,50 );
creature1TextDescription0JLabel.setBounds( 200,675,500,50 );
creature1TextDescription1JLabel.setBounds( 200,695,500,50 );
creature1TextDescription2JLabel.setBounds( 200,715,500,50 );
creature1JLabel.setBounds( 200,390,500,300 );
creature2JLabel.setBounds( 897,377,500,300 );
//Add all labels to the pannel
theSecondPanel.add(backgroundImageJLabel);
backgroundImageJLabel.add(extraFeatureTextJLabel);
backgroundImageJLabel.add(treasureTextJLabel);
backgroundImageJLabel.add(treasureJLabel);
backgroundImageJLabel.add(treasureDescriptionText0JLabel);
backgroundImageJLabel.add(treasureDescriptionText1JLabel);
backgroundImageJLabel.add(creature1TextJLabel);
backgroundImageJLabel.add(creature1JLabel);
backgroundImageJLabel.add(creature2TextJLabel);
backgroundImageJLabel.add(creature2JLabel);
backgroundImageJLabel.add(creature1TextDescription0JLabel);
backgroundImageJLabel.add(creature1TextDescription1JLabel);
backgroundImageJLabel.add(creature1TextDescription2JLabel);
backgroundImageJLabel.add(keyTextJLabel);
backgroundImageJLabel.add(keyJLabel);
backgroundImageJLabel.add(keyTextDescription0JLabel);
backgroundImageJLabel.add(keyTextDescription1JLabel);
backgroundImageJLabel.add(keyTextDescription2JLabel);
backgroundImageJLabel.add(keyTextDescription3JLabel);
//Add panel to the frame
getExtraFeaturesJFrame.add(theSecondPanel);
getExtraFeaturesJFrame.setSize ( 1280, 900 );
getExtraFeaturesJFrame.setLocationRelativeTo( null );
getExtraFeaturesJFrame.setVisible( true );
//Ask for user's amount to deposit, output changes from a String to an Object
//Image 2
Object getTreasures = JOptionPane.showInputDialog( null,
"Dear " + alias + "\u2661,\n"
+"Please enter the number of treasures\n"
+"you wish to acquire",
"\u2661Number of Treasures\u2661",
JOptionPane.PLAIN_MESSAGE,
icon, null,
"0");
//TypeCast, converts returned Object to a string
getUserTreasures = (String)getTreasures;
//Converts returned String to an int
numberOfTreasures = Integer.parseInt( getUserTreasures );
return numberOfTreasures;
}
public int get_addon_2(ArrayList users_Information) {
return 2;
}
public int get_addon_3(ArrayList users_Information) {
return 3;
}
public void confirm(ArrayList users_Information, int[] user_number_information) {
}
public double compute_total_addons(int[] user_number_information) {
return 1.0;
}
public void feature_recipt(ArrayList users_Information, int[] user_number_information) {
}
public void pre_total_reg_fee_recipt(ArrayList users_Information,
int[] user_number_information) {
}
public int get_players_age(int[] user_number_information) {
return 1;
}
public double players_age_reg_fee(int[] user_number_information) {
return 1.0;
}
public double daimeons_round_to_penny(int[] user_number_information) {
return 1.0;
}
public void final_player_fee_amount(ArrayList users_Information, double[] user_dep_amount) {
}
public void exit_m() {
System.exit(0);
}
public void close() {
// TODO: Fix:
// WindowEvent winClosingEvent = new WindowEvent(this,
// WindowEvent.WINDOW_CLOSING);
// Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
public static void main(String[] args) {
Program1 methods = new Program1();
ArrayList<String> users_Information = new ArrayList<>();
users_Information.add(methods.welcome());
methods.start_regstration(users_Information);
methods.extraFeatureTreasure();
}
}
You didn't put enough information and explanation to your exact problem but here is what I can help you with :
To make a JFrame close when you click on the OS provided close button (at the top right corner usually) this will work for you (put it in the class that controlls your JFrame which also extends JFrame class ) :
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
To close a JFrame on an a specific event use :
this.dispose();
To make a JFrame invisible use this :
this.setVisible(false);

How to center objects within a panel that is already laid out with borderlayout

I have searched this site, other sites, and my textbook and cannot come up with a solution so here goes:
I have a simple temp. conversion program which functions just fine however I would like to make my layout more appealing and more similar to what is asked for in the procedures.
Right now it looks like this:
And I want it to look like this:
Difference being the Input and Output fields are centered in the desired output.
Here is my program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Convert extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel convertFrom, convertTo, top, bottom;
private JLabel label3, label4;
private JTextField temperature1, temperature2;
private ButtonGroup radioFrom, radioTo;
private JRadioButton celsiusBoxTo, fahrenheitBoxTo, kelvinBoxTo, celsiusBoxFrom, fahrenheitBoxFrom, kelvinBoxFrom;
public Convert(){
fahrenheitBoxFrom = new JRadioButton( "Fahrenheit", true );
celsiusBoxFrom = new JRadioButton( "Celsius", false );
kelvinBoxFrom = new JRadioButton( "Kelvin", false );
radioFrom = new ButtonGroup();
radioFrom.add( fahrenheitBoxFrom );
radioFrom.add( celsiusBoxFrom );
radioFrom.add( kelvinBoxFrom );
label3 = new JLabel( "Input" );
label4 = new JLabel( "Output" );
fahrenheitBoxTo = new JRadioButton( "Fahrenheit", false );
celsiusBoxTo = new JRadioButton( "Celsius", true );
kelvinBoxTo = new JRadioButton( "Kelvin", false );
radioTo = new ButtonGroup();
radioTo.add( fahrenheitBoxTo );
radioTo.add( celsiusBoxTo );
radioTo.add( kelvinBoxTo );
convertFrom = new JPanel();
convertFrom.setLayout( new GridLayout( 4, 1 ) );
convertFrom.add(new JLabel( "Input Scale" ));
convertFrom.add( fahrenheitBoxFrom );
convertFrom.add( celsiusBoxFrom );
convertFrom.add( kelvinBoxFrom );
convertTo = new JPanel();
convertTo.setLayout( new GridLayout( 4, 1 ) );
convertTo.add(new JLabel( "Output Scale" ));
convertTo.add( fahrenheitBoxTo );
convertTo.add( celsiusBoxTo );
convertTo.add( kelvinBoxTo );
temperature1 = new JTextField( 10 );
top = new JPanel();
top.setLayout(new GridLayout(1, 2));
top.add(label3);
top.add(temperature1);
temperature1.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent event ){
int convertTemp, temp;
temp = Integer.parseInt( ( ( JTextField ) event.getSource() ).getText() );
if ( fahrenheitBoxFrom.isSelected() && celsiusBoxTo.isSelected() ){
convertTemp = ( int ) ( 5.0f / 9.0f * ( temp - 32 ) );
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( fahrenheitBoxFrom.isSelected() && kelvinBoxTo.isSelected() ){
convertTemp = ( int ) ( 5.0f / 9.0f * ( temp - 32 ) + 273 );
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( celsiusBoxFrom.isSelected() && fahrenheitBoxTo.isSelected() ){
convertTemp = ( int ) ( 9.0f / 5.0f * temp + 32 );
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( celsiusBoxFrom.isSelected() && kelvinBoxTo.isSelected()){
convertTemp = temp + 273;
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( kelvinBoxFrom.isSelected() && celsiusBoxTo.isSelected()){
convertTemp = temp - 273;
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( kelvinBoxFrom.isSelected() && fahrenheitBoxTo.isSelected()){
convertTemp = ( int ) ( 9.0f / 5.0f * ( temp - 273 ) + 32 );
temperature2.setText( String.valueOf( convertTemp ) );
}
}
});
temperature2 = new JTextField( 10 );
temperature2.setEditable( false );
bottom = new JPanel();
bottom.setLayout(new GridLayout(1, 2));
bottom.add(label4);
bottom.add(temperature2);
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add( top, BorderLayout.NORTH );
container.add( convertFrom, BorderLayout.WEST );
container.add( convertTo, BorderLayout.EAST );
container.add( bottom, BorderLayout.SOUTH );
setSize( 350,250);
setVisible( true );
}
public static void main ( String args[] ){
Convert application = new Convert();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
BoxLayout can place components centered. BoxLayout respects the setAlignmentX property of a component (see also the answers to this question).
One caveat though: you'll have to manage a component's maximum size if it is configured to take the full available width of the window (like a text-field is). Here is how you can do it for the "bottom" panel:
javax.swing.Box bottomBox = Box.createHorizontalBox();
bottom = new JPanel();
bottomBox.add(bottom);
bottom.setAlignmentX(java.awt.Component.CENTER_ALIGNMENT);
bottom.add(label4);
temperature2.setMaximumSize(temperature2.getPreferredSize());
bottom.add(temperature2);
...
container.add( bottomBox, BorderLayout.SOUTH );
You can do a similar thing for the "top" panel.
You can use GridBagLayout for this task. it will easily place your components in a 4x6 grid and you can pretty much specify the desired spacing between components using GridBagConstraints. I would use this layout.

How to represent 3As as "AAA" or 3Bs as BBB in Java

I'm writing a Java code to represent the grades that students achieved in an exam. When you input the number 10 in the bar labelled # of grade As, and input the number 20 in the bar labelled # of grade Bs, and do it until you reach # of grade E, and then you click on the label "Display bar chart", you get a chart with the output Grade As : 10 ....Grade Bs : 20............Grade E : something. My question to you is this. If, instead of having the output Grade A : 10, I want the output AAAAAAAAAA (ie the letter A written out 10 times), how do I do it? I've thought about it all day but still can't come up with an answer.
Second (related) question: if NO students achieve any particular grade (let's say nobody scored an A), then there should be no grade letters displayed in that bar (the bar for grade A). Could someone please tell me how I should modify my code to take this into account? Here is my code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class GradeChart extends JFrame
implements ActionListener {
private JTextField gradeAField = new JTextField( 5 );
private JTextField gradeBField = new JTextField( 5 );
private JTextField gradeCField = new JTextField( 5 );
private JTextField gradeDField = new JTextField( 5 );
private JTextField gradeEField = new JTextField( 5 );
private int gradeAs;
private int gradeBs;
private int gradeCs;
private int gradeDs;
private int gradeEs;
private JButton displayChartButton = new JButton( "Display bar chart" );
private JButton displayDataFieldsButton = new JButton( "Clear data fields" );
private JPanel chartPanel = new JPanel();
private Color chartPanelColor = Color.cyan;
private final Font labelFont = new Font( "Serif", Font.BOLD, 16 );
// Various fixed coordinates and dimensions
private final int chartLeftXA = 30;
private final int chartLeftXB = 30;
private final int chartLeftXC = 30;
private final int chartLeftXD = 30;
private final int chartLeftXE = 30;
private final int chartTopYA = 50;
private final int chartTopYB = 102;
private final int chartTopYC = 154;
private final int chartTopYD = 206;
private final int chartTopYE = 258;
public static void main( String[] args ) {
GradeChart chart = new GradeChart();
chart.setSize( 550, 550 );
chart.createGUI();
chart.setVisible( true );
}
private void createGUI() {
// Set up main window characteristics
setDefaultCloseOperation( EXIT_ON_CLOSE );
Container window = getContentPane();
window.setLayout( new FlowLayout() );
JLabel gradeAFieldLabel = new JLabel( "# of grade As:" );
gradeAFieldLabel.setFont( labelFont );
window.add( gradeAFieldLabel );
window.add( gradeAField );
JLabel gradeBFieldLabel = new JLabel( "# of grade Bs:" );
gradeBFieldLabel.setFont( labelFont );
window.add( gradeBFieldLabel );
window.add( gradeBField );
JLabel gradeCFieldLabel = new JLabel( "# of grade Cs:" );
gradeCFieldLabel.setFont( labelFont );
window.add( gradeCFieldLabel );
window.add( gradeCField );
JLabel gradeDFieldLabel = new JLabel( "# of grade Ds:" );
gradeDFieldLabel.setFont( labelFont );
window.add( gradeDFieldLabel );
window.add( gradeDField );
JLabel gradeEFieldLabel = new JLabel( "# of grade Es:" );
gradeEFieldLabel.setFont( labelFont );
window.add( gradeEFieldLabel );
window.add( gradeEField );
window.add( displayChartButton );
displayChartButton.addActionListener( this );
window.add( displayDataFieldsButton );
displayDataFieldsButton.addActionListener( this );
chartPanel.setPreferredSize( new Dimension( 450, 300 ) );
chartPanel.setBackground( chartPanelColor );
window.add( chartPanel );
}
public void actionPerformed( ActionEvent e ) {
if ( e.getSource() == displayChartButton ) {
checkAndRecordData();
Graphics g = chartPanel.getGraphics();
g.setColor(Color.white);
g.fillRect(20,20,410,52);
g.setColor(Color.black);
g.drawRect(20,20,410,52);
g.setColor( Color.black );
g.drawString( "Grade As: " + gradeAs, chartLeftXA, chartTopYA );
g.setColor(Color.white);
g.fillRect(20,72,410,52);
g.setColor(Color.black);
g.drawRect(20,72,410,52);
g.setColor( Color.black );
g.drawString( "Grade Bs: " + gradeBs, chartLeftXB, chartTopYB );
g.setColor(Color.white);
g.fillRect(20,124,410,52);
g.setColor(Color.black);
g.drawRect(20,124,410,52);
g.setColor( Color.black );
g.setColor( Color.black );
g.drawString( "Grade Cs: " + gradeCs, chartLeftXC, chartTopYC );
g.setColor(Color.white);
g.fillRect(20,176,410,52);
g.setColor(Color.black);
g.drawRect(20,176,410,52);
g.setColor( Color.black );
g.setColor( Color.black );
g.drawString( "Grade Ds: " + gradeDs, chartLeftXD, chartTopYD );
g.setColor(Color.white);
g.fillRect(20,228,410,52);
g.setColor(Color.black);
g.drawRect(20,228,410,52);
g.setColor( Color.black );
g.setColor( Color.black );
g.drawString( "Grade Es: " + gradeEs, chartLeftXE, chartTopYE );
}
if ( e.getSource() == displayDataFieldsButton ) {
gradeAField.setText("");
gradeBField.setText("");
gradeCField.setText("");
gradeDField.setText("");
gradeEField.setText("");
}
} // End of actionPerformed
private void checkAndRecordData() {
int tempAs = 0;
int tempBs = 0;
int tempCs = 0;
int tempDs = 0;
int tempEs = 0;
tempAs = Integer.parseInt( gradeAField.getText() );
tempBs = Integer.parseInt( gradeBField.getText() );
tempCs = Integer.parseInt( gradeCField.getText() );
tempDs = Integer.parseInt( gradeDField.getText() );
tempEs = Integer.parseInt( gradeEField.getText() );
gradeAs = tempAs;
gradeBs = tempBs;
gradeCs = tempCs;
gradeDs = tempDs;
gradeEs = tempEs;
}
Use a loop:
String longString = "";
for (int i=0; i<numOfLetter; i++) {
longString += gradeLetter;
}
Or, if you have Apache Commons available:
String longString = StringUtils.repeat(gradeLetter, numOfLetter);
If you only need a few:
String someAs = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".substring(0, length);

Add values to a specified series in a DynamicTimeSeriesCollection

The program will receive data every second and draw them on time Series chart. However, once I create two series, I cannot add new value to it. It displays a straight line only.
How do I append data to a specified series? I.e. YYY. Based on this example, here's what I'm doing:
...
// Data set.
final DynamicTimeSeriesCollection dataset =
new DynamicTimeSeriesCollection( 2, COUNT, new Second() );
dataset.setTimeBase( new Second( 0, 0, 0, 1, 1, 2011 ) );
dataset.addSeries( gaussianData(), 0, "XXX" );
dataset.addSeries( gaussianData(), 1, "YYY" );
// Chart.
JFreeChart chart = createChart( dataset );
this.add( new ChartPanel( chart ), BorderLayout.CENTER );
// Timer.
timer = new Timer( 1000, new ActionListener() {
#Override
public void actionPerformed ( ActionEvent e ) {
dataset.advanceTime();
dataset.appendData( new float[] { randomValue() } );
}
} );
...
private JFreeChart createChart ( final XYDataset dataset ) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
TITLE, "", "", dataset, true, true, false );
final XYPlot plot = result.getXYPlot();
ValueAxis domain = plot.getDomainAxis();
domain.setAutoRange( true );
ValueAxis range = plot.getRangeAxis();
range.setRange( -MINMAX, MINMAX );
return result;
}
Assuming you started from here, you've specified a dataset with two series, but you're only appending one value with each tick of the Timer. You need two values for each tick. Here's how I modified the original to get the picture below:
final DynamicTimeSeriesCollection dataset =
new DynamicTimeSeriesCollection(2, COUNT, new Second());
...
dataset.addSeries(gaussianData(), 0, "Human");
dataset.addSeries(gaussianData(), 1, "Alien");
...
timer = new Timer(FAST, new ActionListener() {
// two values appended with each tick
float[] newData = new float[2];
#Override
public void actionPerformed(ActionEvent e) {
newData[0] = randomValue();
newData[1] = randomValue();
dataset.advanceTime();
dataset.appendData(newData);
}
});

Categories