public class Main extends JFrame{
public static void main(String[] args) {
JFrame jp1 = new JFrame();
jp1.setTitle("Diagram");
Print m = new Print();
jp1.setLayout(null);
jp1.setSize(500,500);
m.setBounds(0,0,500,500);
jp1.add(m);
jp1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp1.setVisible(true);
}
static class Print extends JPanel{
public void drawDiagram(Graphics g, double[] x, double[] y){
g.setColor(Color.BLUE);
int scale = 100;
int lastX = 0, lastY = 0;
for (int i = 0; i < x.length; i++) {
g.drawLine(lastX*scale, lastY*scale,(int) x[i] * scale,(int) y[i]* scale);
lastX = (int) x[i];
lastY = (int) y[i];
}
}
}
}
I am using java swing and I dont understand why my digram isnt printing. I have tried using object of class Main but it didnt help. Could ypu help me with my problem? Thanks in advance
Much better to handle custom painting in a dedicated component, like your original idea. The (main) problem with your original idea is that you didn't do the painting in the right way. This is the way to do it:
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Color;
public class Main extends JFrame {
public static void main(String[] args) {
JFrame jp1 = new JFrame();
jp1.setTitle("Diagram");
Print m = new Print(new double[] { 1, 1, 1 }, new double[] { 1, 2, 3 });
jp1.add(m);
jp1.setSize(500, 500);
jp1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp1.setVisible(true);
}
static class Print extends JPanel{
private double[] x, y;
public Print(double[] x, double[] y){
this.x = x;
this.y = y;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
int scale = 100;
int lastX = 10, lastY = 10;
for (int i = 0; i < x.length; i++) {
System.out.printf("(%d,%d) (%d,%d)%n", lastX*scale, lastY*scale,(int) x[i] * scale,(int) y[i]* scale);
g.drawLine(lastX*scale, lastY*scale,(int) x[i] * scale,(int) y[i]* scale);
lastX = (int) x[i];
lastY = (int) y[i];
}
}
}
}