Which plane is most loaded in relation to it's capacity? - java

i have to found out the plane that is most loaded in relation to it's capacity.
I create a formula inside my Plane class :
import java.util.ArrayList;
import java.util.List;
public class Plane {
private String name;
private int sitPLaces;
private int capacity;
List<Passanger> passangers = new ArrayList<>();
List<Baggage> baggage = new ArrayList<>();
public Plane(String name, int sitPLaces, int capacity) {
this.name = name;
this.sitPLaces = sitPLaces;
this.capacity = capacity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSitPLaces() {
return sitPLaces;
}
public void setSitPLaces(int sitPLaces) {
this.sitPLaces = sitPLaces;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
#Override
public String toString() {
return "Plane{" +
"name='" + name + '\'' +
", sitPLaces=" + sitPLaces +
", capacity=" + capacity +
'}';
}
public void addPassanger(Passanger newPassanger) {
if (capacity < passangers.size()) {
// System.out.println("No space for more passangers");
} else {
// System.out.println("Welcome to board!");
}
passangers.add(newPassanger);
}
//todo you need sum of weight baggages and passengers to compare it
public void addBaggage(Baggage newBaggage) {
baggage.add(newBaggage);
}
public int getKgPassanger() {
int totalKg = 0;
for (int i = 0; i < passangers.size(); i++) {
totalKg += passangers.get(i).getWeight();
}
return totalKg;
}
public int getKgBaggage() {
int totalKg = 0;
for (int i = 0; i < baggage.size(); i++) {
totalKg += baggage.get(i).getWeigh();
}
return totalKg;
}
public int getCombinedKg(){
return getKgBaggage() + getKgPassanger();
}
public int getHowManyPassangersAreIn() {
return passangers.size();
}
}
That helps me to get the sum of Passangers Kg and Baggages Kg - now i know i have to compare the sum of those with the Capacity and return the most laoded to it's capacity (in my situation
should be Plane ({"Plane plane2 = new Plane("Flig", 200, 2000)"})
Here is my Main class:
import java.util.List;
public class Main {
public static void main(String[] args) {
Plane plane1 = new Plane("Beoing", 350, 3000);
plane1.addPassanger(new Passanger("Victor", 100));
plane1.addPassanger(new Passanger("Stefan", 100));
plane1.addBaggage(new Baggage("Kipling", 100));
plane1.addBaggage(new Baggage("Kipling", 100));
Plane plane2 = new Plane("Flig", 200, 2000);
plane2.addPassanger(new Passanger("Mihai", 100));
plane2.addPassanger(new Passanger("Rudy", 100));
plane2.addPassanger(new Passanger("Rudy", 100));
plane2.addBaggage(new Baggage("Kipling", 100));
plane2.addBaggage(new Baggage("Kipling", 100));
plane2.addBaggage(new Baggage("Kipling", 100));
Plane plane3 = new Plane("Aly", 400, 2500);
plane3.addPassanger(new Passanger("Vlad", 100));
plane3.addPassanger(new Passanger("Vali", 100));
plane3.addPassanger(new Passanger("Ionut", 100));
plane3.addPassanger(new Passanger("Ionut", 100));
plane3.addBaggage(new Baggage("Kipling", 100));
plane3.addBaggage(new Baggage("Kipling", 100));
plane3.addBaggage(new Baggage("Kipling", 100));
plane3.addBaggage(new Baggage("Kipling", 100));
List<Plane> planeList = List.of(plane1, plane2, plane3);
Plane mostLoadedinRelation = getMostLoadedinRelation(planeList);
System.out.println("This plane its loaded most in relation to it's capacity: " + mostLoadedinRelation);
}
I made an for() but i do not get the result i need, and i assume that here i am not comparing the right things .
public static Plane getMostLoadedinRelation(List<Plane> planeList) {
Plane closest = planeList.get(0);
for (int i = 0; i < planeList.size(); ++i) {
if (planeList.get(i).getCombinedKg() < planeList.get(i).getCapacity()) {
closest = planeList.get(i);
}
}
return closest;
}
Is it possible to help me by giving me a hint ?
Thanks,

Related

Is it possible to split up a diagram which exceeds the raster class size limit and draw it onto several bufferedimages? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
Improve this question
I'm trying to draw a diagram which exceeds the Raster class' limit of 46340 x 46340. My diagram is 2030000 x 240000 (with the help of JScrollPane). Is it possible to create several split up BufferedImages so that I can draw my diagram onto them piece by piece?
So, based on you previous code, encapsulate the data model into a stand alone class, then create a "view model" which takes the data model and generates the "virtual" representation and caches this information.
Then, simple render the "view model" - this way all the computation overhead is done and not repeated.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.LinkedList;
import java.util.Objects;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new JScrollPane(new TestPane(new ViewModel(new DataModel()))));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel implements Scrollable {
private ViewModel viewModel;
public TestPane(ViewModel viewModel) {
this.viewModel = viewModel;
Font currentFont = getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1F);
setFont(newFont);
setBackground(Color.WHITE);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Coord coord : viewModel.getNodeCoords()) {
g2d.setColor(Color.RED);
g2d.fillOval(coord.getXCoord() - 2, coord.getYCoord() - 2, 10, 10);
if (coord.getName() != null) {
g2d.setColor(Color.BLACK);
g2d.drawString(coord.getName(), coord.getXCoord(), coord.getYCoord());
}
}
for (Connection connection : viewModel.getConnections()) {
Point from = connection.getFrom();
Point to = connection.getTo();
g.drawLine(from.x, from.y, to.x, to.y);
}
g2d.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(2030000, 200000);
}
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(400, 400);
}
#Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 32;
}
#Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 32;
}
#Override
public boolean getScrollableTracksViewportWidth() {
return false;
}
#Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
}
public class DataModel {
private LinkedList<Integer> vNodes = new LinkedList<>();
private LinkedList<Integer> vLevelWidth = new LinkedList<>();
private LinkedList<Integer> potentMoveSize = new LinkedList<>();
public DataModel() {
for (int i = 0; i < 10270; i++) {
vNodes.add(i);
}
vLevelWidth.add(10);
vLevelWidth.add(180);
vLevelWidth.add(1440);
vLevelWidth.add(8640);
for (int i = 0; i < 10; i++) {
potentMoveSize.add(18);
}
for (int i = 0; i < 180; i++) {
potentMoveSize.add(8);
}
for (int i = 0; i < 1440; i++) {
potentMoveSize.add(6);
}
potentMoveSize.add(10);
}
public LinkedList<Integer> getPotentMoveSize() {
return potentMoveSize;
}
public LinkedList<Integer> getVLevelWidth() {
return vLevelWidth;
}
public LinkedList<Integer> getVNodes() {
return vNodes;
}
}
public class Connection {
private Point from;
private Point to;
public Connection(Point from, Point to) {
this.from = from;
this.to = to;
}
public Point getFrom() {
return from;
}
public Point getTo() {
return to;
}
}
public class Coord {
private String name;
private Integer x, y, value;
public Coord(String name, Integer x, Integer y) {
this.x = x;
this.y = y;
}
public String getName() {
return name;
}
public Integer getXCoord() {
return x;
}
public Integer getYCoord() {
return y;
}
public Integer getValue() {
return value;
}
}
public class ViewModel {
private LinkedList<Coord> nodeCoords = new LinkedList<>();
private LinkedList<Connection> connections = new LinkedList<>();
public ViewModel(DataModel model) {
LinkedList<Integer> potentMoveSize = new LinkedList<>(model.getPotentMoveSize());
LinkedList<Integer> vLevelWidth = new LinkedList<>(model.getVLevelWidth());
LinkedList<Integer> vNodes = new LinkedList<>(model.getVNodes());
nodeCoords.add(new Coord("0", 2030000 / 2, 10));
Integer height = 4;
Integer heightIntervals = 200000 / (height + 1);
for (int i = 0; i < height; i++) {
for (int j = 0; j < vLevelWidth.size(); j++) {
Integer fullWidth = vLevelWidth.get(j);
Integer nodeCount = 0;
Integer widthInterval = (2030000 - 150) / fullWidth;
for (int k = 0; k < vNodes.size(); k++) {
nodeCoords.add(new Coord(
"k" + 0 + 0 + "R" + 0 + 0 + "K" + 0 + 0 + ";",
widthInterval * (k + 1),
heightIntervals * (i + 1))
);
nodeCount++;
if (Objects.equals(nodeCount, fullWidth)) {
break;
}
}
for (int k = 0; k < nodeCount; k++) {
vNodes.removeFirst();
}
if (Objects.equals(nodeCount, fullWidth)) {
vLevelWidth.removeFirst();
break;
}
}
}
LinkedList<Point> froms = new LinkedList<>();
LinkedList<Point> tos = new LinkedList<>();
for (int i = 0; i < nodeCoords.size() - (model.getVLevelWidth().getLast()); i++) // everything except bottom row of nodes
{
froms.add(new Point(nodeCoords.get(i).getXCoord(), nodeCoords.get(i).getYCoord()));
}
for (int i = 1; i < nodeCoords.size(); i++) {
tos.add(new Point(nodeCoords.get(i).getXCoord(), nodeCoords.get(i).getYCoord()));
}
Integer connectedCount;
for (int i = 0; i < froms.size(); i++) {
connectedCount = 0;
for (int j = 0; j < tos.size(); j++) {
connections.add(new Connection(froms.get(i), tos.get(j)));
connectedCount++;
if (j + 1 == potentMoveSize.get(0)) {
potentMoveSize.removeFirst();
for (int k = 0; k < connectedCount; k++) {
tos.removeFirst();
}
break;
}
}
}
}
public LinkedList<Coord> getNodeCoords() {
return nodeCoords;
}
public LinkedList<Connection> getConnections() {
return connections;
}
}
}
The above had no issues with scrolling for me, although I had many issues with actually trying to view the output - personally, I think the distance between nodes is WAY to large, but that's something you need to work out - I'd start with calculating the model and then working out the size you need to display instead of starting with the size you want and trying to fit the model into it.
If you have issues scrolling, then you could look at reducing the amount your are rendering by looking at the current clip rectangle and only rendering those elements which are actually currently displayed.
LinkedList is also not very good at "random" access, it's best for linear access, so keep that in mind as well.

Compare int values from objects in an array list, and then display the top 3 objects

I need to compare all objects in the ArrayList players, and have it return the top 3 players in terms of total points for the season (In the TopPoints method).
There are 5 players objects in the ArrayList, and their total points are: 379, 330, 313, 157, & 153. I know I need to compare them using TotalPts, but I'm drawing a blank.
Can anyone help guide me in the right direction?
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Roster {
static ArrayList <Player> players = new ArrayList<Player> ();
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\tpurv_000\\Desktop\\Stats.txt");
Scanner scan = new Scanner(file);
scan.useDelimiter("\\r?\\n");
scan.nextLine(); // ignores first line, since it's a header
while(scan.hasNextLine()) {
String[] values = scan.nextLine().split("\t");
Player currentPlayer = new Player();
currentPlayer.setPlayerNum(Integer.parseInt(values[0]));
currentPlayer.setPlayerName(values[1]);
currentPlayer.setGP(Integer.parseInt(values[2]));
currentPlayer.setGS(Integer.parseInt(values[3]));
currentPlayer.setTotalMins(Integer.parseInt(values[4]));
currentPlayer.setTotalFG(Integer.parseInt(values[5]));
currentPlayer.setTotalFGA(Integer.parseInt(values[6]));
currentPlayer.setThreeFG(Integer.parseInt(values[7]));
currentPlayer.setThreeFGA(Integer.parseInt(values[8]));
currentPlayer.setFT(Integer.parseInt(values[9]));
currentPlayer.setFTA(Integer.parseInt(values[10]));
currentPlayer.setOffReb(Integer.parseInt(values[11]));
currentPlayer.setDefReb(Integer.parseInt(values[12]));
currentPlayer.setPF(Integer.parseInt(values[13]));
currentPlayer.setA(Integer.parseInt(values[14]));
currentPlayer.setTO(Integer.parseInt(values[15]));
currentPlayer.setSTL(Integer.parseInt(values[16]));
currentPlayer.setBLK(Integer.parseInt(values[17]));
currentPlayer.setTotalPts(Integer.parseInt(values[18]));
players.add(currentPlayer);
}
System.out.println(players);
TopPoints();
}
public static void TopPoints(){
int largest = 0;
int secondLargest = 0;
int thirdLargest = 0;
//Not sure how to compare
System.out.println(largest);
}
}
class Player {
private int playerNum, GP, GS, totalMins, totalFG, totalFGA, threeFG, threeFGA, FT, FTA, offReb, defReb, PF, A, TO, STL, BLK, totalPts;
private String playerName;
//accessors & mutators
public int getPlayerNum() {
return playerNum;
}
public void setPlayerNum(int playerNum) {
this.playerNum = playerNum;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public int getGP() {
return GP;
}
public void setGP(int gP) {
GP = gP;
}
public int getGS() {
return GS;
}
public void setGS(int gS) {
GS = gS;
}
public int getTotalMins() {
return totalMins;
}
public void setTotalMins(int totalMins) {
this.totalMins = totalMins;
}
public int getTotalFG() {
return totalFG;
}
public void setTotalFG(int totalFG) {
this.totalFG = totalFG;
}
public int getTotalFGA() {
return totalFGA;
}
public void setTotalFGA(int totalFGA) {
this.totalFGA = totalFGA;
}
public int getThreeFG() {
return threeFG;
}
public void setThreeFG(int threeFG) {
this.threeFG = threeFG;
}
public int getThreeFGA() {
return threeFGA;
}
public void setThreeFGA(int threeFGA) {
this.threeFGA = threeFGA;
}
public int getFT() {
return FT;
}
public void setFT(int fT) {
FT = fT;
}
public int getFTA() {
return FTA;
}
public void setFTA(int fTA) {
FTA = fTA;
}
public int getOffReb() {
return offReb;
}
public void setOffReb(int offReb) {
this.offReb = offReb;
}
public int getDefReb() {
return defReb;
}
public void setDefReb(int defReb) {
this.defReb = defReb;
}
public int getPF() {
return PF;
}
public void setPF(int pF) {
PF = pF;
}
public int getA() {
return A;
}
public void setA(int a) {
A = a;
}
public int getTO() {
return TO;
}
public void setTO(int tO) {
TO = tO;
}
public int getSTL() {
return STL;
}
public void setSTL(int sTL) {
STL = sTL;
}
public int getBLK() {
return BLK;
}
public void setBLK(int bLK) {
BLK = bLK;
}
public int getTotalPts() {
return totalPts;
}
public void setTotalPts(int totalPts) {
this.totalPts = totalPts;
}
//Computing methods
public int avgMin() {
return (this.totalMins / this.GP);
}
public int fgPercentage() {
return (this.totalFG / this.totalFGA) * 100;
}
public int threefgPercentage() {
return (this.threeFG / this.threeFGA) * 100;
}
public int freethrowPercentage() {
return (this.FT / this.FTA) * 100;
}
public int avgRebounds() {
return (this.offReb + this.defReb) / 2;
}
}
There is a lot of solutions for it. You can use TreeList, for example, to sort all item at moment that it is added.
To sort an ArrayList, you should use Collections.sort() method. Take a look in this example:
public class ArrayListSortExample{
public static void main(String ... args){
List<Player> players = new ArrayList<>();
// Lets create 50 players with random score.
Random random = new Random();
for(int i = 0; i < 50; i++){
Player player = new Player();
player.setScore(random.nextInt(100));
players.add(player);
}
// Lets sort players by score
Collections.sort(players, new Comparator<Player>() {
#Override
public int compare(Player o1, Player o2) {
return o1.getScore() - o2.getScore();
}
});
// Print 3 top players
for(int i = 0; i < 3; i++){
System.out.println((i+1) + "ยบ place: " + players.get(i).getScore() + " score");
}
}
public static class Player{
private int score;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
}

Drawing and dragging lines using paintComponent without inflicting with any other GUI components within a JPanel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For my binary tree program, I have been using JTextFields as nodes and I have managed to make it so when I click left button and select two of the JTextFields, it will draw a line between them. The problem is if I want to drag the JtextField around, I want the line to be following as well between two of the midpoints of the JTextField. I don't know if it's possible with using only paintComponent or not. I did try it but it's like a one off thing and it will leave a trail of all the previously drawn lines.
Here, is the code so far, there are other classes so some of the bits won't work. The code has been fiddled around a bit as well for testing.
public class BinaryTreeMainPnl extends JPanel {
public static Graphics g1;
public int Width = 75;
public int Height = 45;
public String tempNode1 = "";
public int tempNode1Pos = 0;
public int tempNode2Pos = 0;
public String tempNode2 = "";
public static boolean leftBtnSelected;
public static boolean rightBtnSelected;
private static int x1, y1 = 50;
private static int x2, y2 = 500;
JToggleButton leftBtn = new JToggleButton("Left");
JToggleButton rightBtn = new JToggleButton("Right");
JTextField[] myArray = new JTextField[60];
ArrayList<String> nodeNames = new ArrayList<String>();
JFrame MainFrame;
JTextField txtFld1 = new JTextField("Enter Questions here");
JButton btn1 = new JButton("Submit");
public BinaryTreeMainPnl(JFrame frame) {
super();
setSize(800, 700);
MainFrame = frame;
readInput();
leftBtn.setFont(new Font("Arial", Font.BOLD, 15));
leftBtn.setForeground(Color.blue);
leftBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
rightBtn.setSelected(false);
leftBtnSelected = leftBtn.getModel().isSelected();
rightBtnSelected = false;
System.out.println(leftBtnSelected);
System.out.println(rightBtnSelected);
}
});
add(leftBtn);
rightBtn.setFont(new Font("Arial", Font.BOLD, 15));
rightBtn.setForeground(Color.green);
rightBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
leftBtn.setSelected(false);
rightBtnSelected = rightBtn.getModel().isSelected();
leftBtnSelected = false;
System.out.println(leftBtnSelected);
System.out.println(rightBtnSelected);
}
});
add(rightBtn);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
updateLine(g);
}
public void readInput() {
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
identifyNodeNames(txtFld1.getText());
displayNodes(nodeNames);
new TreeSorting().treeSort(nodeNames);
}
});
this.add(txtFld1);
this.add(btn1);
}
public void displayNodes(ArrayList<String> nodeNames) {
for (int i = 0; i < nodeNames.size(); i++) {
String currentSetText = nodeNames.get(i);
myArray[i] = new JTextField(currentSetText);
myArray[i].setEditable(false);
}
for (int i = 0; i < nodeNames.size(); i++) {
int I = i;
myArray[I].addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent evt) {
int x = evt.getX() + myArray[I].getX();
int y = evt.getY() + myArray[I].getY();
myArray[I].setBounds(x, y, myArray[I].getWidth(), myArray[I].getWidth());
System.out.println(myArray[I] + "dragged");
}
});
myArray[I].addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
if (leftBtnSelected) {
if (tempNode1.equals("")) {
tempNode1 = myArray[I].getText();
System.out.println(tempNode1 + "clicked");
} else {
tempNode2 = myArray[I].getText();
System.out.println(tempNode2 + "Clicked as well");
leftBtn.setSelected(false);
leftBtnSelected = false;
x1 = 40;
y1 = 40;
x2 = 400;
y2 = 400;
updateLine(g1);
System.out.println("asdasd");
}
}
if (rightBtnSelected) {
}
}
public void moveComponent(MouseEvent evt) {
}
});
System.out.println("I " + I);
System.out.println(myArray[I].getText());
add(myArray[I]);
}
MainFrame.revalidate();
}
public int findMidPoint(JTextField temp) {
Point p = temp.getLocation();
Dimension d = temp.getSize();
return p.x + (d.width) / 2;
}
int coun = 0;
public void updateLine(Graphics g) {
g.drawLine(x1, x2, y1, y2);
x1 = x1 + 10;
y1 = y1 + 10;
y2 = y2 + 10;
x2 = x2 + 10;
System.out.println("Line Updated" + coun);
coun++;
}
public void identifyNodeNames(String answer) {
int arrayCounter = 0;
int lastNodePosition = 0;
for (int i = 0; i < answer.length(); i++) {
char c = answer.charAt(i);
if (c == ',') {
nodeNames.add(arrayCounter, answer.substring(lastNodePosition, i + 1).replaceAll(",", "").replaceAll(" ", ""));
lastNodePosition = i + 1;
arrayCounter++;
}
if (i == answer.length() - 1) {
nodeNames.add(arrayCounter, answer.substring(lastNodePosition, answer.length()).replaceAll(" ", ""));
}
}
}
}
import java.util.ArrayList;
public class TreeSorting {
public static int arrayLength;
String[][] Child;
String root = "";
boolean nodeSorted = false;
int parentCounter = 1;
public void treeSort(ArrayList<String> passedQuestions) {
// declaring nodes
arrayLength = passedQuestions.size();
System.out.println(arrayLength + "ARRAY LENGTH");
Child = new String[arrayLength][3];
for (int i = 0; i < arrayLength; i++) {
Child[i][0] = passedQuestions.get(i);
}
//initially calling the mainprocess with parentCounter 1;
root = Child[0][0];
mainProcess(1);
}
public void mainProcess(int parentCounter) {
if (parentCounter < Child.length) {
System.out.println(parentCounter);
sortingTree(Child[parentCounter][0], root, 0); //where the next node is passed on the tree is sorted recursively
for (int i = 0; i < Child.length; i++) {
System.out.println(Child[i][0]);
System.out.println(Child[i][1] + "," + Child[i][2]);
}
}
}
public void sortingTree(String CurrentNode, String PreviousNode, int PreviousPosition) {
nodeSorted = false;// node is not sorted in the beginning
if (isAfter(CurrentNode.toLowerCase(), PreviousNode.toLowerCase())) {
System.out.println(Child[PreviousPosition][2]);
if (Child[PreviousPosition][2] == null) { //checks if the right of the node is empty, if found empty the node is placed there.
Child[PreviousPosition][2] = CurrentNode;
nodeSorted = true; // if the node finds a position in the array node is sorted.
} else {
sortingTree(CurrentNode, Child[PreviousPosition][2], getPositionInArray(Child[PreviousPosition][2]));
//if the array position was not empty, the loop will process again this time with the item found in the filled position.
}
} else if (Child[PreviousPosition][1] == null) { // if the left of the node is empty, the item will be placed there
Child[PreviousPosition][1] = CurrentNode;
nodeSorted = true;
} else {
sortingTree(CurrentNode, Child[PreviousPosition][1], getPositionInArray(Child[PreviousPosition][1]));
//if the array position was not empty, the loop will process again this time with the item found in the filled position.
}
if (nodeSorted) { // if the node finds a position in the array, the nodeCounter increments and the next node in the question is processed.
parentCounter++;
mainProcess(parentCounter);
}
}
public int getPositionInArray(String node) {
int position = 0;
loop:
for (int i = 0; i < Child.length; i++) {
if (Child[i][0].equals(node)) {
position = i;
break loop;
}
}
return position;
}
public boolean isAfter(String CurrentNode, String PreviousNode) {
int loopLength = determineLoopLength(CurrentNode, PreviousNode);
boolean result = false;
String tempCheck = "";
loop:
for (int i = 0; i < loopLength; i++) {
if ((int) CurrentNode.charAt(i) > (int) PreviousNode.charAt(i)) {
result = true;
break loop;
}
if ((int) CurrentNode.charAt(i) < (int) PreviousNode.charAt(i)) {
result = false;
break loop;
} else if (CurrentNode.charAt(i) == PreviousNode.charAt(i) && CurrentNode.length() > PreviousNode.length()) {
System.out.println("I'm here");
tempCheck = tempCheck + CurrentNode.charAt(i) + "";
if (i == loopLength - 1 && tempCheck.equals(PreviousNode)) {
result = true;
break loop;
}
}
}
return result;
}
public int determineLoopLength(String CurrentNode, String PreviousNode) {
int loopLength = 0;
if (CurrentNode.length() < PreviousNode.length()) {
loopLength = CurrentNode.length();
}
if (PreviousNode.length() < CurrentNode.length()) {
loopLength = PreviousNode.length();
} else {
loopLength = CurrentNode.length();
}
return loopLength;
}
}
WTF, been working on this,.....
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class DragMyFields extends JPanel {
private static final int PREF_W = 1000;
private static final int PREF_H = 800;
private static final int COLS = 8;
private static final int DELTA_Y = 120;
private static final int MAX_DEPTH = 3;
private MySimpleTreeNode<JTextField> treeRoot = new MySimpleTreeNode<>();
private MyMouse myMouse = new MyMouse();
public DragMyFields() {
setLayout(null); // this is *** BAD ***
// much better would be to create a custom layout
JTextField field = new JTextField(COLS);
field.addMouseListener(myMouse);
field.addMouseMotionListener(myMouse);
field.setSize(field.getPreferredSize());
int x = (PREF_W - field.getPreferredSize().width) / 2;
int y = DELTA_Y;
field.setLocation(x, y);
add(field);
treeRoot.setNode(field);
recursiveCreateTree(treeRoot, MAX_DEPTH, x, y);
}
private void recursiveCreateTree(MySimpleTreeNode<JTextField> node, int depth, int x, int y) {
if (depth == 0) {
return;
}
JTextField leftField = new JTextField(COLS);
JTextField rightField = new JTextField(COLS);
MySimpleTreeNode<JTextField> leftNode = new MySimpleTreeNode<>(leftField);
MySimpleTreeNode<JTextField> rightNode = new MySimpleTreeNode<>(rightField);
node.setLeft(leftNode);
node.setRight(rightNode);
int multiplier = 4;
for (int i = 0; i < MAX_DEPTH - depth; i++) {
multiplier *= 2;
}
int xL = x - getPreferredSize().width / multiplier;
int xR = x + getPreferredSize().width / multiplier;
y += DELTA_Y;
leftField.setSize(leftField.getPreferredSize());
rightField.setSize(rightField.getPreferredSize());
leftField.setLocation(xL, y);
rightField.setLocation(xR, y);
leftField.addMouseListener(myMouse);
leftField.addMouseMotionListener(myMouse);
rightField.addMouseListener(myMouse);
rightField.addMouseMotionListener(myMouse);
add(leftField);
add(rightField);
recursiveCreateTree(leftNode, depth - 1, xL, y);
recursiveCreateTree(rightNode, depth - 1, xR, y);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
recursiveDraw(g, treeRoot);
}
private void recursiveDraw(Graphics g, MySimpleTreeNode<JTextField> node) {
MySimpleTreeNode<JTextField> left = node.getLeft();
MySimpleTreeNode<JTextField> right = node.getRight();
Point p = getNodeCenter(node);
if (left != null) {
Point p2 = getNodeCenter(left);
g.drawLine(p.x, p.y, p2.x, p2.y);
recursiveDraw(g, left);
}
if (right != null) {
Point p2 = getNodeCenter(right);
g.drawLine(p.x, p.y, p2.x, p2.y);
recursiveDraw(g, right);
}
}
private Point getNodeCenter(MySimpleTreeNode<JTextField> node) {
JTextField field = node.getNode();
Point location = field.getLocation();
Dimension size = field.getSize();
return new Point(location.x + size.width / 2, location.y + size.height / 2);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouse extends MouseAdapter {
Component source = null;
private Point pressedP;
private Point pressedLoc;
private Point parentP;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
source = e.getComponent();
parentP = source.getParent().getLocationOnScreen();
pressedLoc = source.getLocationOnScreen();
pressedP = e.getLocationOnScreen();
}
#Override
public void mouseReleased(MouseEvent e) {
moveComponent(e);
source = null;
pressedP = null;
pressedLoc = null;
}
#Override
public void mouseDragged(MouseEvent e) {
if (source == null) {
return;
}
moveComponent(e);
}
private void moveComponent(MouseEvent e) {
Point p = e.getLocationOnScreen();
int x = pressedLoc.x + p.x - pressedP.x - parentP.x;
int y = pressedLoc.y + p.y - pressedP.y - parentP.y;
Point newP = new Point(x, y);
source.setLocation(newP);
repaint();
}
}
private static void createAndShowGui() {
DragMyFields mainPanel = new DragMyFields();
JFrame frame = new JFrame("DragMyFields");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
class MySimpleTreeNode<T> {
private T node;
private MySimpleTreeNode<T> left;
private MySimpleTreeNode<T> right;
public MySimpleTreeNode() {
// default constructor
}
public MySimpleTreeNode(T node) {
this.node = node;
}
public void setNode(T node) {
this.node = node;
}
public T getNode() {
return node;
}
public MySimpleTreeNode<T> getLeft() {
return left;
}
public void setLeft(MySimpleTreeNode<T> left) {
this.left = left;
}
public MySimpleTreeNode<T> getRight() {
return right;
}
public void setRight(MySimpleTreeNode<T> right) {
this.right = right;
}
}

Please Help:Grid of JButtons in a JPanel shows one JButton instead of 400 when GridLayout(20,20) is used

Thank you for trying to help me.
I want to create a grid of 20*20 squares.It is for my A-Star Algorithm Demo.
For experiment purpose I wrote the following code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Node extends JButton {
Node(){
super();
setSize(new Dimension(20,20));
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0,0,getHeight(),getWidth());
}
}
public class Map
{
static final int n = 20;
JPanel p;
public JPanel init() {
p=new JPanel();
p.setLayout(new GridLayout(n, n));
p.setBackground(Color.black);
p.setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
p.add(new Node());
}
}
return p;
}
}
public class Display extends JApplet{
public void init(){
Map m=new Map();
add(m.init());
}
}`
I got the following output:
Please load the code & check.I cannot post image since I lack 10 reputation
However,when I am trying to add the experiment code with my original code for the demo
it is not showing the desired output.My original code is as follows:
import java.util.ArrayList;
import javax.swing.*;
import java.awt.*;
public class Node extends JButton implements Comparable<Node> {
/* Nodes that this is connected to */
private Node north;
private Node east;
private Node south;
private Node west;
private ArrayList<Node> neighbourList;
private boolean visited;
private float g;
private float h;
private Node parent;
private int x;
private int y;
private boolean isObstacle;
private boolean isStart;
private boolean isGoal;
Node(int x, int y) {
super();
neighbourList = new ArrayList<Node>();
this.x = x;
this.y = y;
this.visited = false;
this.g = Integer.MAX_VALUE;
this.isObstacle = false;
this.isStart = false;
this.isGoal = false;
}
public void setNorth(Node north) {
//replace the old Node with the new one in the neighbourList
if (neighbourList.contains(this.north))
neighbourList.remove(this.north);
neighbourList.add(north);
//set the new Node
this.north = north;
}
public void setEast(Node east) {
//replace the old Node with the new one in the neighbourList
if (neighbourList.contains(this.east))
neighbourList.remove(this.east);
neighbourList.add(east);
//set the new Node
this.east = east;
}
public void setSouth(Node south) {
//replace the old Node with the new one in the neighbourList
if (neighbourList.contains(this.south))
neighbourList.remove(this.south);
neighbourList.add(south);
//set the new Node
this.south = south;
}
public void setWest(Node west) {
//replace the old Node with the new one in the neighbourList
if (neighbourList.contains(this.west))
neighbourList.remove(this.west);
neighbourList.add(west);
//set the new Node
this.west = west;
}
public ArrayList<Node> getneighbourList() {
return neighbourList;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public float getG() {
return g;
}
public void setG(float f) {
this.g = f;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public float getH() {
return h;
}
public void setH(float h) {
this.h = h;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isObstacle() {
return isObstacle;
}
public void setObstacle(boolean isObstacle) {
this.isObstacle = isObstacle;
}
public boolean isStart() {
return isStart;
}
public void setStart(boolean isStart) {
this.isStart = isStart;
}
public boolean isGoal() {
return isGoal;
}
public void setGoal(boolean isGoal) {
this.isGoal = isGoal;
}
public boolean equals(Node node) {
return (node.x == x) && (node.y == y);
}
public int compareTo(Node otherNode) {
float thisTotalDistanceFromGoal = h + g;
float otherTotalDistanceFromGoal = otherNode.getH() + otherNode.getG();
if (thisTotalDistanceFromGoal < otherTotalDistanceFromGoal)
return -1;
else if (thisTotalDistanceFromGoal > otherTotalDistanceFromGoal)
return 1;
else
return 0;
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0,0,getHeight()-1,getWidth()-1);
}
}
public class Map {
private int mapWidth;
private int mapHeight;
private ArrayList<ArrayList<Node>> map;
private int startLocationX = 0;
private int startLocationY = 0;
private int goalLocationX = 0;
private int goalLocationY = 0;
private int[][] obstacleMap;
private JPanel p;
private Logger log = new Logger();
Image buffer;
Map(int mapWidth, int mapHeight, int[][] obstacleMap) {
this.mapWidth = mapWidth;
this.mapHeight = mapHeight;
this.obstacleMap = obstacleMap;
createMap();
log.addToLog("\tMap Created");
registerEdges();
log.addToLog("\tMap Node edges registered");
}
private void createMap() {
Node node;
map = new ArrayList<ArrayList<Node>>();
for (int x=0; x<mapWidth; x++) {
map.add(new ArrayList<Node>());
for (int y=0; y<mapHeight; y++) {
node = new Node(x,y);
if (obstacleMap[x][y] == 1)
node.setObstacle(true);
map.get(x).add(node);
}
}
}
/**
* Registers the nodes edges (connections to its neighbours).
*/
private void registerEdges() {
for ( int x = 0; x < mapWidth-1; x++ ) {
for ( int y = 0; y < mapHeight-1; y++ ) {
Node node = map.get(x).get(y);
if (!node.isObstacle()){
if (!(y==0))
node.setNorth(map.get(x).get(y-1));
if (!(x==mapWidth))
node.setEast(map.get(x+1).get(y));
if (!(y==mapHeight))
node.setSouth(map.get(x).get(y+1));
if (!(x==0))
node.setWest(map.get(x-1).get(y));
}
}
}
}
public ArrayList<ArrayList<Node>> getNodes() {
return map;
}
public void setObstacle(int x, int y, boolean isObstacle) {
map.get(x).get(y).setObstacle(isObstacle);
}
public Node getNode(int x, int y) {
return map.get(x).get(y);
}
public void setStartLocation(Node start) {
map.get(startLocationX).get(startLocationY).setStart(false);
map.get(start.getX()).get(start.getY()).setStart(true);
startLocationX = start.getX();
startLocationY = start.getY();
}
public void setStartLocation(int x, int y) {
map.get(startLocationX).get(startLocationY).setStart(false);
map.get(x).get(y).setStart(true);
startLocationX = x;
startLocationY = y;
}
public void setGoalLocation(Node goal) {
map.get(goalLocationX).get(goalLocationY).setGoal(false);
map.get(goal.getX()).get(goal.getY()).setGoal(true);
goalLocationX = goal.getX();
goalLocationY = goal.getY();
}
public void setGoalLocation(int x, int y) {
map.get(goalLocationX).get(goalLocationY).setGoal(false);
map.get(x).get(y).setGoal(true);
goalLocationX = x;
goalLocationY = y;
}
public int getStartLocationX() {
return startLocationX;
}
public int getStartLocationY() {
return startLocationY;
}
public Node getStartNode() {
return map.get(startLocationX).get(startLocationY);
}
public int getGoalLocationX() {
return goalLocationX;
}
public int getGoalLocationY() {
return goalLocationY;
}
public Node getGoalLocation() {
return map.get(goalLocationX).get(goalLocationY);
}
public float getDistanceBetween(Node node1, Node node2) {
//if the nodes are on top or next to each other, return 1
if (node1.getX() == node2.getX() || node1.getY() == node2.getY()){
return 1;
} else { //if they are diagonal to each other return diagonal distance: sqrt(1^2+1^2)
return (float) 1.4;
}
}
public int getMapWidth() {
return mapWidth;
}
public int getMapHeight() {
return mapHeight;
}
public JPanel init(){
int n=20;
p=new JPanel();
p.setLayout(new GridLayout(n, n));
p.setSize(400,400);
p.setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
p.add(map.get(j).get(i));
}
}
return p;
}
public void clear() {
startLocationX = 0;
startLocationY = 0;
goalLocationX = 0;
goalLocationY = 0;
createMap();
registerEdges();
}
}
public class Display extends JApplet
{
private static int[][] M = {{0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0},
{0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0},
{0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,1,1,0,0,0},
{0,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0},
{0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0},
{1,1,1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0},
{0,0,0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0},
{0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0},
{0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
public void init()
{
JRootPane rootPane = this.getRootPane();
rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
Map m=new Map(20,20,M);
add(m.init());
}
}
This is the output that I got from the above code:
Please load the code & check.I cannot post image since I lack 10 reputation
Within the Node class, the methods getParent, getX, and getY are overriding methods in the super class JButton. When the layout manager calls getX and getY your methods get called which confuses the layout manager. Rename your three methods to anything else, for example nodeGetParent, nodeGetX, and nodeGetY.
The lesson to learn here is that you must be careful when extending a class that you don't accidentally override the super class' methods.

java multiple graphics [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Okay so I have been working on this code for awhile that shows how the sorting algorithms work. Right now I have it working where it sorts multiple graphs with the same sort but I need each graph to do a different sort at the same time. I have been researching and trying to solve this for days and now I just have tunnel vision. I'll post my code in case my explanation was confusing. I feel like this could benefit a lot of people working with java graphics and any help would be appreciated.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Scanner;
public class Sort extends Applet {
/** Constructor. Only for starting the sorting animation as applet. */
public Sort() {}
/** For starting the sorting animation as application. */
public static void main(String[] argv) {
Frame _aFrame = new Frame("Sort Animations");
_aFrame.setBackground(Color.white);
_aFrame.setPreferredSize(new Dimension(2700,1000));
Scanner in = new Scanner(System.in);
int sizeOfArray;
System.out.println("How many numbers do you want to sort?");
sizeOfArray = in.nextInt();
_aFrame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
}
);
_aFrame.setLayout(new BorderLayout());
_aFrame.add(new SortPanel(sizeOfArray));
_aFrame.pack();
_aFrame.setVisible(true);
}
}
class SortPanel extends Panel implements Runnable {
/** button triggering the sort animation */
private Button aSortButton_ = new Button("sort");
/** choice item for selecting the sort algorithm */
private Choice aChoice_ = new Choice();
/** component for handling the animation */
private ArrayCanvas anArrayCanvas_;
/////////////////////////////////////////////////////////////////////////////
/**
* Constructor.
*
* #param length no of elements of the array
* #param aBarColor the color the elements representing bars will be drawn in
*
* #exception IllegalArgumentException if the array <code>length</code> is
* to big to display (ie <code>length</code> is bigger than
* <code>BAR_WIDTH</code> or <code>BAR_HEIGHT</code>).
*/
public SortPanel(int arraySize) {
setLayout(new BorderLayout());
aSortButton_.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread(SortPanel.this).start();
}
}
);
anArrayCanvas_ = new ArrayCanvas(arraySize);
for (int i=0; i<ArrayCanvas.SORT_NAMES.length; ++i)
aChoice_.add(ArrayCanvas.SORT_NAMES[i]);
// add buttons at top:
Panel _aTopPanel = new Panel();
_aTopPanel.add(aSortButton_);
add(_aTopPanel, BorderLayout.NORTH);
// add choice and ArrayCanvas below:
Panel _aPanel = new Panel();
_aPanel.setLayout(new BorderLayout());
Panel _aChoicePanel = new Panel();
_aChoicePanel.add(aChoice_);
_aPanel.add(_aChoicePanel, BorderLayout.NORTH);
_aPanel.add(anArrayCanvas_, BorderLayout.CENTER);
add(_aPanel, BorderLayout.CENTER);
Panel _aBottomPanel = new Panel();
add(_aBottomPanel, BorderLayout.SOUTH);
}
/////////////////////////////////////////////////////////////////////////////
/** Runs the sorting animation. */
public void run() {
aSortButton_.setEnabled(false);
double time = System.currentTimeMillis();
anArrayCanvas_.sort(aChoice_.getSelectedItem());
aSortButton_.setEnabled(true);
}
}
class ArrayCanvas extends Canvas {
/** Labels of available sorting algorithms. */
public final static String[] SORT_NAMES = { "bubble sort", "insertion sort", "shell sort", "heap sort", "merge sort", "quick sort",};
/** offset between bars and border in x-directions (left and right) */
public final static int OFFSET_X = 5;
/** offset between bars and border in y-directions (top and bottom) */
public final static int OFFSET_Y = 5;
/** horizontal size of all bars together */
public final static int BAR_WIDTH = 350;
/** (max) vertical horizontal size of bars together */
public final static int BAR_HEIGHT = 250;
/** milliseconds to sleep after a swap in the sorting animation */
public final static int SLEEP_AFTER_SWAP = 20;
/** used for random permutation of the array elements */
private static Random aRandom_ = new Random(System.currentTimeMillis());
/** the array to display */
private int[] anArrayOfInt_;
/** offscreen buffer */
private Image image_;
/** graphics of the offscreen buffer */
private Graphics offscreenGraphics_;
/////////////////////////////////////////////////////////////////////////////
/**
* Constructor.
*
* #param length no of elements of the array
*
* #exception IllegalArgumentException if the array <code>length</code> is
* to big to display (ie <code>length</code> is bigger than
* <code>BAR_WIDTH</code> or <code>BAR_HEIGHT</code>).
*/
public ArrayCanvas(int length) {
if (length > BAR_WIDTH || length > BAR_HEIGHT)
throw new IllegalArgumentException("array to big: "+length);
anArrayOfInt_ = new int[length];
for (int i=0; i<length; ++i)
anArrayOfInt_[i] = i+1;
permute();
addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
repaint();
}
}
);
}
/////////////////////////////////////////////////////////////////////////////
// overloaded for double buffering
public void update(Graphics aGraphics) {
paint(aGraphics);
}
/** displays the array */
public void paint(Graphics aGraphics) {
int _deltaX = 0;
int w = BAR_WIDTH / anArrayOfInt_.length;
if (w > 1) {
--w;
++_deltaX;
}
int _heightFactor = BAR_HEIGHT / anArrayOfInt_.length;
if (offscreenGraphics_ == null) {
image_ = createImage(getSize().width, getSize().height);
offscreenGraphics_ = image_.getGraphics();
}
offscreenGraphics_.setColor(getBackground());
offscreenGraphics_.fillRect(0, 0, getSize().width-1, getSize().height-1);
offscreenGraphics_.setColor(Color.black);
//offscreenGraphics_.drawRect(0, 0, getSize().width-1, getSize().height-1);
offscreenGraphics_.translate(OFFSET_X, OFFSET_Y);
for (int i=0; i<anArrayOfInt_.length; ++i) {
int h = _heightFactor*anArrayOfInt_[i];
offscreenGraphics_.setColor(Color.blue);
offscreenGraphics_.fillRect((w+_deltaX)*i, BAR_HEIGHT-h, w, h);
if(anArrayOfInt_[i]==(i+1)){
offscreenGraphics_.setColor(Color.red);
offscreenGraphics_.fillRect((w+_deltaX)*i, BAR_HEIGHT-h, w, _heightFactor);
}
}
offscreenGraphics_.translate(-OFFSET_X, -OFFSET_Y);
aGraphics.drawImage(image_, 0, 0, this);
aGraphics.drawImage(image_, 475, 0, this);
aGraphics.drawImage(image_, 950, 0, this);
aGraphics.drawImage(image_, 0, 350, this);
aGraphics.drawImage(image_, 475, 350, this);
aGraphics.drawImage(image_, 950, 350, this);
}
public Dimension getMinimumSize() {
return new Dimension(BAR_WIDTH+2*OFFSET_X, BAR_HEIGHT+2*OFFSET_Y);
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
///////////////////////////////////////////////////
/** random permutation of array entries */
public void permute() {
for (int i=anArrayOfInt_.length-1; i>0; --i) {
int j = Math.abs(aRandom_.nextInt()) % (i+1);
swap(anArrayOfInt_,i,j);
}
}
/** animated sort */
public void sort(String aSortNameString) {
mySort(aSortNameString);
}
///////////////////////////////////////////////////
private void mySort(String aSortNameString) {
if (aSortNameString.equals("bubble sort")) {
bubbleSort(anArrayOfInt_);
}
if (aSortNameString.equals("insertion sort")) {
insertionSort(anArrayOfInt_);
}
if (aSortNameString.equals("selection sort")) {
selectionSort(anArrayOfInt_);
}
if (aSortNameString.equals("shell sort")) {
shellSort(anArrayOfInt_);
}
if (aSortNameString.equals("heap sort")) {
heapSort(anArrayOfInt_);
}
if (aSortNameString.equals("merge sort")) {
mergeSort(anArrayOfInt_, 0, anArrayOfInt_.length-1);
}
if (aSortNameString.equals("quick sort")) {
qSort(anArrayOfInt_, 0, anArrayOfInt_.length-1);
}
}
/**
* swaps the two array elements, redisplays the array in its canvas,
* and waits a moment.
*/
private void swap(int[] anArrayOfInt, int i, int j) {
int x = anArrayOfInt[i];
anArrayOfInt[i] = anArrayOfInt[j];
anArrayOfInt[j] = x;
repaint();
try { Thread.sleep(SLEEP_AFTER_SWAP); } catch (InterruptedException e) {}
}
/////////////////////////////////////////////////////////////////////////////
// SORTING ALGORITHMS //
/////////////////////////////////////////////////////////////////////////////
/** bubble sort */
private void bubbleSort(int[] anArrayOfInt) {
for (int i=0; i<anArrayOfInt.length; ++i)
for (int j=1; j<anArrayOfInt.length-i; ++j)
if (anArrayOfInt[j-1]>anArrayOfInt[j]) {
swap(anArrayOfInt, j-1, j);
}
}
/** insertion sort */
private void insertionSort(int[] anArrayOfInt) {
for (int i=0; i<anArrayOfInt.length; ++i)
for (int j=i-1; j>=0 && anArrayOfInt[j]>anArrayOfInt[j+1]; --j)
swap(anArrayOfInt, j, j+1);
}
/** selection sort */
private void selectionSort(int[] anArrayOfInt) {
for (int i=0; i<anArrayOfInt.length-1; ++i) {
for (int j=i+1; j<anArrayOfInt.length; ++j)
if (anArrayOfInt[j] < anArrayOfInt[i])
swap(anArrayOfInt, i, j);
}
}
/** shell sort */
private void shellSort(int[] anArrayOfInt) {
// TODO: calculate needed STEPS-elements instead of using an array
// (STEPS[i+1] = 3*STEPS[i]+1)
for (int i=0; i<STEPS.length; ++i) {
int _delta = STEPS[i];
if (_delta >= anArrayOfInt.length)
continue;
for (int j=_delta; j<anArrayOfInt.length; ++j)
for (int k=j; k-_delta>=0 && anArrayOfInt[k]<anArrayOfInt[k- _delta];
k-=_delta)
swap(anArrayOfInt, k, k-_delta);
}
}
/** used by shell sort */
private final static int[] STEPS = { 1093, 364, 121, 40, 13, 4, 1 };
/** heap sort */
private void heapSort(int[] anArrayOfInt) {
int r = anArrayOfInt.length-1;
for (int l = anArrayOfInt.length/2 ; l>=0; --l)
sift(anArrayOfInt, l, r);
while (r > 0) {
swap(anArrayOfInt, 0, r);
sift(anArrayOfInt, 0, --r);
}
}
/** auxiliary function for heap sort. */
private void sift(int[] anArrayOfInt, int l, int r) {
if (r==l)
return;
int i = l, j = 2*l;
int x = anArrayOfInt[i];
if (j<r && anArrayOfInt[j]<anArrayOfInt[j+1])
++j;
while (j<=r && x<=anArrayOfInt[j]) {
swap(anArrayOfInt, i, j);
i = j; j = 2*j;
if (j<r && anArrayOfInt[j]<anArrayOfInt[j+1])
++j;
}
}
/** quick sort (pivot=(l+r)/2)*/
private void qSort(int[] anArrayOfInt, int l, int r) {
if (l >= r)
return;
swap(anArrayOfInt, l, (l+r)/2); // TODO: more clever pivot
int _last = l;
for (int i=l+1; i<=r; ++i)
if (anArrayOfInt[i] < anArrayOfInt[l])
swap(anArrayOfInt, ++_last, i);
swap(anArrayOfInt, l, _last);
qSort(anArrayOfInt, l, _last-1);
qSort(anArrayOfInt, _last+1, r);
}
/** merge sort */
private void mergeSort(int[] anArrayOfInt, int l, int r) {
int[][] B = new int[2][r+1];
mergeSort16(anArrayOfInt, B, l, r);
}
private void mergeSort16(int[] anArrayOfInt, int[][] B, int l, int r) {
if (l >= r)
return;
int _last = (l+r)/2;
mergeSort16(anArrayOfInt, B, l, _last);
mergeSort16(anArrayOfInt, B, _last+1, r);
merge6(anArrayOfInt, B, l, _last, r);
}
/** auxiliary function for merge sort */
protected void merge6(int[] anArrayOfInt, int[][] B, int l, int q, int r) {
for (int i=l;i<=q;i++) {
B[0][i] = i;
B[1][i] = i;
}
for (int i=r;i>q;i--) {
B[0][i] = r+q+1-i;
B[1][i] = r+q+1-i;
}
int i = l;
int j = r;
for (int k=l; k<r;k++) {
int s = B[0][i];
int t = B[0][j];
if (anArrayOfInt[s]<=anArrayOfInt[t]) {
i++;
} else {
s = t;
j--;
}
swap(anArrayOfInt, s, k);
t = B[1][k];
B[0][t] = s;
B[1][s] = t;
}
}
}
For each sort graph you need some kind of model, which should hold the current state of each sort. This would probably mean adding your list of ints to a separate list per sort.
You would also need some kind of mechanism that would allow you to loop through each sort algorithm and tell it to move to the next step in its algorithm, thus allowing you to control when each sort algorithm update and therefore control when the screen is updated.
Updated
Based on a comment from the OP, basically, I've ripped out the sort algorithm as a separate interface. Each algorithm would need to extend from this interface, but it provides the basic requirements to allow the UI to render the sort animation.
Bellow is basic implementation, while it's based on Swing, if required, it wouldn't be a stretch to get it to work with AWT.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestSort {
public static void main(String[] args) {
new TestSort();
}
public TestSort() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
SortPane sortPane = new SortPane();
int values[] = new int[10];
for (int index = 0; index < values.length; index++) {
values[index] = (int)Math.round(Math.random() * 100f);
}
BubbleSort sorter = new BubbleSort(values);
sortPane.setSorter(sorter);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(sortPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
sorter.sort();
}
});
}
public class SortPane extends JPanel {
private Sorter sorter;
private ChangeHandler changeHandler;
private int maxValue;
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int values[] = getSorter().getValues();
int width = getWidth() - 1;
int height = getHeight() - 1;
int colWidth = Math.round((float)width / (float)values.length);
int x = 0;
Color fill = Color.YELLOW;
Color highlight = null;
switch (getSorter().getState()) {
case Sorting:
fill = Color.BLUE;
highlight = Color.RED;
break;
case Done:
fill = Color.GREEN;
break;
}
for (int index = 0; index < values.length; index++) {
g2d.setColor(fill);
int value = values[index];
int colHeight = (int)((float)height * ((float)value / (float)maxValue));
g2d.fillRect(x, height - colHeight, colWidth - 1, colHeight);
if (getSorter().isActiveIndex(index) && highlight != null) {
g2d.setColor(highlight);
g2d.drawRect(x, height - colHeight, colWidth - 1, colHeight);
}
x += colWidth;
}
g2d.dispose();
}
public Sorter getSorter() {
return sorter;
}
public void setSorter(Sorter value) {
if (sorter != value) {
if (sorter != null) {
sorter.removeChangeListener(getChangeHandler());
}
sorter = value;
if (sorter != null) {
sorter.addChangeListener(getChangeHandler());
maxValue = 0;
for (int intValue : sorter.getValues()) {
maxValue = Math.max(maxValue, intValue);
}
}
repaint();
}
}
public ChangeHandler getChangeHandler() {
if (changeHandler == null) {
changeHandler = new ChangeHandler();
}
return changeHandler;
}
public class ChangeHandler implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
repaint();
}
}
}
public interface Sorter {
public enum State {
Waiting,
Sorting,
Done
}
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
public int[] getValues();
public void sort();
public State getState();
public boolean isActiveIndex(int index);
}
public abstract class AbstracSorter implements Sorter {
private List<ChangeListener> listeners;
private int[] values;
private State state = State.Waiting;
private List<Integer> activeIndices;
public AbstracSorter(int[] values) {
this.values = values;
listeners = new ArrayList<>(25);
activeIndices = new ArrayList<>(2);
}
#Override
public State getState() {
return state;
}
public void setState(State value) {
if (value != state) {
state = value;
fireStateChanged();
}
}
#Override
public int[] getValues() {
return values;
}
#Override
public void addChangeListener(ChangeListener listener) {
listeners.add(listener);
}
#Override
public void removeChangeListener(ChangeListener listener) {
listeners.remove(listener);
}
protected void fireStateChanged() {
if (listeners.size() > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
#Override
public boolean isActiveIndex(int index) {
return activeIndices.contains(index);
}
protected void setActiveIndicies(int lower, int upper) {
activeIndices.clear();
activeIndices.add(lower);
activeIndices.add(upper);
fireStateChanged();
}
protected void swap(int[] anArrayOfInt, int i, int j) {
setActiveIndicies(i, j);
int x = anArrayOfInt[i];
anArrayOfInt[i] = anArrayOfInt[j];
anArrayOfInt[j] = x;
fireStateChanged();
}
}
public class BubbleSort extends AbstracSorter {
private int outter = 0;
private int inner = 0;
public BubbleSort(int[] values) {
super(values);
}
#Override
public void sort() {
setState(State.Sorting);
outter = 0;
inner = 1;
Timer timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int[] values = getValues();
inner++;
if (inner >= values.length - outter) {
outter++;
inner = 1;
}
if (outter < values.length) {
if (values[inner - 1] > values[inner]) {
swap(values, inner - 1, inner);
} else {
setActiveIndicies(inner - 1, inner);
}
} else {
((Timer)e.getSource()).stop();
setState(State.Done);
}
}
});
timer.setRepeats(true);
timer.start();
}
}
}
Example using the source array
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestSort {
public static void main(String[] args) {
new TestSort();
}
private List<Sorter> sorters;
public TestSort() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
sorters = new ArrayList<>(2);
int values[] = new int[10];
for (int index = 0; index < values.length; index++) {
values[index] = (int) Math.round(Math.random() * 100f);
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2));
frame.add(createBubbleSortPane(values));
frame.add(createBubbleSortPane(values));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
for (Sorter sorter : sorters) {
sorter.sort();
}
}
});
}
protected SortPane createBubbleSortPane(int[] values) {
SortPane sortPane = new SortPane();
BubbleSort sorter = new BubbleSort(values);
sortPane.setSorter(sorter);
sortPane.setBorder(new CompoundBorder(new LineBorder(Color.GRAY), new EmptyBorder(8, 8, 8, 8)));
sorters.add(sorter);
return sortPane;
}
public class SortPane extends JPanel {
private Sorter sorter;
private ChangeHandler changeHandler;
private int maxValue;
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int values[] = getSorter().getValues();
Insets insets = getInsets();
int width = getWidth() - 1 - (insets.left + insets.right);
int height = getHeight() - 1 - (insets.top + insets.bottom);
int colWidth = Math.round((float) width / (float) values.length);
int x = insets.left;
Color fill = Color.YELLOW;
Color highlight = null;
switch (getSorter().getState()) {
case Sorting:
fill = Color.BLUE;
highlight = Color.RED;
break;
case Done:
fill = Color.GREEN;
break;
}
for (int index = 0; index < values.length; index++) {
g2d.setColor(fill);
int value = values[index];
int colHeight = (int) ((float) height * ((float) value / (float) maxValue));
g2d.fillRect(x, insets.top + height - colHeight, colWidth - 1, colHeight);
if (getSorter().isActiveIndex(index) && highlight != null) {
g2d.setColor(highlight);
g2d.drawRect(x, insets.top + height - colHeight, colWidth - 1, colHeight);
}
x += colWidth;
}
g2d.dispose();
}
public Sorter getSorter() {
return sorter;
}
public void setSorter(Sorter value) {
if (sorter != value) {
if (sorter != null) {
sorter.removeChangeListener(getChangeHandler());
}
sorter = value;
if (sorter != null) {
sorter.addChangeListener(getChangeHandler());
maxValue = 0;
for (int intValue : sorter.getValues()) {
maxValue = Math.max(maxValue, intValue);
}
}
repaint();
}
}
public ChangeHandler getChangeHandler() {
if (changeHandler == null) {
changeHandler = new ChangeHandler();
}
return changeHandler;
}
public class ChangeHandler implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
repaint();
}
}
}
public interface Sorter {
public enum State {
Waiting,
Sorting,
Done
}
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
public int[] getValues();
public void sort();
public State getState();
public boolean isActiveIndex(int index);
}
public abstract class AbstracSorter implements Sorter {
private List<ChangeListener> listeners;
private int[] values;
private State state = State.Waiting;
private List<Integer> activeIndices;
public AbstracSorter(int[] values) {
this.values = new int[values.length];
System.arraycopy(values, 0, this.values, 0, values.length);
listeners = new ArrayList<>(25);
activeIndices = new ArrayList<>(2);
}
#Override
public State getState() {
return state;
}
public void setState(State value) {
if (value != state) {
state = value;
fireStateChanged();
}
}
#Override
public int[] getValues() {
return values;
}
#Override
public void addChangeListener(ChangeListener listener) {
listeners.add(listener);
}
#Override
public void removeChangeListener(ChangeListener listener) {
listeners.remove(listener);
}
protected void fireStateChanged() {
if (listeners.size() > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
#Override
public boolean isActiveIndex(int index) {
return activeIndices.contains(index);
}
protected void setActiveIndicies(int lower, int upper) {
activeIndices.clear();
activeIndices.add(lower);
activeIndices.add(upper);
fireStateChanged();
}
protected void swap(int[] anArrayOfInt, int i, int j) {
setActiveIndicies(i, j);
int x = anArrayOfInt[i];
anArrayOfInt[i] = anArrayOfInt[j];
anArrayOfInt[j] = x;
fireStateChanged();
}
}
public class BubbleSort extends AbstracSorter {
private int outter = 0;
private int inner = 0;
public BubbleSort(int[] values) {
super(values);
}
#Override
public void sort() {
setState(State.Sorting);
outter = 0;
inner = 1;
Timer timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int[] values = getValues();
inner++;
if (inner >= values.length - outter) {
outter++;
inner = 1;
}
if (outter < values.length) {
if (values[inner - 1] > values[inner]) {
swap(values, inner - 1, inner);
} else {
setActiveIndicies(inner - 1, inner);
}
} else {
((Timer) e.getSource()).stop();
setState(State.Done);
}
}
});
timer.setRepeats(true);
timer.start();
}
}
}
Example Insertion Sorter
This is an example of using a Thread as the primary sort engine instead of a Swing Timer
public class InsertionSorter extends AbstracSorter {
public InsertionSorter(int[] values) {
super(values);
}
#Override
public void sort() {
setState(State.Sorting);
new Thread(new SortRunnable()).start();
}
#Override
protected void swap(int[] anArrayOfInt, int i, int j) {
setActiveIndicies(i, j);
int x = anArrayOfInt[i];
anArrayOfInt[i] = anArrayOfInt[j];
anArrayOfInt[j] = x;
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
fireStateChanged();
}
});
} catch (InterruptedException | InvocationTargetException exp) {
exp.printStackTrace();
}
}
public class SortRunnable implements Runnable {
#Override
public void run() {
int[] values = getValues();
for (int i = 0; i < values.length; ++i) {
for (int j = i - 1; j >= 0 && values[j] > values[j + 1]; --j) {
try {
Thread.sleep(250);
} catch (InterruptedException ex) {
}
swap(values, j, j + 1);
}
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
setState(State.Done);
}
});
}
}
}

Categories

Resources