Baptiste Arnaud
Baptiste Arnaud

Reputation: 2750

Trying to solve a proportionnality issue here

In my code i generate randoms integer between 0 and 60 and i draw lines based on these.

I just want my lines fit the ordinate vertical line without touching my randoms integer... I guess it's kind of a mathematics problem but i'm really stuck here!

Here's my code first:

Windows.java:

public class Window extends JFrame{


Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time=0;
double temperature=0.0;
Timer chrono;


public static void main(String[] args) {
    new Window();
}

public Window()
{
    System.out.println("je suis là");
    this.setSize(1000,400);
    this.setLocationRelativeTo(null);
    this.setResizable(false);
    this.setTitle("Assignment2 - CPU temperature");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    container = new JPanel(new BorderLayout());


    north = new JPanel();
    north.setLayout(new BorderLayout());
    ip = new JButton ("New");
    north.add(ip, BorderLayout.WEST);
    print = new JButton ("Print");
    north.add(print,BorderLayout.EAST);

    JPanel centerPanel = new JPanel();

    centerPanel.add(new JLabel("Time Step (in s): "));
    timeStep = new JTextArea("0.1",1,5);
    centerPanel.add(timeStep);
    start = new JButton("OK");
    ListenForButton lForButton = new ListenForButton();
    start.addActionListener(lForButton);
    ip.addActionListener(lForButton);
    print.addActionListener(lForButton);
    centerPanel.add(start);

    north.add(centerPanel, BorderLayout.CENTER);



    west = new JPanel();
    JLabel temp = new JLabel("°C");
    west.add(temp);

    container.add(north, BorderLayout.NORTH);
    container.add(west,BorderLayout.WEST);
    container.add(pan, BorderLayout.CENTER);

    this.setContentPane(container);
    this.setVisible(true);
}



private class ListenForButton implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource()==start)
    {

        time=Double.parseDouble(timeStep.getText());
        System.out.println(time);
        chrono = new Timer((int)(1000*time),pan);
        chrono.start();

    }
    if(e.getSource()==ip)
    {
        JPanel options = new JPanel();
        JLabel address = new JLabel("IP Address:");
        JTextField address_t = new JTextField(15);
        JLabel port = new JLabel("Port:");
        JTextField port_t = new JTextField(5);
        options.add(address);
        options.add(address_t);
        options.add(port);
        options.add(port_t);
         int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
         if(result==JOptionPane.OK_OPTION)
         {
             System.out.println(address_t.getText());
             System.out.println(port_t.getText());
         }
    }
    if(e.getSource()==print)
    {
        chrono.stop();
    }

}
}
}

Panel.java:

public class Panel extends JPanel implements ActionListener {


int rand;
int lastrand=0;
ArrayList<Integer> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255,0,0);
Color green = new Color(0,200,0);
Color blue = new Color (0,0,200);
Color yellow = new Color (200,200,0);
int max=0;
int min=0;
int i,k,inc = 0,j;
int total,degr,moyenne;

public Panel()
{
    super();
}

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

    g2.setStroke(new BasicStroke(1.8f));


    g2.drawLine(20, 20, 20, this.getHeight()-50);
    g2.drawLine(20, this.getHeight()-50, this.getWidth()-50, this.getHeight()-50);
    g2.drawLine(20, 20, 15, 35);
    g2.drawLine(20, 20, 25, 35);
    g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-45);
    g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-55);
    g.drawString("10", 0, this.getHeight()-85);
    g.drawString("20", 0, this.getHeight()-125);
    g.drawString("30", 0, this.getHeight()-165);
    g.drawString("40", 0, this.getHeight()-205);
    g.drawString("50", 0, this.getHeight()-245);
    g2.drawString("Maximum: ", 20, this.getHeight()-20);
    g2.drawString(Integer.toString(max), 80, this.getHeight()-20);
    g2.drawString("Minimum: ", 140, this.getHeight()-20);
    g2.drawString(Integer.toString(min), 200, this.getHeight()-20);
    g2.drawString("Average: ", 260, this.getHeight()-20);
    g2.drawString(Integer.toString(moyenne), 320, this.getHeight()-20);
    g2.setColor(red);
    g2.drawLine(500, this.getHeight()-25, 540, this.getHeight()-25);
    g2.setColor(new Color(0,0,0));
    g2.drawString(":  Maximum", 560, this.getHeight()-20);
    g2.setColor(blue);
    g2.drawLine(640, this.getHeight()-25, 680, this.getHeight()-25);
    g2.setColor(new Color(0,0,0));
    g2.drawString(":  Minimum", 700, this.getHeight()-20);
    g2.setColor(green);
    g2.drawLine(780, this.getHeight()-25, 820, this.getHeight()-25);
    g2.setColor(new Color(0,0,0));
    g2.drawString(":  Average", 840, this.getHeight()-20);


    if(!randL.isEmpty()){
        g2.setColor(red);
        g2.drawLine(15, this.getHeight()-50-max, this.getWidth()-50,this.getHeight()-50-max);

        g2.setColor(blue);
        g2.drawLine(15, this.getHeight()-50-min, this.getWidth()-50,this.getHeight()-50-min);

        g2.setColor(green);
        g2.drawLine(15, this.getHeight()-50-moyenne, this.getWidth()-50,this.getHeight()-50-moyenne);

    }
    for(i = 0; i<tL.size(); i++){
        int temp = randL.get(i);
        int t = tL.get(i);
        g2.setColor(new Color(0,0,0));
        g2.drawLine(20+t, this.getHeight()-50-temp, 20+t, this.getHeight()-50);
       // Ellipse2D circle = new Ellipse2D.Double();
        //circle.setFrameFromCenter(20+t, this.getHeight()-50, 20+t+2, this.getHeight()-52);

    }
    for(j=0;j<5;j++)
    {
        inc=inc+40;
        g2.setColor(new Color(0,0,0));
        g2.drawLine(18, this.getHeight()-50-inc, 22, this.getHeight()-50-inc);
    }
    inc=0;
    }


@Override
public void actionPerformed(ActionEvent e) {
    rand = (int)(Math.random() * (60));
    lastT += 80;
    randL.add(rand);
    tL.add(lastT);
    Object obj = Collections.max(randL);
    max = (int) obj;
    Object obj2 = Collections.min(randL);
    min = (int) obj2;
   if(!randL.isEmpty()) {
    degr = randL.get(k);
    total += degr;
    moyenne=total/randL.size();
     }
    k++;
    if(randL.size()>=12)
    {
        randL.removeAll(randL);
        tL.removeAll(tL);
        lastT = 0;
        k=0;
        degr=0;
        total=0;
        moyenne=0;
    }

    repaint();
}

}

And here it what i gives me :

Starting window

Window

Sorry it's a real mess!

Any thoughts ? Thanks.

Upvotes: 1

Views: 38

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

You need to stop working with absolute/magical values, and start using the actual values of the component (width/height).

The basic problem is a simple calculation which takes the current value divides it by the maximum value and multiples it by the available width of the allowable area

int length = (value / max) * width;

value / max generates a percentage value of 0-1, which you then use to calculate the percentage of the available width of the area it will want to use.

The following example places a constraint (or margin) on the available viewable area, meaning all the lines need to be painted within that area and not use the entire viewable area of the component

Example

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DrawLine {

    public static void main(String[] args) {
        new DrawLine();
    }

    public DrawLine() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int margin = 20;

            int width = getWidth() - (margin * 2);
            int height = getHeight() - (margin * 2);

            int x = margin;
            for (int index = 0; index < 4; index++) {

                int y = margin + (int)(((index / 3d) * height));
                int length = (int)(((index + 1) / 4d) * width);

                g2d.drawLine(x, y, x + length, y);

            }

            g2d.dispose();
        }

    }

}

Upvotes: 2

Related Questions