I am making a program that inputs 5 integers and sort them visually by displaying the lines representing the number, but when I run the program, the logic works fine but line's position changes when I resize the window of the jframe, instead of automatically changing the position, here is my code
import java.util.concurrent.TimeUnit;
import java.util.Date;
import java.util.*;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
class visualSorter extends Canvas
{
static int n = 5, ar[] = new int[n],height;
JFrame frame = new JFrame("MyFrame");
public static void main(String args[])
{
try
{
Scanner ob = new Scanner(System.in);
for(int i = 0; i < 5;i++)
{
ar[i] = ob.nextInt();
}
ob.close();
visualSorter vs = new visualSorter();
vs.frame();
TimeUnit.SECONDS.sleep(5);
vs.sort();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
void frame()
{
Canvas cn = new visualSorter();
cn.setSize(1920,1080);
frame.add(cn);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
void sort()
{
try
{
int temp;
for(int i = 0; i < n; i++)
{
for(int j = i+1; j < n; j++)
{
if(ar[j] < ar[i])
{
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
TimeUnit.SECONDS.sleep(1);
revalidate();
}
repaint();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
int xDistance = 0;
for(int j = 0; j < 5; j++)
{
xDistance+=200;
height = ar[j]*100;
g2d.setColor(Color.green);
g2d.fillRect(0+xDistance,0,10,height);
}
}
}
I would really appreciate any help, my code might be quite bad so please give me some suggestions to improve and also some tips.
Thank you for you help.