I have a Label in a Group in SWT and if it contains many lines of text, I would like to make it scrollable vertically. Setting the style parameter with SWT.V_SCROLL doesn't seem to do it. How can I do this?
Label does not support scrolling.
You could use a read only Text control which will scroll:
Text text = new Text(parent, SWT.READ_ONLY | SWT.V_SCROLL);
Here is a way
ScrolledComposite ivScrollComposite = new ScrolledComposite( ivShell, SWT.V_SCROLL );
ivScrollComposite.addControlListener( new ScrollCompositeControlListener() );
ivScrollComposite.setExpandVertical( true );
ivScrollComposite.setExpandHorizontal( true );
ivScrollComposite.setAlwaysShowScrollBars( true );
Composite ivCompositeResults = new Composite( ivScrollComposite, SWT.NONE );
Label ivLabelResults = new Label( ivCompositeResults, SWT.WRAP );
ivScrollComposite.setContent( ivCompositeResults );
ivScrollComposite.setLayout( new FormLayout() );
FormData formData = new FormData();
formData.top = new FormAttachment( 0, 0 );
formData.left = new FormAttachment( 0, 0 );
formData.right = new FormAttachment( 100, 0 );
formData.bottom = new FormAttachment( 100, 0 );
ivCompositeResults.setLayoutData( formData );
ivCompositeResults.setLayout( new FormLayout() );
formData = new FormData();
formData.top = new FormAttachment( 0, 0 );
formData.left = new FormAttachment( 0, 0 );
formData.right = new FormAttachment( 100, 0 );
formData.bottom = new FormAttachment( 100, 0 );
ivLabelResults.setLayoutData( formData );
then
private void resizeScroll()
{
Rectangle r = ivScrollComposite.getClientArea();
ivScrollComposite.setMinSize( ivCompositeResults.computeSize( r.width, SWT.DEFAULT ) );
}
private class ScrollCompositeControlListener extends ControlAdapter
{
#Override
public void controlResized( ControlEvent e )
{
resizeScroll();
}
}
And whenever you change the Label text
ivLabelResults.setText( "some text" );
resizeScroll();
Related
I hope I'm doing this right, first post for me here. I've only been programming with java for a few weeks so this might be really simple but I just cannot figure it out, I tried my java book, youtube, google. I have one panel with textfields and one button, after the button is pressed a new panel should show up with some other textfields. The new panel does show up when the button is clicked, only it stays empty. I'm guessing I have to put some of the code in a different location for it to actually show? Any help would be appreciated, I hope the code is readable, I don't understand where exactly I'm going wrong so figured it would be best to add it completely.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class java03 extends JFrame
{
public static void main ( String args[] )
{
JFrame frame1 = new java03();
frame1.setSize ( 600, 500 );
frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame1.setTitle( "Hour Registration" );
JPanel paneel = new Paneelinvoer();
frame1.setContentPane( paneel );
frame1.setVisible ( true );
}
}
class Paneelinvoer extends JPanel
{
private JTextField naaminvoer, badgeinvoer;
private JTextField maandaginvoer, dinsdaginvoer, woensdaginvoer, donderdaginvoer, vrijdaginvoer, zaterdaginvoer, zondaginvoer;
private JLabel naam, badge, uren;
private JLabel maandag, dinsdag, woensdag, donderdag, vrijdag, zaterdag, zondag;
private JButton knop;
public Paneelinvoer()
{
setLayout( null );
//tekstvakken
naaminvoer = new JTextField( 40 );
naaminvoer.setHorizontalAlignment ( JTextField.LEFT );
badgeinvoer = new JTextField( 4 );
badgeinvoer.setHorizontalAlignment ( JTextField.LEFT );
maandaginvoer = new JTextField( 2 );
maandaginvoer.setHorizontalAlignment ( JTextField.LEFT );
dinsdaginvoer = new JTextField( 2 );
dinsdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
woensdaginvoer = new JTextField( 2 );
woensdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
donderdaginvoer = new JTextField( 2 );
donderdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
vrijdaginvoer = new JTextField( 2 );
vrijdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
zaterdaginvoer = new JTextField( 2 );
zaterdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
zondaginvoer = new JTextField( 2 );
zondaginvoer.setHorizontalAlignment ( JTextField.LEFT );
//labels
naam = new JLabel ( "Naam:" );
badge = new JLabel ( "Badgenummer:" );
uren = new JLabel ( "Uren" );
maandag = new JLabel ( "Maandag" );
dinsdag = new JLabel ( "Dinsdag" );
woensdag = new JLabel ( "Woensdag" );
donderdag = new JLabel ( "Donderdag" );
vrijdag = new JLabel ( "Vrijdag" );
zaterdag = new JLabel ( "Zaterdag" );
zondag = new JLabel ( "Zondag" );
//knoppen
knop = new JButton ( "Accept" );
knop.addActionListener ( new knopHandler () );
//plaats en afmetingen
naam.setBounds( 20, 20, 120, 20 );
naaminvoer.setBounds( 140, 20, 90, 20 );
badge.setBounds( 20, 50, 120, 20 );
badgeinvoer.setBounds( 140, 50, 90, 20 );
uren.setBounds ( 190, 100, 90, 20 );
maandag.setBounds( 20, 120, 120, 20 );
maandaginvoer.setBounds( 160, 120, 90, 20 );
dinsdag.setBounds( 20, 160, 120, 20 );
dinsdaginvoer.setBounds( 160, 160, 90, 20 );
woensdag.setBounds( 20, 200, 120, 20 );
woensdaginvoer.setBounds( 160, 200, 90, 20 );
donderdag.setBounds( 20, 240, 120, 20 );
donderdaginvoer.setBounds( 160, 240, 90, 20 );
vrijdag.setBounds( 20, 280, 120, 20 );
vrijdaginvoer.setBounds( 160, 280, 90, 20 );
zaterdag.setBounds( 20, 320, 120, 20 );
zaterdaginvoer.setBounds( 160, 320, 90, 20 );
zondag.setBounds( 20, 360, 120, 20 );
zondaginvoer.setBounds( 160, 360, 90, 20 );
knop.setBounds ( 100, 400, 100, 20 );
//voeg componenten toe
add ( naaminvoer );
add ( badgeinvoer );
add ( naam );
add ( badge );
add ( uren );
add ( maandag );
add ( dinsdag );
add ( woensdag );
add ( donderdag );
add ( vrijdag );
add ( zaterdag );
add ( zondag );
add ( maandaginvoer );
add ( dinsdaginvoer );
add ( woensdaginvoer );
add ( donderdaginvoer );
add ( vrijdaginvoer );
add ( zaterdaginvoer );
add ( zondaginvoer );
add ( knop );
}
class knopHandler implements ActionListener
{
public void actionPerformed ( ActionEvent e )
{
JFrame frame2 = new JFrame ( "Total Hours" );
frame2.setSize ( 600, 500 );
JPanel uitvoerpanel = new JPanel();
frame2.setContentPane( uitvoerpanel );
frame2.setVisible( true );
String invoerstring1 = maandaginvoer.getText();
int getal1 = Integer.parseInt( invoerstring1 );
String invoerstring2 = dinsdaginvoer.getText();
int getal2 = Integer.parseInt( invoerstring2 );
String invoerstring3 = woensdaginvoer.getText();
int getal3 = Integer.parseInt( invoerstring3 );
String invoerstring4 = donderdaginvoer.getText();
int getal4 = Integer.parseInt( invoerstring4 );
String invoerstring5 = vrijdaginvoer.getText();
int getal5 = Integer.parseInt( invoerstring5 );
String invoerstring6 = zaterdaginvoer.getText();
int getal6 = Integer.parseInt( invoerstring6 );
String invoerstring7 = zondaginvoer.getText();
int getal7 = Integer.parseInt( invoerstring7 );
int resultaat = getal1 + getal2 + getal3 + getal4 + getal5 + getal6 + getal7;
}
}
class uitvoerpanel extends JPanel
{
private JTextField naamvak, badgevak, totaalurenvak;
private JLabel naam, badge, totaaluren;
public uitvoerpanel()
{
setLayout( null );
naamvak = new JTextField ( 20 );
naamvak.setHorizontalAlignment ( JTextField.LEFT );
naamvak.setEditable ( false );
badgevak = new JTextField ( 20 );
badgevak.setHorizontalAlignment ( JTextField.LEFT );
badgevak.setEditable ( false );
totaalurenvak = new JTextField ( 20 );
totaalurenvak.setHorizontalAlignment ( JTextField.LEFT );
totaalurenvak.setEditable ( false );
naam = new JLabel ( "Naam:" );
badge = new JLabel ( "Badgenummer:" );
totaaluren = new JLabel ( "Totaal gewerkte uren:" );
naam.setBounds ( 50,50, 90, 20 );
naamvak.setBounds ( 160, 50, 90, 20);
badge.setBounds ( 50, 90, 90, 20 );
badgevak.setBounds ( 160, 90, 90, 20 );
totaaluren.setBounds ( 50, 130, 90, 20 );
totaalurenvak.setBounds ( 160, 130, 90, 20 );
add ( naamvak );
add ( badgevak );
add ( totaalurenvak );
add ( naam );
add ( badge );
add ( totaaluren );
}
}
}
Your problem lies within knopHandler :
JPanel uitvoerpanel = new JPanel();
You are simply creating a new JPanel; you actually want to create a new uitvoerpanel. Because it extends JPanel, you can do this:
JPanel uitvoerpanel = new uitvoerpanel();
This will fix your mentioned problem. However, you should be aware of the Java naming conventions. It will make your code much easier to read.
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.
i cannot figure out how to get my code to tell when the button is pressed. i was taught poorly, just FYI so any help will need to be greatly detailed. also, i am new to the site so if the post isnt formatted correctly i am sorry.
public static void main(String[] args) {
final JFrame frame = new JFrame("JSlider Demo");
final double odd = 50;
final double bet = 1;
boolean auto = false;
double cash = 5.00;
int cash1 = 0;
JLabel jLabel1 = new JLabel("your cash: " + cash);
JButton b1 = new JButton("GO!");
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
// create odds slider
JSlider odds = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
odds.setMinorTickSpacing(5);
odds.setMajorTickSpacing(25);
odds.setPaintTicks(true);
odds.setPaintLabels(true);
odds.setLabelTable(odds.createStandardLabels(100));
//Create the label table for the odds slider
Hashtable labelTable1 = new Hashtable();
labelTable1.put( new Integer( 50 ), new JLabel("Odds") );
labelTable1.put( new Integer( 0 ), new JLabel("0") );
labelTable1.put( new Integer( 100 ), new JLabel("100") );
odds.setLabelTable( labelTable1 );
odds.setPaintLabels(true);
// create auto bet count slider
JSlider count = new JSlider(JSlider.HORIZONTAL, 1, 101, 1);
count.setMinorTickSpacing(5);
count.setMajorTickSpacing(20);
count.setPaintTicks(true);
count.setPaintLabels(true);
count.setLabelTable(count.createStandardLabels(50));
//Create the label table for auto bet count
Hashtable labelTable3 = new Hashtable();
labelTable3.put( new Integer( 50 ), new JLabel("Auto-bet count") );
labelTable3.put( new Integer( 1 ), new JLabel("1") );
labelTable3.put( new Integer( 101 ), new JLabel("100") );
count.setLabelTable( labelTable3 );
count.setPaintLabels(true);
// create auto bet speed slider
JSlider speed = new JSlider(JSlider.HORIZONTAL, 0, 4, 0);
speed.setMinorTickSpacing(20);
speed.setMajorTickSpacing(1);
speed.setPaintTicks(true);
speed.setPaintLabels(true);
speed.setLabelTable(speed.createStandardLabels(50));
//Create the label table for speed
Hashtable labelTable4 = new Hashtable();
labelTable4.put( new Integer( 2 ), new JLabel("Auto-bet speed") );
labelTable4.put( new Integer( 0 ), new JLabel("1(BPS)") );
labelTable4.put( new Integer( 4 ), new JLabel("5(BPS)") );
speed.setLabelTable( labelTable4 );
speed.setPaintLabels(true);
//sets the GUI
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 200);
frame.getContentPane().add(odds);
frame.getContentPane().add(count);
frame.getContentPane().add(speed);
frame.getContentPane().add(b1);
frame.getContentPane().add(jLabel1);
frame.setVisible(true);
}
Did you tried addActionListener method? For example;
JButton b1 = new JButton("GO!");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// execute this method when the button is pressed
}
});
Docs: https://docs.oracle.com/javase/8/docs/api/java/awt/event/ActionListener.html
You could make your class in which your main method exists, implement ActionListener, and then override the actionPerformed method. For example:
public class A implements ActionListener {
JButton b1 = new JButton("Hello");
b1.addActionListener(this);
public void actionPerformed(ActionEvent e) {
if (e.getSource == b1) {
// do stuff when button b1 is clicked.
}
}
...
}
You can do this for all the buttons in the class. I'm not sure which way of doing this is recommended though, thought I'd add it anyway. :)
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);
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();