Graph plotting in Java Swing only draws points - java

I'm currently working on a program where certain numerical variables, which evolve over time, have their value displayed on each iteration. That works well enough, but now I want to plot a graph that shows their evolution over time.
So, I looked into an example of code for plotting graphs in Swing. My final code looks like this:
public class Populus3 extends JPanel
{
public static void main(String[] args) throws IOException {
final Populus3 pop = new Populus3();
JFrame f = new JFrame(); //where I want to plot the graph
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new GraphingData());
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
frame = new JFrame("Animation Frame"); //where I'm running animation for another element of the program
frame.add(pop, BorderLayout.CENTER);
frame.setSize(graphSize, graphSize);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//insert all sort of things
}
public void paint(Graphics g)
{
super.paint(g);
paintCell(g, 1);
Toolkit.getDefaultToolkit().sync(); // necessary for linux users to draw and animate image correctly
g.dispose();
}
public void actionPerformed(ActionEvent e) {
repaint();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < particleType.length; i++)
paintCell(g, i); //a method that draws a small circle for the animation panel
}
public static class GraphingData extends JPanel {
int[] data = {
21, 14, 18, 03, 86, 88, 74, 87, 54, 77,
61, 55, 48, 60, 49, 36, 38, 27, 20, 18
};
final int PAD = 20;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
// Draw ordinate.
g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
// Draw abcissa.
g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
double xInc = (double)(w - 2*PAD)/(data.length-1);
double scale = (double)(h - 2*PAD)/getMax();
// Mark data points.
g2.setPaint(Color.red);
for(int i = 0; i < data.length; i++) {
double x = PAD + i*xInc;
double y = h - PAD - scale*data[i];
g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
}
}
private int getMax() {
int max = -Integer.MAX_VALUE;
for(int i = 0; i < data.length; i++) {
if(data[i] > max)
max = data[i];
}
return max;
}
}
}
Now, the animation panel works just fine. The graph panel, on the other hand...when I run the program, it displays a bunch of red dots, without lines to connect them. What am I doing wrong?

In addition to #Hovercraft's helpful suggestions, also consider these other approaches:
Accumulate the points in a GeneralPath that may be rendered as required, for example.
Connect the points using repeated calls to drawLine() using a suitable coordinate system, outlined here.
Look at JFreeChart.

Your code confuses me:
You override both paint and paintComponent for your Populus3 JPanel -- why? You should only override paintComponent unless you absolutely have to have your drawing affect a component's children and borders.
You dispose of the Graphics object passed into paint -- a very dangerous thing to do. You should never dispose of a Graphics object given to you by the JVM, only Graphics objects that you yourself create.
You repeatedly call a method not defined here for us, paintCell(...).
I've never heard of the need for Toolkit.getDefaultToolkit().sync(); for Swing applications. Do you have a reference for this need?
You mention "animation" but I see no animation code.
In your GraphingData class's paintComponent method you fill ellipses in your for loop, but you don't connect them with lines ever, so it shouldn't be surprising that you're only seeing dots in your graph and no lines.
Consider isolating your problem more and posting an sscce, a minimal test program that we can compile, run, modify and correct and that shows us your problem, but has no extra code not related to the problem or required for demonstration.

The following code demonstrates a real-time Java chart using XChart where the line is updated as the data evolves over time. Creating real-time charts is as simple as calling updateXYSeries for one or more series objects through the XYChart instance and triggering a redraw of the JPanel containing the chart. This works for all chart types including XYChart, CategoryChart, BubbleChart and PieChart, for which example source code can be found here: https://github.com/timmolter/XChart/tree/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/realtime. Examples demonstrate using the SwingWrapper with repaintChart() method as well as XChartPanel with revalidate() and repaint(). Disclaimer, I'm the main developer of the XChart library.
public class SimpleRealTime {
public static void main(String[] args) throws Exception {
double phase = 0;
double[][] initdata = getSineData(phase);
// Create Chart
final XYChart chart = QuickChart.getChart("Simple XChart Real-time Demo", "Radians", "Sine", "sine", initdata[0], initdata[1]);
// Show it
final SwingWrapper<XYChart> sw = new SwingWrapper<XYChart>(chart);
sw.displayChart();
while (true) {
phase += 2 * Math.PI * 2 / 20.0;
Thread.sleep(100);
final double[][] data = getSineData(phase);
chart.updateXYSeries("sine", data[0], data[1], null);
sw.repaintChart();
}
}
private static double[][] getSineData(double phase) {
double[] xData = new double[100];
double[] yData = new double[100];
for (int i = 0; i < xData.length; i++) {
double radians = phase + (2 * Math.PI / xData.length * i);
xData[i] = radians;
yData[i] = Math.sin(radians);
}
return new double[][] { xData, yData };
}
}
This results in the following Java Swing real-time chart app:

Related

Not sure if I am overriding paintComponent() correctly [duplicate]

This question already has an answer here:
Circle not showing up in JPanel
(1 answer)
Closed 2 years ago.
For someone who is wanting to learn more about awt/swing and who has not worked a lot with awt/swing I'm not sure if I am doing this correctly or not. What I am trying to do is override paintComponent() with a method that creates 6 circles that are supposed to be added to the inner panel in certain spots (the x + 50 and y + 50 are just for testing purposes). I've looked through online resources including this site and the circles still don't appear to be showing up. I'm sure I am doing something wrong but I am not sure what. Tips and/or informative links would be greatly appreciated
This is the class I have with the goal of creating and adding the circles to the panel:
public class TimeUnit extends JPanel {
private static final long serialVersionUID = 1L;
private int x = -50;
private int y = -50;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
ArrayList<Graphics> list = new ArrayList<Graphics>(6);
for (int i = 0; i < 6; i++) {
list.add(g.create());
}
for (Graphics r : list) {
r.drawOval(x + 50, y + 50, 50, 50);
}
}
And this is where it is incorporated into my main program:
JPanel inner = new JPanel();
inner.setLayout(null);
inner.setSize(325, 570);
inner.setBackground(null);
inner.setLocation(500, 350);
inner.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.BLACK));
inner.setVisible(true);
inner.repaint();
//----Containers to Panel/Panel to Frame---------
Panel.add(inner);
Panel.add(labelOne);
Panel.add(labelTwo);
Panel.add(labelFour);
Panel.add(labelEight);
Panel.add(timeLabel);
frame.add(Panel, BorderLayout.CENTER);
You should use the passed in Graphics g to draw the ovals, not create new Graphics objects:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 6; i++) {
g.drawOval(x + 50*i, y + 50*i, 50, 50);
}
}

How can I remove the white background and how can i add a stick?

I am trying to create a Billiards game for my project and I am having difficulty in adding the stick and the balls at the same time. Also, when I add the balls the background of the JFrame goes white, it is actually supposed to be green (the color of the table).
Your help will be much appreciated.
I tried using Graphics. For example g2d.setBackground(Color.green). Which did not work
public class Practice_Window implements MouseListener, MouseMotionListener, KeyListener {
JFrame Practice_Mode = new JFrame();
Balls myBalls = new Balls();
Stick myStick = new Stick();
public void PracticeWindow()
{
Practice_Mode.setSize(1000, 500);
Practice_Mode.setVisible(true);
Practice_Mode.setResizable(false);
Practice_Mode.setTitle("Practice Mode");
Practice_Mode.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Practice_Mode.getContentPane().setBackground(new Color(0, 1, 0, 0.5f)); //Not visible after i add my balls
Practice_Mode.getRootPane().setBorder(BorderFactory.createMatteBorder(10, 10, 10, 10, Color.GREEN));
Practice_Mode.add(myBalls);
//Practice_Mode.add(myStick);
//JPanel p = new JPanel();
//Timer t= new Timer(10, myBalls);
}
//BALL CLASS
public class Balls extends JPanel implements ActionListener
{
double Size = 35;
double REDxSpeed = 5;
double REDySpeed = 5;
double REDSpeed = 0;
double YELLOWxSpeed = 2;
double YELLOWySpeed = 3;
double YELLOWSpeed = 0;
double WHITExSpeed = 4;
double WHITEySpeed = 2;
double WHITESpeed = 0;
double friction = 0.2;
boolean Collision = false;
Ellipse2D.Double red = new Ellipse2D.Double(200, 200, Size, Size);
Ellipse2D.Double yellow = new Ellipse2D.Double(300, 300, Size, Size);
Ellipse2D.Double white = new Ellipse2D.Double(150, 400, Size, Size);
Timer t = new Timer(10, this);
Balls()
{
t.start();
}
#Override
public void actionPerformed(ActionEvent e) //Things are moving here
{
//RED BALL
red.x += REDxSpeed;
red.y += REDySpeed;
REDSpeed = Math.sqrt(REDxSpeed*REDxSpeed + REDySpeed*REDySpeed);
repaint();
if(red.x < 0 || red.x > getWidth() - red.width)
{
REDxSpeed = -REDxSpeed;
}
if(red.y < 0 || red.y > getHeight() - red.height)
{
REDySpeed = -REDySpeed;
}
//YELLOW BALL
yellow.x += YELLOWxSpeed;
yellow.y += YELLOWySpeed;
YELLOWSpeed = Math.sqrt(YELLOWxSpeed*YELLOWxSpeed + YELLOWySpeed*YELLOWySpeed);
repaint();
if(yellow.x < 0 || yellow.x > getWidth() - yellow.width)
{
YELLOWxSpeed = -YELLOWxSpeed;
}
if(yellow.y < 0 || yellow.y > getHeight() - yellow.height)
{
YELLOWySpeed = -YELLOWySpeed;
}
//WHITE BALL
white.x += WHITExSpeed;
white.y += WHITEySpeed;
WHITESpeed = Math.sqrt(WHITExSpeed*WHITExSpeed + WHITESpeed*WHITEySpeed);
repaint();
if(white.x < 0 || white.x > getWidth() - white.width)
{
WHITExSpeed = -WHITExSpeed;
}
if(white.y < 0 || white.y > getHeight() - white.height)
{
WHITEySpeed = -WHITEySpeed;
}
Collision_Detection();
}
public void paintComponent(Graphics g) //DRAWING MY BALLS
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
//g2d.setBackground(Color.green);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.red);
g2d.fill(red);
g2d.setColor(Color.yellow);
g2d.fill(yellow);
g2d.setColor(Color.black);
g2d.fill(white);
}
//STICK CLASS
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
public class Stick extends JPanel implements MouseListener, MouseMotionListener, ActionListener {
int xLocation = 50;
int yLocation = 50;
int Width = 50;
int Height = 15;
Rectangle2D.Double stick = new Rectangle2D.Double(200, 200, Width, Height);
Timer t = new Timer(10, this);
Stick()
{
t.start();
}
public void PaintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.ORANGE);
g2d.fill(stick);
}
I am having difficulty in adding the stick and the balls at the same time.
So why are you trying to write your entire application at once without doing any testing along the way? Why do you have Timers in the code? Why do you have KeyListeners?
Learn to develop applications one step at a time. Write a little code do some testing. When it works add more functionality. Get the basic right first before adding more complicated logic.
Practice_Mode.add(myBalls);
//Practice_Mode.add(myStick);
The default layout manager of a JFrame is the BorderLayout. By default, when you add a component to the frame (and don't specify a constraint) the component goes to the CENTER. Only a single component can be added to the CENTER so only the last component added will be visible.
Your basic design is wrong. You don't want to have separate panels for the balls and stick. You want to have a single "BilliardsGameBoard" panel that will paint multiple objects. So this panel will paint all the balls and the stick. This way all the objects are managed by the same class.
You should also not be creating individual objects with variable names. This limits the number of object you can control. Instead, keep the objects you want to paint in an ArrayList, then the painting method iterates through the ArrayList and paints each object.
See: get width and height of JPanel outside of the class for a working example of this approach.
I add the balls the background of the JFrame goes white,
Practice_Mode.getContentPane().setBackground(new Color(0, 1, 0, 0.5f));
Don't use alpha values when you specify your color. For green you can just use:
practiceMode.getContentPane().setBackground( Color.GREEN );
Your stick and balls are extending JPanel, which is typically used as a container to group a bunch of JComponents, which are buttons and UI elements. The graphical errors you see is likely Java trying to line up your panels side by side using the default BorderLayout, because it thinks you want panels of buttons and stuff when you are just trying to achieve freeform shapes.
A better approach would be to to render your stick and balls as primitive shapes on a JPanel, rather than as JPanels themselves. This is accomplished by making them implement Shape or at least giving them draw methods; the Primitives tutorial would be of use. This question also has somebody in a somewhat similar situation as yourself, and has answers relevant to you.

How can I recreate my graphic using recursion?

I have a graphic which consists of a horizontal line of circles of different sizes at regular intervals. Here is the picture:
I am trying to recreate this graphic using recursion as opposed to the if statements used in my code but after trying, am unsure about how to do this. Would love some help, here is my code:
package weekFour;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.*;
#SuppressWarnings("serial")
public class Circle extends JPanel {
private int circX = 10;
private static int windowW = 1700;
private static int windowH = 1000;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //smoothes out edges
Color c5 = new Color(50, 50, 50);
Color c4 = new Color(100, 100, 100);
Color c3 = new Color(150, 150, 150);
Color c2 = new Color(200, 200, 200);
Color c1= new Color(250, 250, 250);
for (int i = 0; i < 1; i++) {
g2.setColor(c1);
g2.fillOval(522 + 75*i, 138, 666, 666);
g2.setColor(c1);
g2.drawOval(522 + 75*i, 138, 666, 666);
}
for (int i = 0; i < 3; i++) {
g2.setColor(c2);
g2.fillOval(244 + 522*i, 365, 180, 180);
g2.setColor(c2);
g2.drawOval(244 + 522*i, 365, 180, 180);
}
for (int i = 0; i < 10; i++) {
g2.setColor(c3);
g2.fillOval(130 + 174*i, 428, 60, 60);
g2.setColor(c3);
g2.drawOval(130 + 174*i, 428, 60, 60);
}
for (int i = 0; i < 25; i++) {
g2.setColor(c4);
g2.fillOval(60 + 87*i, 444, 25, 25);
g2.setColor(c4);
g2.drawOval(60 + 87*i, 444, 25, 25);
}
for (int i = 0; i < 120; i++) {
g2.setColor(c5);
g2.fillOval(circX + 29*i, 450, 12, 12);
g2.setColor(c5);
g2.drawOval(circX + 29*i, 450, 12, 12);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("MyTaskToo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Circle());
frame.setSize(windowW, windowH);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Thanks for your time.
This is how I went about this problem, although we had to do it with green circles as opposed to grey circles but it's not that different.
N.B: Sorry for the appealing comments for sometimes trivial things but we get marks for commenting and it is better to be safe than sorry. Maybe they change you some insight into the thought process.
Here is the main method that starts the programme and sets out the window information.
public class Q2Main {
public static void main(String[] args) {
// here we are just setting out the window end putting the circles drawin in Q2Circles into this window.
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(1000, 500);
window.getContentPane().add(new Q2Circles(5));
window.setVisible(true);
}}
This is where the magic happens:
public class Q2Circles extends JPanel {
// this allows the user to specify how many loops of recursion they want the programme to complete before finishing
int recursionsToDo;
public Q2Circles(int recursionMax){
super();
recursionsToDo = recursionMax;
}
/*
this method is automatically called when we run the constructor as it inherits from the JFram superclass. here
we are setting out the size of the circle by getting the size of the window to make it proportional to the rest
of the screen and circles.
we then pass these values into the drawCircle method to draw the circle
*/
public void paintComponent(Graphics g){
Rectangle rectangle = this.getBounds();
int diameter = rectangle.width/3;
int centerPoint = rectangle.width/2;
drawCircle(g, 1, centerPoint, diameter);
}
/*
This method is where the magic of the programme really takes place. first of all we make sure we haven't completed
the necessary recursions. we the set the color by dividing it by the amount of times we have recursed, this will
have the affect of getting darker the more times the method recurses. we then sset the color. finaly we fill the
oval (draw the circle). because we want to move depending on the times it has recursed and size of the previous
we do it based on the size of the elements from the previous call to this method. Getting the right numbers
though was just alot of trial and error.
we then increment the recursion counter so that we know how many times we have recursed and that can then be
used at different points where needed. e.g for setting the color.
each recursive call used the dimension of the other recursive calls to make the whole picture. Although the
first recursive call creates the circles on the right of the screen. the second call draws the circle on the
left of the screen and the last one does the circles in the middle, they all use eachothers values to make it
complete. without one recursive step, more is missing than just what is created by that recursive call on its own.
in all honesty though, there is alot of duplication, like the large middlecircle.
*/
public void drawCircle(Graphics g, int amountOfRecursions, int center, int diameter){
if (amountOfRecursions <= recursionsToDo){
int recursionsCount = amountOfRecursions;
int greenColor = Math.round(225 / (amountOfRecursions));
g.setColor(new Color(0, greenColor, 0));
g.fillOval(center - (diameter/2), 200 - (diameter/2), diameter, diameter);
recursionsCount++;
drawCircle(g, recursionsCount, Math.round(center + diameter), diameter/3);
drawCircle(g, recursionsCount, Math.round(center - diameter), diameter/3);
drawCircle(g, recursionsCount, Math.round(center), diameter/3);
}
}}

Drawing on a panel but when adding it through another frame, nothing draws

I'm working on a project and the general idea of my work is to do every part of it in a stand alone project, then add it when finished to the main project through libraries.
My problem is - one part I have done was to perform a painting on a panel.
When I add a layer pane which connects it to the main project , there is no drawing actually happening.
Here is my project sample code:
In code sample 1 there is JLayeredPane which contains my panel to perform drawing.
In code sample 2 there is a button. Its actionPerformed is to add that JLayeredPane to a panel. But the problem is that the drawing is not appearing after adding the JLayeredPane.
Code sample 1:
public class GraphGui extends javax.swing.JFrame {
/**
* Creates new form GraphGui
*/
adjacencyMatrix m = new adjacencyMatrix();
Dfs df = new Dfs();
int[] x = new int[df.MAX_VERTS];
int[] y = new int[df.MAX_VERTS];
public Graphics2D d;
public Graphics2D doo;
int i = 0;
public GraphGui() {
setlookAndFeel();
initComponents();
setLocationRelativeTo(null);
DFS.setVisible(true);
adjMatrics.setVisible(false);
//display is the panel that draw over
d = (Graphics2D) display.getGraphics();
doo = (Graphics2D) jPanel2.getGraphics();
}
//crating an initialization of components are done automatically
public void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
df.dfs();
doo.setFont(new Font("TimesRoman", Font.BOLD, 19));
doo.drawString("visits: " + df.out, 5, 20);
df.out = "";
}
public void AddE1ActionPerformed(java.awt.event.ActionEvent evt) {
String j = start1.getText();
int k = Integer.parseInt(j) - 1;
String c = end1.getText();
int v = Integer.parseInt(c) - 1;
df.addEdge(k, v);
d.setFont(new Font("TimesRoman", Font.BOLD, 17));
d.drawLine(x[k] + 30, y[k] + 20, x[v], y[v] + 19);
}
public void AddV1ActionPerformed(java.awt.event.ActionEvent evt) {
String f = ver1.getText();
String toUpperCase = f.toUpperCase();
char r = toUpperCase.charAt(0);
df.addVertex(r);
int radius = 30;
int R = (int) (Math.random() * 256);
int G = (int) (Math.random() * 256);
int B = (int) (Math.random() * 256);
x[i] = R % 320;
y[i] = B % 167;
d.setColor(new Color(R, G, B));
d.setFont(new Font("TimesRoman", Font.BOLD, 15));
d.drawOval(x[i], y[i], radius, radius);
d.fillOval(x[i], y[i], radius, radius);
d.setColor(Color.BLACK);
d.drawString(r + "", x[i] + 10, y[i] + 20);
d.drawOval(0, 0, radius, radius);
i++;
}
What code sample 1 is supposed to do is shown at this link:
https://pbs.twimg.com/media/CG8INXZXAAEqthh.png:large
Code Sample 2
{
private void graphBTActionPerformed(java.awt.event.ActionEvent evt) {
GraphGui gr=new GraphGui();
jPanel2.removeAll();
jPanel2.add(gr.DFS);
MainLayer.setVisible(false);
Displaylayer.setVisible(true);
}
}
And at the link below is what I got after adding the panel-
nothing draws.
https://pbs.twimg.com/media/CG8IR7rWoAA3qKG.png:large
There are 2 separate issues here.
(1) Simplest answer is - you need to call 'getGraphics' from within your action method. Not from the constructor. E.g.
public void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Graphics2D doo = (Graphics2D) jPanel2.getGraphics();
...
doo.setFont(...);
doo.drawString(...);
}
(2) This would yield visible drawings, but they'll disappear whenever java decides to repaint - e.g. if you minimize the frame. This can be solved by paintComponent() as mentioned in the remarks. The basic idea is that your component (eg jPanel2) would hold a data structure of eveything it needs to paint - Strings, edges, vertexes etc. In paintComponent you draw them all. In actionPerformed() you change the datastructure and invoke 'repaint'. A sketch of this approach:
class MyPanel extends JPanel{
private String text;
private Point[] vertextes;
public void addVertext(..)
public void paintComponent(Graphics g){
... use g to drawString, drawOval... according to 'text' and 'vertexes'
}
}
// Then in your JFrame:
private MyPanel p;
...
actionPerfomred(...){
p.addVertext(..)
p.repaint();
}

Java JFrame Plotting Multiple Lines

So the crux of my problem is plotting multiple components into one JFrame in Java. I'm trying to use the same component twice to plot two different lines, but only one appears. I'm working across three separate classes in separate files, which might be making it more difficult for me. I have tried possible solutions to no avail here, here, here, here, and elsewhere. I suspect I am doing multiple things wrong, as I'm still trying to fully understand JFrame, JPanel, and LayoutManagers. Can anyone show where I went wrong?
My tester class is as follows:
import javax.swing.JFrame;
public class TransportSlabTester
{
public static void main(String[] args)
{
System.out.println("Estimation at 100 sections: ");
TransportSlab slab1 = new TransportSlab(10000,1,5,100);
System.out.println();
JFrame frame = new JFrame("Attenuated Profile");
frame.setSize(600,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TransportSlabGraph component = new TransportSlabGraph();
//analytical is a method from a 3rd class that returns double[]
component.attProfileArray(slab1.analytical(),slab1.getThickness());
frame.add(component);
component = new TransportSlabGraph();
//euler is a method from a 3rd class that returns double[]
component.attProfileArray(slab1.euler(),slab1.getThickness());
frame.add(component);
frame.setVisible(true);
}
}
Now, the class that extends JPanel:
import java.awt.*;
import java.awt.geom.Line2D;
import java.math.*;
import javax.swing.JPanel;
public class TransportSlabGraph extends JPanel
{
double[] N, xAxes, yAxes;
final int edge = 100; //Distance from edge of frame
String[] xlabel = new String[11];
String[] ylabel = new String[11];
/**
*
* #param inputN Data array of type {#code double[]}
* #param thickness Thickness set by the original constructor
*/
public void attProfileArray(double[] inputN, double thickness)
{
N = new double[inputN.length];
//Create labels for the tick marks of the x and y axis from rounded #'s
BigDecimal bd1, bd2;
for (int i = 0; i <= 10; i++)
{
bd1 = new BigDecimal((thickness/10)*i);
MathContext mc = new MathContext(2); //Round to one decimal place
bd2 = bd1.round(mc);
xlabel[i] = String.valueOf(bd2.doubleValue());
ylabel[i] = String.valueOf((inputN[0]*i)/(inputN.length-1));
}
//Set up data array and the axes
for (int i = 0; i < N.length; i++)
{
N[i]=inputN[i];
xAxes = new double[N.length];
yAxes = new double[N.length];
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//Get frame dimensions to scale drawn components
int w = getWidth();
int h = getHeight();
double xInc = (double)(w-2*edge)/(N.length-1);
double scale = (double)(h-2*edge)/N[0];
g2.draw(new Line2D.Double(edge, h-edge, w-edge, h-edge)); //draw x axis
g2.draw(new Line2D.Double(edge, edge, edge, h-edge)); // draw y axis
//Create evenly spaced tick marks for both axes and label them
for (int i = 0; i <= 10; i++)
{
g2.draw(new Line2D.Double(edge+((w-edge-edge)/10.0)*i, h-edge-10, edge+((w-edge-edge)/10.0)*i, h-edge+10)); //x ticks
g2.draw(new Line2D.Double(edge-10, h-edge-((h-edge-edge)/10.0)*i, edge+10, h-edge-((h-edge-edge)/10.0)*i)); //y ticks
g2.drawString(xlabel[i],(int)(edge+((w-edge-edge)/10.0)*i),h-edge+20);
g2.drawString(ylabel[i],edge-30,(int)(h-edge-((h-edge-edge)/10.0)*i));
}
//Scale data and convert to pixel coordinates
for (int i = 0; i < N.length; i++)
{
xAxes[i] = edge+i*xInc;
yAxes[i] = h-edge-scale*N[i];
}
//Only set the data line's color
g2.setPaint(Color.BLUE);
//Draw the data as a series of line segments
for (int i = 1; i < N.length; i++)
{
g2.draw(new Line2D.Double(xAxes[i-1],yAxes[i-1],xAxes[i],yAxes[i]));
}
}
}
Problem #1
An instance of a Component may only reside within a single Container (once).
You will need to create a new instance of each Component you want to add. I would recommend a factory pattern...
Problem #2
JFrame, but default, uses a BorderLayout, which will only allow a single component to reside at each of it's 5 available layout positions.
You will also have problems because your TransportSlabGraph class doesn't override it's getPreferredSize method, which means that, by default, instance of the component will be provided with a default size of 0x0 by many of the layout managers.
Consider changing the layout manager to something like GridLayout to start with.
Take a look at Laying Out Components Within a Container for more details

Categories