package gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import main.settings;
import mergesort.algorithm;
public class Panel extends JPanel{
private static final long serialVersionUID = 1L;
private algorithm algorithm;
private float multiplicator;
private int[] data;
private JButton start, okay;
private int current = -1, left = -1, right = -1;
private TreeFrame treeframe = new TreeFrame();
public Panel() {
setLayout(null);
init();
start = new JButton("start");
start.setBounds(20,20,80,30);
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
start.setVisible(false);
SwingUtilities.invokeLater(() -> algorithm.run());
}
});
add(start);
okay = new JButton("okay");
okay.setBounds(20,20,80,30);
okay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
init();
okay.setVisible(false);
start.setVisible(true);
repaint();
}
});
add(okay);
okay.setVisible(false);
}
private void init() {
this.algorithm = new algorithm(this, treeframe);
this.data = algorithm.getData();
this.multiplicator = getMultiplicator(data);
}
public void paintComponent(Graphics g) {
g.fillRect(0, 0, settings.frameWidth, settings.frameHeight);
for(int i = 0; i < data.length; i++) {
if(i == current) g.setColor(Color.RED);
else if(i == left || i == right) g.setColor(Color.GREEN);
else g.setColor(Color.WHITE);
int width = (settings.frameWidth) / data.length;
int height = (int) ((int) data[i]*multiplicator);
int x = i * width;
int y = (int) settings.frameHeight - height;
g.fillRect(x, y, width, height);
g.setColor(Color.BLACK);
g.drawRect(x, y, width, height);
}
}
private float getMultiplicator(int[] data) {
int max = data[0];
for(int i = 0; i < data.length; i++) {
if(max < data[i]) max = data[i];
}
float multiplicator = (settings.frameHeight-10) / (float) max;
return multiplicator;
}
public void setData(int[] data, int current, int left, int right) {
this.data = data;
this.current = current;
this.left = left;
this.right = right;
repaint();
}
public void setDefault() {
okay.setVisible(true);
current = -1;
left = -1;
right = -1;
}
public void pause() {
algorithm.pause();
}
public void changeSpeed(int direction) {
algorithm.changeSpeed(direction);
}
}