Faulty code from book on viewing bubble sort - java

I am running example code from this book, Data Structures and Algorithms in Java (2nd Edition) - LaFore, that is not behaving as expected. In the third chapter there is example code for running a visual on bubble sorts. But the only button that works for the applet is "New" and "Step". I am trying to fix the code in IntelliJ but the breakpoints are getting a cancel feature. I am not sure if this means the code is never even run. How can I get the breakpoints to show up. Also look at the image.
BubbleSort.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;
public class BubbleSort extends Applet
implements Runnable, ActionListener
{
public void init()
{
thePersonGroup = new groupBS(groupSize, order);
setLayout(new FlowLayout(2));
newButton = new Button("New");
add(newButton);
newButton.addActionListener(this);
sizeButton = new Button("Size");
add(sizeButton);
sizeButton.addActionListener(this);
drawButton = new Button("Draw");
add(drawButton);
drawButton.addActionListener(this);
runButton = new Button("Run");
add(runButton);
runButton.addActionListener(this);
stepButton = new Button("Step");
add(stepButton);
stepButton.addActionListener(this);
aWidth = thePersonGroup.getAppletWidth();
aHeight = thePersonGroup.getAppletHeight();
offscreenImage = createImage(aWidth, aHeight);
offscreenGraphics = offscreenImage.getGraphics();
thePersonGroup.setDrawMode(2);
runFlag = false;
}
public void paint(Graphics g)
{
thePersonGroup.draw(offscreenGraphics);
g.drawImage(offscreenImage, 0, 0, this);
}
public void update(Graphics g)
{
paint(g);
}
public void actionPerformed(ActionEvent actionevent)
{
if(actionevent.getSource() == newButton)
{
runFlag = false;
order = order != 1 ? 1 : 2;
thePersonGroup = new groupBS(groupSize, order);
} else
if(actionevent.getSource() == sizeButton)
{
runFlag = false;
groupSize = groupSize != 10 ? 10 : 100;
thePersonGroup = new groupBS(groupSize, order);
} else
if(actionevent.getSource() == drawButton)
{
runFlag = false;
thePersonGroup.setDrawMode(2);
} else
if(actionevent.getSource() == runButton)
runFlag = true;
else
if(actionevent.getSource() == stepButton)
{
runFlag = false;
thePersonGroup.sortStep();
thePersonGroup.setDrawMode(1);
}
repaint();
}
public void run()
{
for(Thread thread = Thread.currentThread(); runner == thread;)
if(runFlag && !thePersonGroup.getDone())
{
thePersonGroup.sortStep();
repaint();
thePersonGroup.setDrawMode(1);
int i = groupSize != 10 ? 75 : 250;
try
{
Thread.sleep(i);
}
catch(InterruptedException _ex) { }
}
}
public void start()
{
if(runner == null)
{
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
runner = null;
}
public BubbleSort()
{
groupSize = 10;
order = 1;
}
private Image offscreenImage;
private Graphics offscreenGraphics;
private int aWidth;
private int aHeight;
private Thread runner;
private int groupSize;
private groupBS thePersonGroup;
private boolean runFlag;
private int order;
private Button newButton;
private Button sizeButton;
private Button drawButton;
private Button runButton;
private Button stepButton;
}
groupBS.java
import java.awt.Color;
import java.awt.Graphics;
class groupBS
{
public groupBS(int i, int j)
{
aSize = i;
initOrder = j;
theArray = new personBS[aSize];
if(aSize == 100)
{
barWidth = 2;
barSeparation = 1;
} else
{
barWidth = 20;
barSeparation = 10;
}
outer = aSize - 1;
inner = 0;
comps = 0;
swaps = 0;
swapFlag = false;
doneFlag = false;
drawMode = 2;
if(initOrder == 1)
{
for(int k = 0; k < aSize; k++)
{
int i1 = (int)(Math.random() * 199D);
int k1 = (int)(Math.random() * 254D);
int i2 = (int)(Math.random() * 254D);
int k2 = (int)(Math.random() * 254D);
newColor = new Color(k1, i2, k2);
theArray[k] = new personBS(i1, newColor);
}
return;
}
for(int l = 0; l < aSize; l++)
{
int j1 = 199 - (199 * l) / aSize;
int l1 = 255 - j1;
int j2 = 85 * (l % 3);
int l2 = j1;
newColor = new Color(l1, j2, l2);
theArray[l] = new personBS(j1, newColor);
}
}
public void setDrawMode(int i)
{
drawMode = i;
}
public int getAppletWidth()
{
return 370;
}
public int getAppletHeight()
{
return 320;
}
public boolean getDone()
{
return doneFlag;
}
public void arrowText(Graphics g, Color color, String s, int i, int j, boolean flag, boolean flag1)
{
int k = 35 + i * (barWidth + barSeparation);
int l = 230 + (j + 1) * 13;
g.setColor(color);
if(flag1)
g.drawString(s, k, l);
if(flag)
{
g.drawLine(k + barWidth / 2, 232, k + barWidth / 2, l - 13);
g.drawLine(k + barWidth / 2, 232, (k + barWidth / 2) - 3, 237);
g.drawLine(k + barWidth / 2, 232, k + barWidth / 2 + 3, 237);
}
}
public void drawOneBar(Graphics g, int i)
{
int j = theArray[i].getHeight();
int k = 35 + i * (barWidth + barSeparation);
int l = 230 - j;
Color color = theArray[i].getColor();
g.setColor(Color.lightGray);
g.fillRect(k, 30, barWidth, 200);
g.setColor(color);
g.fill3DRect(k, l, barWidth, j, true);
}
public void draw(Graphics g)
{
if(drawMode != 2)
{
if(swapFlag)
{
drawOneBar(g, innerOld);
drawOneBar(g, innerOld + 1);
swapFlag = false;
}
} else
{
g.setColor(Color.lightGray);
g.fillRect(0, 0, 370, 320);
for(int i = 0; i < aSize; i++)
drawOneBar(g, i);
}
g.setColor(Color.lightGray);
g.fillRect(0, 0, 150, 32);
g.setColor(Color.black);
g.drawString("Comparisons = " + comps, 10, 28);
g.drawString("Swaps = " + swaps, 10, 15);
g.setColor(Color.lightGray);
g.fillRect(0, 230, 370, 65);
if(aSize == 10)
{
arrowText(g, Color.red, "outer", outer, 3, true, true);
arrowText(g, Color.blue, "inner", inner, 1, true, true);
arrowText(g, Color.blue, "inner+1", inner + 1, 1, true, true);
if(doneFlag)
arrowText(g, Color.black, "Sort is complete", inner, 2, false, true);
else
if(theArray[inner].getHeight() > theArray[inner + 1].getHeight())
arrowText(g, Color.blue, "Will be swapped", inner, 2, false, true);
else
arrowText(g, Color.blue, "Will not be swapped", inner, 2, false, true);
} else
{
arrowText(g, Color.red, "xxx", outer, 3, true, false);
arrowText(g, Color.blue, "xxx", inner, 1, true, false);
arrowText(g, Color.blue, "xxx", inner + 1, 1, true, false);
}
drawMode = 2;
}
public void sortStep()
{
if(doneFlag)
return;
comps++;
if(theArray[inner].getHeight() > theArray[inner + 1].getHeight())
{
swap(inner, inner + 1);
swapFlag = true;
swaps++;
}
innerOld = inner;
inner++;
if(inner > outer - 1)
{
inner = 0;
outer--;
if(outer == 0)
doneFlag = true;
}
}
public void swap(int i, int j)
{
personBS personbs = theArray[i];
theArray[i] = theArray[j];
theArray[j] = personbs;
}
private final int appletWidth = 370;
private final int appletHeight = 320;
private final int maxHeight = 200;
private final int topMargin = 30;
private final int leftMargin = 10;
private final int barLeftMargin = 35;
private final int textHeight = 13;
private int aSize;
private personBS theArray[];
private int barWidth;
private int barSeparation;
private int outer;
private int inner;
private int innerOld;
private boolean swapFlag;
private boolean doneFlag;
private int comps;
private int swaps;
private int initOrder;
Color newColor;
private int drawMode;
}
personBS.java
import java.awt.Color;
class personBS
{
public Color getColor()
{
return color;
}
public int getHeight()
{
return height;
}
public personBS(int i, Color color1)
{
height = i;
color = color1;
}
private int height;
private Color color;
}

Related

My GUI won't show and I can't seem to understand why?

I am writing a video game GUI and I want to firstly open a frame with a menu bar and when the user clicks on play in the menu a JPanel that is in a different class gets added to the current one and it ends up with a frame containing the menu bar and the JPanel. When I run the code bellow I don't get any errors and the console initiates the process. The problem is nothing shows on the screen?? Not the initial frame or anything else.
The code for the frame that calls the class with the JPanel is:
/*-----------------------------------------------------------------------------------------------------*/
package Testes;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Tetris extends JFrame{
private static final long serialVersionUID = 1L;
public static final int WIDTH = 250;
public static final int HEIGHT = 490;
public Tetris() {
JFrame frame = new JFrame();
TetrisBoard janela = new TetrisBoard();
JMenuBar menubar = new JMenuBar();
JMenu start = new JMenu("Start");
JMenuItem play = new JMenuItem("Play");
play.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
janela.startGame();
}
});
start.add(play);
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
start.add(exit);
JMenu help = new JMenu("Help");
JMenuItem manual = new JMenuItem("User Manual");
manual.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "The goal of Tetris is to eliminate \nas many lines as possible before\n the Tetrominoes reach the top.\nControls:\n\u2190 - Move Left\n\u2192 - Move Right\n\u2193 - Drop\n" +
"C - Rotate AntiClockwise\nV - Rotate Clockwise\nP - Pause\nEsc - Quit","Instructions", JOptionPane.OK_OPTION, new ImageIcon());
}
});
help.add(manual);
JMenuItem about = new JMenuItem("About");
about.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JLabel label = new JLabel("<html><center>Tetris made by GG<br>MEEC<br>2020<html>");
label.setHorizontalAlignment(SwingConstants.CENTER);
JOptionPane.showMessageDialog(null, label, "About", JOptionPane.INFORMATION_MESSAGE);
}
});
help.add(about);
menubar.add(start);
menubar.add(help);
frame.add(janela,BorderLayout.CENTER);
frame.add(menubar,BorderLayout.NORTH);
janela.setFocusable(true);
frame.setTitle("Tetris");
frame.setLayout(new BorderLayout());
frame.setSize(250, 490);
//setPreferredSize(new Dimension(255, 495));
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.pack();
}
public static void main(String[] args) {
new Tetris();
}
}
/*-----------------------------------------------------------------------------------------------------*/
And the class with the JPanel is:
/*-----------------------------------------------------------------------------------------------------*/
package Testes;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class TetrisBoard extends JPanel implements KeyListener/*, ActionListener*/{
private static final long serialVersionUID = 1L;
public static final int COLOR_MIN = 35;
public static final int COLOR_MAX = 255 - COLOR_MIN;
public static final int BORDER_WIDTH = 5;
public static final int COL_COUNT = 10;
public static final int VISIBLE_ROW_COUNT = 20;
public static final int HIDDEN_ROW_COUNT = 2;
public static final int ROW_COUNT = VISIBLE_ROW_COUNT + HIDDEN_ROW_COUNT;
public static final int TILE_SIZE = 24;
public static final int SHADE_WIDTH = 4;
private static final int CENTER_X = COL_COUNT * TILE_SIZE / 2;
public static final int CENTER_Y = VISIBLE_ROW_COUNT * TILE_SIZE / 2;
public static final int PANEL_WIDTH = COL_COUNT * TILE_SIZE + BORDER_WIDTH * 2;
public static final int PANEL_HEIGHT = VISIBLE_ROW_COUNT * TILE_SIZE + BORDER_WIDTH * 2;
public static final Font LARGE_FONT = new Font("Tahoma", Font.BOLD, 16);
public static final Font SMALL_FONT = new Font("Tahoma", Font.BOLD, 12);
public static final long FRAME_TIME = 20L;
public static final int TYPE_COUNT = TileType.values().length;
public boolean isPaused;
public boolean isNewGame;
public boolean isGameOver;
public int level;
public int score;
public Random random;
public Clock logicTimer;
public TileType currentType;
public TileType nextType;
public int currentCol;
private int currentRow;
public int currentRotation;
public int dropCooldown;
public float gameSpeed;
public String difficulty = "Easy";
public int newLevel;
public int lines;
public int cleared;
public TileType[][] tiles;
public TetrisBoard() {
addKeyListener(this);
this.tiles = new TileType[ROW_COUNT][COL_COUNT];
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
setBackground(Color.BLACK);
startGame();
}
public void clear() {
for(int i = 0; i < ROW_COUNT; i++) {
for(int j = 0; j < COL_COUNT; j++) {
tiles[i][j] = null;
}
}
}
public boolean isValidAndEmpty(TileType type, int x, int y, int rotation) {
if(x < -type.getLeftInset(rotation) || x + type.getDimension() - type.getRightInset(rotation) >= COL_COUNT) {
return false;
}
if(y < -type.getTopInset(rotation) || y + type.getDimension() - type.getBottomInset(rotation) >= ROW_COUNT) {
return false;
}
for(int col = 0; col < type.getDimension(); col++) {
for(int row = 0; row < type.getDimension(); row++) {
if(type.isTile(col, row, rotation) && isOccupied(x + col, y + row)) {
return false;
}
}
}
return true;
}
public void addPiece(TileType type, int x, int y, int rotation) {
for(int col = 0; col < type.getDimension(); col++) {
for(int row = 0; row < type.getDimension(); row++) {
if(type.isTile(col, row, rotation)) {
setTile(col + x, row + y, type);
}
}
}
}
public int checkLines() {
int completedLines = 0;
for(int row = 0; row < ROW_COUNT; row++) {
if(checkLine(row)) {
completedLines++;
}
}
return completedLines;
}
public boolean checkLine(int line) {
for(int col = 0; col < COL_COUNT; col++) {
if(!isOccupied(col, line)) {
return false;
}
}
for(int row = line - 1; row >= 0; row--) {
for(int col = 0; col < COL_COUNT; col++) {
setTile(col, row + 1, getTile(col, row));
}
}
return true;
}
public boolean isOccupied(int x, int y) {
return tiles[y][x] != null;
}
public void setTile(int x, int y, TileType type) {
tiles[y][x] = type;
}
public TileType getTile(int x, int y) {
return tiles[y][x];
}
//#Override
public void paintComponent(Graphics g) {
this.paintComponent(g);
g.translate(BORDER_WIDTH, BORDER_WIDTH);
if(isPaused()) {
g.setFont(LARGE_FONT);
g.setColor(Color.GREEN);
String msg = "PAUSED";
g.drawString(msg, CENTER_X - g.getFontMetrics().stringWidth(msg) / 2, CENTER_Y);
} else if(isNewGame() || isGameOver()) {
g.setFont(LARGE_FONT);
g.setColor(Color.WHITE);
g.setColor(Color.GREEN);
String msg = isNewGame() ? "TETRIS" : "GAME OVER";
g.drawString(msg, CENTER_X - g.getFontMetrics().stringWidth(msg) / 2, 150);
g.setFont(SMALL_FONT);
msg = "Press Enter to Play" + (isNewGame() ? "" : " Again");
g.drawString(msg, CENTER_X - g.getFontMetrics().stringWidth(msg) / 2, 300);
} else {
for(int x = 0; x < COL_COUNT; x++) {
for(int y = HIDDEN_ROW_COUNT; y < ROW_COUNT; y++) {
TileType tile = getTile(x, y);
if(tile != null) {
drawTile(tile, x * TILE_SIZE, (y - HIDDEN_ROW_COUNT) * TILE_SIZE, g);
}
}
}
TileType type = getPieceType();
int pieceCol = getPieceCol();
int pieceRow = getPieceRow();
int rotation = getPieceRotation();
for(int col = 0; col < type.getDimension(); col++) {
for(int row = 0; row < type.getDimension(); row++) {
if(pieceRow + row >= 2 && type.isTile(col, row, rotation)) {
drawTile(type, (pieceCol + col) * TILE_SIZE, (pieceRow + row - HIDDEN_ROW_COUNT) * TILE_SIZE, g);
}
}
}
g.setColor(Color.DARK_GRAY);
for(int x = 0; x < COL_COUNT; x++) {
for(int y = 0; y < VISIBLE_ROW_COUNT; y++) {
g.drawLine(0, y * TILE_SIZE, COL_COUNT * TILE_SIZE, y * TILE_SIZE);
g.drawLine(x * TILE_SIZE, 0, x * TILE_SIZE, VISIBLE_ROW_COUNT * TILE_SIZE);
}
}
}
g.setColor(Color.GREEN);
g.drawRect(0, 0, TILE_SIZE * COL_COUNT, TILE_SIZE * VISIBLE_ROW_COUNT);
}
public void drawTile(TileType type, int x, int y, Graphics g) {
drawTile(type.getBaseColor(), type.getLightColor(), type.getDarkColor(), x, y, g);
}
public void drawTile(Color base, Color light, Color dark, int x, int y, Graphics g) {
g.setColor(base);
g.fillRect(x, y, TILE_SIZE, TILE_SIZE);
g.setColor(dark);
g.fillRect(x, y + TILE_SIZE - SHADE_WIDTH, TILE_SIZE, SHADE_WIDTH);
g.fillRect(x + TILE_SIZE - SHADE_WIDTH, y, SHADE_WIDTH, TILE_SIZE);
g.setColor(light);
for(int i = 0; i < SHADE_WIDTH; i++) {
g.drawLine(x, y + i, x + TILE_SIZE - i - 1, y + i);
g.drawLine(x + i, y, x + i, y + TILE_SIZE - i - 1);
}
}
public void startGame() {
this.random = new Random();
this.isNewGame = true;
if(this.difficulty.equals("Easy")) {
this.gameSpeed=1.0f;
}else if(this.difficulty.equals("Intermediate")) {
this.gameSpeed=3.0f;
}else if(this.difficulty.equals("Hard")) {
this.gameSpeed=6.0f;
}
this.level=1;
this.cleared=0;
this.newLevel=0;
this.logicTimer = new Clock(gameSpeed);
logicTimer.setPaused(true);
while(true) {
long start = System.nanoTime();
logicTimer.update();
if(logicTimer.hasElapsedCycle()) {
updateGame();
}
//Decrement the drop cool down if necessary.
if(dropCooldown > 0) {
dropCooldown--;
}
renderGame();
long delta = (System.nanoTime() - start) / 1000000L; // delta in miliseconds
if(delta < FRAME_TIME) {
try {
Thread.sleep(FRAME_TIME - delta); // sleeps the difference between the fps and the time for the game to process (delta)
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
public void updateGame() {
if(isValidAndEmpty(currentType, currentCol, currentRow + 1, currentRotation)) {
currentRow++;
} else {
addPiece(currentType, currentCol, currentRow, currentRotation);
cleared = checkLines();
if(cleared > 0) {
lines += cleared;
score += 50 << cleared; // left bit shift - add the number of zeros on the right to the binary version of the number on the right
// score = score + 50 << cleared;
}
//newLevel+=cleared;
gameSpeed += 0.035f;
logicTimer.setCyclesPerSecond(gameSpeed);
logicTimer.reset();
dropCooldown = 25;
if(newLevel<10) {
newLevel+=cleared;
}else if(newLevel>=10) {
level+=1;
newLevel=0;
cleared=0;
}
spawnPiece();
}
}
public void renderGame() {
repaint();
}
public void resetGame() {
this.level = 1;
this.score = 0;
this.lines = 0;
this.newLevel = 0;
this.cleared = 0;
if(this.difficulty.equals("Easy")) {
this.gameSpeed=1.0f;
}else if(this.difficulty.equals("Intermediate")) {
this.gameSpeed=3.0f;
}else if(this.difficulty.equals("Hard")) {
this.gameSpeed=6.0f;
}
this.nextType = TileType.values()[random.nextInt(TYPE_COUNT)];
this.isNewGame = false;
this.isGameOver = false;
clear();
logicTimer.reset();
logicTimer.setCyclesPerSecond(gameSpeed);
spawnPiece();
}
public void spawnPiece() {
this.currentType = nextType;
this.currentCol = currentType.getSpawnColumn();
this.currentRow = currentType.getSpawnRow();
this.currentRotation = 0;
this.nextType = TileType.values()[random.nextInt(TYPE_COUNT)];
if(!isValidAndEmpty(currentType, currentCol, currentRow, currentRotation)) {
lose();
}
}
public void lose()
{
this.isGameOver = true;
logicTimer.setPaused(isPaused);
String info = "";
if (score>HighScore.getHighScores()[9].getScore())
{
info="You got a high score!\n<br>Please enter you name.\n<br>(Note: Only 10 characters will be saved)";
JLabel label = new JLabel("<html><center>GAME OVER\n<br>" + info);
label.setHorizontalAlignment(SwingConstants.CENTER);
String name=JOptionPane.showInputDialog(null, label,"Tetris", JOptionPane.INFORMATION_MESSAGE);
if (name!=null) {
HighScore.addHighScore(new HighScore(score,level,lines,(name.length()>10)?name.substring(0, 10):name,(difficulty.length()>12)?difficulty.substring(0, 12):difficulty));
}
}else {
info="You didn't get a high score:( \n<br>Keep trying you will get it next time!";
JLabel label = new JLabel("<html><center>GAME OVER\n<br>" + info);
label.setHorizontalAlignment(SwingConstants.CENTER);
JOptionPane.showMessageDialog(null, label, "Tetris", JOptionPane.PLAIN_MESSAGE);
}
if (JOptionPane.showConfirmDialog(null, "Do you want to play again?",
"Tetris", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) {
this.score=0;
this.level=0;
this.lines=0;
startGame();
}else
{
//If not, quit
System.exit(0);
}
}
public void rotatePiece(int newRotation) {
int newColumn = currentCol;
int newRow = currentRow;
int left = currentType.getLeftInset(newRotation);
int right = currentType.getRightInset(newRotation);
int top = currentType.getTopInset(newRotation);
int bottom = currentType.getBottomInset(newRotation);
if(currentCol < -left) {
newColumn -= currentCol - left;
} else if(currentCol + currentType.getDimension() - right >= COL_COUNT) {
newColumn -= (currentCol + currentType.getDimension() - right) - COL_COUNT + 1;
}
if(currentRow < -top) {
newRow -= currentRow - top;
} else if(currentRow + currentType.getDimension() - bottom >= ROW_COUNT) {
newRow -= (currentRow + currentType.getDimension() - bottom) - ROW_COUNT + 1;
}
if(isValidAndEmpty(currentType, newColumn, newRow, newRotation)) {
currentRotation = newRotation;
currentRow = newRow;
currentCol = newColumn;
}
}
public boolean isPaused() {
return isPaused;
}
public boolean isGameOver() {
return isGameOver;
}
public boolean isNewGame() {
return isNewGame;
}
public int getScore() {
return score;
}
public int getLevel() {
return level;
}
public String getDiff(){
return difficulty;
}
public int getLines() {
return lines;
}
public TileType getPieceType() {
return currentType;
}
public TileType getNextPieceType() {
return nextType;
}
public int getPieceCol() {
return currentCol;
}
public int getPieceRow() {
return currentRow;
}
public int getPieceRotation() {
return currentRotation;
}
//#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN:
if(!isPaused && dropCooldown == 0) {
logicTimer.setCyclesPerSecond(25.0f);
}
break;
case KeyEvent.VK_LEFT:
if(!isPaused && isValidAndEmpty(currentType, currentCol - 1, currentRow, currentRotation)) {
currentCol--;
}
break;
case KeyEvent.VK_RIGHT:
if(!isPaused && isValidAndEmpty(currentType, currentCol + 1, currentRow, currentRotation)) {
currentCol++;
}
break;
case KeyEvent.VK_C:
if(!isPaused) {
rotatePiece((currentRotation == 0) ? 3 : currentRotation - 1);
}
break;
case KeyEvent.VK_V:
if(!isPaused) {
rotatePiece((currentRotation == 3) ? 0 : currentRotation + 1);
}
break;
case KeyEvent.VK_P:
if(!isGameOver && !isNewGame) {
isPaused = !isPaused;
logicTimer.setPaused(isPaused);
}
break;
case KeyEvent.VK_ENTER:
if(isGameOver || isNewGame) {
resetGame();
}
break;
case KeyEvent.VK_ESCAPE:
int ans = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?\n", "Tetris", JOptionPane.INFORMATION_MESSAGE);
if(ans==1 || ans==2) {
//isPaused = !isPaused;
//logicTimer.setPaused(isPaused);
return;
}else if(ans==0) {
System.exit(0);
}
}
}
}
//#Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_S:
logicTimer.setCyclesPerSecond(gameSpeed);
logicTimer.reset();
break;
}
}
#Override
public void keyTyped(KeyEvent e) {}
}
First of all, dont add a JMenuBar by frame.add(myJMenuBar,someConstraints). Do it by calling the method frame.setJMenuBar(myJMenuBar);
Secondly, you add the components into the frame (its content pane), and after that you frame.setLayout(new BorderLayout());, while you should first set the layout and AFTER add the components to it:
frame.setLayout(new BorderLayout());
frame.add(janela, BorderLayout.CENTER);
This works:
You might notice it replaces the ridiculously long & complicated TetrisBoard with a red panel with a preferred size of 400 x 200. This is how you should figure such things out. Post a minimal reproducible example in future.
import java.awt.*;
import javax.swing.*;
public class Tetris extends JFrame {
public Tetris() {
JFrame frame = new JFrame();
JPanel janela = new JPanel();
janela.setBackground(Color.RED);
janela.setPreferredSize(new Dimension(400,200));
JMenuBar menubar = new JMenuBar();
JMenu start = new JMenu("Start");
JMenuItem play = new JMenuItem("Play");
start.add(play);
JMenuItem exit = new JMenuItem("Exit");
start.add(exit);
JMenu help = new JMenu("Help");
JMenuItem manual = new JMenuItem("User Manual");
help.add(manual);
JMenuItem about = new JMenuItem("About");
help.add(about);
menubar.add(start);
menubar.add(help);
frame.add(janela, BorderLayout.CENTER);
frame.setJMenuBar(menubar);
janela.setFocusable(true);
frame.setTitle("Tetris");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new Tetris();
}
}

Keep getting Error: The method getImg() is undefined for the type javax.swing.ImageIcon

My friend code this brick breaker game rip off, but he keep getting this error
"Error: The method getImg() is undefined for the type javax.swing.ImageIcon" and I don't know how to fix it. Can someone help?
here the code:
public class Ball extends Sprite implements iFace{
private int xDir;
private int yDir;
public Ball(){
xDir = 1;
yDir = -1;
String path = "MAJOR_JAVA_ASSESSMENT/ball.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(path));
img = i.getImg();
iWidth = img.getWidth(null);
iHeight = img.getHeight(null);
reset(); }
public void move()
{
x += xDir;
y += yDir;
if(x == 0)
{
setXDir(1);
}
if(x == width - iWidth)
{
setXDir(-1);
}
if (y == 0)
{
setYDir(1);
} }
private void reset()
{
x = initBallX;
y = initBallY;
}
public void setXDir(int x)
{
xDir = x;
}
public void setYDir(int y)
{
yDir = y;
}
public int getYDir()
{
return yDir;
}
}
here another code for you:
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;
public class Board extends JPanel implements iFace
{
private Timer timer;
private String message = "You lose";
private Ball ball;
private Paddle paddle;
private Brick bricks[];
private boolean inGame = true;
public Board()
{
initBoard();
}
private void initBoard()
{
addKeyListener(new timeAdapter());
setFocusable(true);
bricks = new Brick[numOfBricks];
setDoubleBuffered(true);
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(), delay, period);
}
#Override
public void addNotify()
{
super.addNotify();
gameInit();
}
private void gameInit()
{
ball = new Ball();
paddle = new Paddle();
int k = 0;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
bricks[k] = new Brick(j * 40 + 30, i * 10 + 50);
k++;
}
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D graphics2D = (Graphics2D) g;
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
if (inGame)
{
drawObj(graphics2D);
}
else
{
gameDone(graphics2D);
}
Toolkit.getDefaultToolkit().sync();
}
private void drawObj(Graphics graphics2D)
{
graphics2D.drawImage(ball.getImg(), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight(), this);
graphics2D.drawImage(paddle.getImg(), paddle.getX(), paddle.getY(), paddle.getWidth(), paddle.getHeight(), this);
for (int i = 0; i < numOfBricks; i++)
{
if(!bricks[i].isDead())
{
graphics2D.drawImage(bricks[i].getImg(), bricks[i].getX(), bricks[i].getY(), bricks[i].getWidth(), bricks[i].getHeight(), this);
}
}
}
private void gameDone(Graphics2D graphics2D)
{
Font f = new Font("TimesRoman", Font.BOLD, 20);
FontMetrics fm = this.getFontMetrics(f);
graphics2D.setColor(Color.RED);
graphics2D.setFont(f);
graphics2D.drawString(message, (iFace.width - fm.stringWidth(message)) / 2, iFace.width / 2);
}
private class timeAdapter extends KeyAdapter
{
#Override
public void keyReleased(KeyEvent p)
{
keyReleased(p);
}
#Override
public void keyPressed(KeyEvent p)
{
keyPressed(p);
}
}
private class ScheduleTask extends TimerTask
{
#Override
public void run()
{
ball.move();
paddle.move();
checkCollision();
repaint();
}
}
private void stopGame()
{
inGame = false;
timer.cancel();
}
private void checkCollision()
{
if(ball.getRectangle().getMaxY() > iFace.bottom)
{
stopGame();
}
for(int i = 0, j = 0; i < numOfBricks; i++)
{
if(bricks[i].isDead())
{
j++;
}
if(j == numOfBricks)
{
message = "GG YOU WIN";
stopGame();
}
}
if ((ball.getRectangle()).intersects(paddle.getRectangle()))
{
int paddlePos = (int) paddle.getRectangle().getMinX();
int ballPos = (int) ball.getRectangle().getMinX();
int first = paddlePos + 8;
int second = paddlePos + 16;
int third = paddlePos + 24;
int fourth = paddlePos + 32;
if (ballPos < first)
{
ball.setXDir(-1);
ball.setYDir(-1);
}
if (ballPos >= first && ballPos < second)
{
ball.setXDir(-1);
ball.setYDir(-1 + ball.getYDir());
}
if (ballPos >= second && ballPos < third)
{
ball.setXDir(0);
ball.setYDir(-1);
}
if (ballPos >= third && ballPos < fourth)
{
ball.setXDir(1);
ball.setYDir(-1);
}
}
for (int i = 0; i < numOfBricks; i++)
{
if ((ball.getRectangle()).intersects(bricks[i].getRectangle()))
{
int ballLeft = (int) ball.getRectangle().getMinX();
int ballHeight = (int) ball.getRectangle().getHeight();
int ballWidth = (int) ball.getRectangle().getWidth();
int ballTop = (int) ball.getRectangle().getMinY();
Point pR = new Point(ballLeft + ballWidth + 1, ballTop);
Point pL = new Point(ballLeft - 1, ballTop);
Point pT = new Point(ballLeft, ballTop - 1);
Point pB = new Point(ballLeft, ballTop + ballHeight + 1);
if (!bricks[i].isDead())
{
if (bricks[i].getRectangle().contains(pR))
{
ball.setXDir(-1);
}
else if
(bricks[i].getRectangle().contains(pL))
{
ball.setXDir(1);
}
if (bricks[i].getRectangle().contains(pT))
{
ball.setYDir(1);
}
else if (bricks[i].getRectangle().contains(pB))
{
ball.setYDir(-1);
}
bricks[i].setDeath(true);
}
}
}
}
}
i only give you the ball code as the two codes that have problems are basically have the same problem, so if someone can fix this one then, then we can the rest.
Also give you board as it the biggest and most important code, so this code may be the problem?
Thank you for reading this, and I hope you can help my friend.
getImg does not exist in the ImageIcon API, I think you'll find that it's ImageIcon#getImage instead
Having said that, I'd recommend using the ImageIO API instead

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;
}
}

How to find out whether a shape has touch another shape?

I have a working class where I can move a circle around the screen using the keyboard while there are other circles moving across the screen at different speeds.
I reached this point, and I'm trying to figure out how to make it so that I can find out whether my shape has touched another shape, but that's the part I'm stuck at, as I don't have many ideas about how to make it work. I have tried various methods, but most of them don't work.
public class Test extends Panel implements Runnable, KeyListener, MouseMotionListener {
static final int left = 37;
static final int right = 39;
static final int down = 40;
static final int up = 38;
static boolean leftPress = false;
static boolean rightPress = false;
static boolean upPress = false;
static boolean downPress = false;
/*****/
static int upperLeftX;
static int upperLeftY;
static int lowerLeftX;
static int lowerLeftY;
static int upperRightX;
static int upperRightY;
static int lowerRightX;
static int lowerRightY;
int eUpperLeftX;
int eUpperLeftY;
int eLowerLeftX;
int eLowerLeftY;
int eUpperRightX;
int eUpperRightY;
int eLowerRightX;
int eLowerRightY;
/*****/
static boolean eat = false;
static boolean eaten = false;
static int mouseLocationX;
static int mouseLocationY;
static String mouseLocation = "";
/**/
int x1_;
int y1_;
int eSize;
int eRandSpawn;
int sleep;
Color eColor;
/**/
static int x1 = 250;
static int y1 = 250;
static int size = 30;
static JFrame frame = new JFrame("Fishy");
static Test panel = new Test(500, 500, 9);
// static Test time1 = new Test(1000);
// static Test time2 = new Test(500);
// static Test time3 = new Test(250);
// static Test time4 = new Test(Methods.randNum(6,20),Methods.randNum(0, 450));
// static Test time5 = new Test(Methods.randNum(6,20),Methods.randNum(0, 450));
static Test eFish[] = new Test[20];
/** CONSTRUCTOR **/
public Test() {
sleep = Methods.randNum(6, 50);
y1_ = Methods.randNum(0, 450);
eRandSpawn = Methods.randNum(1, 2);
eColor = Methods.randColor();
eSize = Methods.randNum(5, 120);
if (eRandSpawn == 1) {
x1_ = -100;
} else {
x1_ = 600;
}
eUpperLeftX = x1_;
eUpperLeftY = y1_;
eLowerLeftX = x1_;
eLowerLeftY = y1_ + eSize;
eUpperRightX = x1_ + eSize;
eUpperRightY = y1_;
eLowerRightX = x1_ + eSize;
eLowerRightY = x1_ + eSize;
}
/** CONSTRUCTOR **/
public Test(int width, int length, int minusBy) {
super(width, length, minusBy);
}
/** MAIN **/
public static void main(String args[]) throws InterruptedException {
for (int i = 0; i < 20; i++) {
eFish[i] = new Test();
}
Thread time[] = new Thread[20];
for (int i = 0; i < 20; i++) {
time[i] = new Thread(eFish[i]);
}
// Thread time1_ = new Thread(time1);
// Thread time2_ = new Thread(time2);
// Thread time3_ = new Thread(time3);
// Thread time4_ = new Thread(time4);
// Thread time5_ = new Thread(time5);
frame.add(panel);
frame.addKeyListener(panel);
panel.addMouseMotionListener(panel);
Frame.showFrame(frame);
// time1_.start();
// time2_.start();
// time3_.start();
// time4_.start();
// time5_.start();
for (int i = 0; i < 20; i++) {
time[i].start();
}
while (true) {
if (upPress) {
y1--;
}
if (downPress) {
y1++;
}
if (leftPress) {
x1--;
}
if (rightPress) {
x1++;
}
if (upPress || downPress || leftPress || rightPress) {
upperLeftX = x1;
upperLeftY = y1;
lowerLeftX = x1;
lowerLeftY = y1 + size;
upperRightX = x1 + size;
upperRightY = y1;
lowerRightX = x1 + size;
lowerRightY = x1 + size;
Thread.sleep(6);
frame.repaint();
}
for (int i = 0; i < 20; i++) {
if (eat) {
size++;
eFish[i].eRandSpawn = Methods.randNum(1, 2);
if (eFish[i].eRandSpawn == 1) {
eFish[i].y1_ = Methods.randNum(0, 450);
eFish[i].x1_ = -100;
eFish[i].sleep = Methods.randNum(6, 50);
eFish[i].eSize = Methods.randNum(5, 120);
eFish[i].eColor = Methods.randColor();
} else {
eFish[i].y1_ = Methods.randNum(0, 450);
eFish[i].x1_ = 600;
eFish[i].sleep = Methods.randNum(6, 50);
eFish[i].eSize = Methods.randNum(5, 120);
eFish[i].eColor = Methods.randColor();
}
eFish[i].eUpperLeftX = eFish[i].x1_;
eFish[i].eUpperLeftY = eFish[i].y1_;
eFish[i].eLowerLeftX = eFish[i].x1_;
eFish[i].eLowerLeftY = eFish[i].y1_ + eFish[i].eSize;
eFish[i].eUpperRightX = eFish[i].x1_ + eFish[i].eSize;
eFish[i].eUpperRightY = eFish[i].y1_;
eFish[i].eLowerRightX = eFish[i].x1_ + eFish[i].eSize;
eFish[i].eLowerRightY = eFish[i].x1_ + eFish[i].eSize;
}
eat = false;
}
}
}
/** PAINT **/
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.CYAN);
g.fillRect(0, 0, 501, 501);
g.setColor(Color.BLACK);
mouseLocation = String.format("%s,%s,%s", x1, y1, size);
g.drawString(mouseLocation, 100, 100);
g.setColor(Color.GREEN);
g.fillOval(x1, y1, size, size);
// g.drawOval(time4.x1_,time4.y1_,50,50);
// g.drawOval(time5.x1_,time5.y1_,50,50);
for (int i = 0; i < 20; i++) {
g.setColor(eFish[i].eColor);
g.fillOval(eFish[i].x1_, eFish[i].y1_, eFish[i].eSize, eFish[i].eSize);
}
/*
* for (int i = 0; i < 10; i++) { g.setColor(Methods.randColor()); g.drawRect(x1 + i, y1 + i, width - i * 2, height - i * 2);
*
* }
*/
// g.drawString(time1.time, 20, 50);
// g.drawString(time2.time, 20, 100);
// g.drawString(time3.time, 20, 150);
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(sleep);
eUpperLeftX = x1_;
eUpperLeftY = y1_;
eLowerLeftX = x1_;
eLowerLeftY = y1_ + eSize;
eUpperRightX = x1_ + eSize;
eUpperRightY = y1_;
eLowerRightX = x1_ + eSize;
eLowerRightY = x1_ + eSize;
if (x1_ == -150) {
y1_ = Methods.randNum(0, 450);
x1_ = 600;
sleep = Methods.randNum(6, 50);
eSize = Methods.randNum(5, 120);
eColor = Methods.randColor();
}
if (x1_ == 650) {
y1_ = Methods.randNum(0, 450);
x1_ = -100;
sleep = Methods.randNum(6, 50);
eSize = Methods.randNum(5, 120);
eColor = Methods.randColor();
}
if (eRandSpawn == 1) {
x1_++;
} else {
x1_--;
}
frame.repaint();
} catch (InterruptedException e) {
}
}
}
#Override
public void keyPressed(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = true;
}
if (down == e.getKeyCode()) {
downPress = true;
}
if (left == e.getKeyCode()) {
leftPress = true;
}
if (right == e.getKeyCode()) {
rightPress = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = false;
}
if (down == e.getKeyCode()) {
downPress = false;
}
if (left == e.getKeyCode()) {
leftPress = false;
}
if (right == e.getKeyCode()) {
rightPress = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent e) {
mouseLocationX = e.getX();
mouseLocationY = e.getY();
mouseLocation = String.format("%s,%s", mouseLocationX, mouseLocationY);
frame.repaint();
}
}
public boolean madeContact(Ellipse a, Ellipse b) {
//Center of ellipse
int ax = a.getX(), ay = a.getY(), bx = b.getX(), by = b.getY();
//Radii
int arx = a.getRadiusX(), ary = a.getRadiusY();
int brx = b.getRadiusX(), bry = b.getRadiusY();
//Has hit x, y
boolean hitx = Math.abs(ax - bx) < arx+brx;
boolean hity = Math.abs(ay - by) < ary+bry;
return hitx && hity;
}

Drawing curve bit by bit

I need to draw a curve, knowing that I receive points every x milliseconds or x seconds, and that the curve is moving to the left by one pixel each time I receive a new point. I'm using the Bezier algorithm to draw the curve from the points I receive, so I need at least three points to start. I would like to know how to proceed to draw the curve bit by bit on an image.
This is what I'm doing right now:
int xPos = 0;
Point2D.Double[] points = new Point2D.Double[listYpos.size()];
for (int i = 0; i < listYpos.size(); i++) {
points[i] = new Point2D.Double(i, listYpos.get(i));
}
if (curveImg == null) {
curveImg = gc.createCompatibleImage(imageWidth, imageHeight, Transparency.BITMASK);
}
if (points.length > 3) {
Graphics2D gImg = (Graphics2D) curveImg.getGraphics();
renderCurve(gImg, Arrays.copyOfRange(points, listYpos.size() - 4, listYpos.size() - 1));
gImg.dispose();
}
AffineTransform at = g.getTransform();
at.scale(-1, 1);
at.translate(-xPos++, listYpos.get(listYpos.size() - 1));
g.drawImage(curveImg, at, null);
This method is called each time a new point is received every x milliseconds or x seconds.
I think that gImg.dispose();
maybe this code can help you with that (from old.forums.sun.com)
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.swing.*;
public class BezierTest {
private class Animator implements ActionListener {
private double distance = 0;
private boolean moveTo = true;
private ArrayList<Point2D> points = new ArrayList<Point2D>();
private double step = -1;
private double steps;
private Timer timer = new Timer(0, this);
#Override
public void actionPerformed(ActionEvent e) {
step++;
if (step <= steps) {
double t = step / steps;
Point2D newPoint = computeBezierPoint(new Point2D.Double(), t, curvePoints);
marks[marks.length - 1].setFrame(newPoint.getX() - 5, newPoint.getY() - 5, 10, 10);
points.add(newPoint);
if (moveTo) {
path.moveTo(newPoint.getX(), newPoint.getY());
moveTo = false;
} else {
path.lineTo(newPoint.getX(), newPoint.getY());
}
lines[3] = new Line2D.Double(computePointOnLine(lines[0], t), computePointOnLine(lines[1], t));
lines[4] = new Line2D.Double(computePointOnLine(lines[1], t), computePointOnLine(lines[2], t));
lines[5] = new Line2D.Double(computePointOnLine(lines[3], t), computePointOnLine(lines[4], t));
// The maximum distance encountered between the results of two calculation methods.
// newPoint from computeBezierPoint() the other via the lines method
distance = Math.max(distance, newPoint.distance(computePointOnLine(lines[5], t)));
demoComponent.repaint();
} else {
timer.stop();
animationButton.setEnabled(true);
if (distance > 0d) {
System.out.println("Maximum difference " + distance);
}
}
}
public void init() {
timer.stop();
animationButton.setEnabled(false);
steps = sliderStep.getValue();
step = -1;
distance = 0;
moveTo = true;
path = new Path2D.Double();
int sleepTime = (int) Math.round(1000d * sliderDuration.getValue() / steps);
timer.setDelay(sleepTime);
timer.setInitialDelay(0);
timer.start();
}
private Point2D computeBezierPoint(Point2D rv, double t,
Point2D... curve) {
if (rv == null) {
rv = new Point2D.Double();
} else {
rv.setLocation(0, 0);
}
int n = curve.length - 1;
double oneMinusT = 1.0 - t;
for (int index = 0; index < curve.length; index++) {
double multiplier = index == 0 || index == n ? 1 : StrictMath.min(n - index, index) * n;
multiplier *= StrictMath.pow(t, index) * StrictMath.pow(oneMinusT, n - index);
rv.setLocation(rv.getX() + multiplier * curve[index].getX(), rv.getY() + multiplier * curve[index].getY());
}
return rv;
}
private Point2D computePointOnLine(Line2D line, double t) {
return new Point2D.Double((line.getX2() - line.getX1()) * t + line.getX1(), (line.getY2() - line.getY1()) * t + line.getY1());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new BezierTest().createGUI();
}
});
}
private final JButton animationButton = new JButton(new AbstractAction("Start animation") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
animator.init();
}
});
private final Animator animator = new Animator();
private Point2D[] curvePoints = new Point2D[]{new Point(10, 50), new Point(190, 10), new Point(190, 190), new Point(10, 150)};
private JComponent demoComponent = new JComponent() {
private static final long serialVersionUID = 1L;
{
setPreferredSize(new Dimension(400, 400));
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
int w = getWidth();
int h = getHeight();
recalculateAfterResize(w, h);
}
});
}
#Override
protected void paintComponent(Graphics g) {
if (isVisible()) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
paintBezier(g);
}
}
};
private Line2D[] lines = new Line2D[6];
private final Ellipse2D[] marks;
private Path2D path;
private final JSlider sliderDuration = createSlider(1, 20, 2, "Duration in seconds", 9, 1);
private final JSlider sliderStep = createSlider(8, 128, 64, "Animation steps", 16, 1);
private Path2D totalCurve;
{
marks = new Ellipse2D[curvePoints.length + 1];
for (int index = 0; index < marks.length; index++) {
marks[index] = new Ellipse2D.Double();
}
}
private void createGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(demoComponent, BorderLayout.CENTER);
JToolBar toolBar = new JToolBar();
toolBar.add(animationButton);
toolBar.add(sliderStep);
toolBar.add(sliderDuration);
frame.add(toolBar, BorderLayout.PAGE_START);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
private JSlider createSlider(int min, int max, int value, String title, int major, int minor) {
JSlider slider = new JSlider(min, max, value);
slider.setBorder(BorderFactory.createTitledBorder(title));
slider.setMajorTickSpacing(major);
// slider.setMinorTickSpacing(minor);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
return slider;
}
private void paintBezier(Graphics g) {
Path2D path1 = this.path;
if (path1 != null) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.GREEN);
for (Shape mark : marks) {
g2.fill(mark);
}
g2.setStroke(new BasicStroke(2f));
g2.setColor(Color.BLACK);
for (Shape mark : marks) {
g2.draw(mark);
}
g2.setStroke(new BasicStroke(0f));
g2.draw(totalCurve);
g2.setStroke(new BasicStroke(1f));
g2.setColor(Color.RED);
g2.draw(path1);
g2.setStroke(new BasicStroke(.5f));
g2.setColor(Color.BLACK);
for (Line2D line : lines) {
if (line != null) {
g2.draw(line);
}
}
}
}
private void recalculateAfterResize(int w, int h) {
curvePoints = new Point2D[]{new Point2D.Double(10, h / 4.0), new Point2D.Double(w - 10, 10), new Point2D.Double(w - 10, h - 10), new Point2D.Double(10, h - h / 4.0)};
totalCurve = new Path2D.Double();
totalCurve.moveTo(curvePoints[0].getX(), curvePoints[0].getY());
totalCurve.curveTo(curvePoints[1].getX(), curvePoints[1].getY(), curvePoints[2].getX(), curvePoints[2].getY(), curvePoints[3].getX(), curvePoints[3].getY());
for (int index = 0; index < curvePoints.length; index++) {
marks[index].setFrame(curvePoints[index].getX() - 5, curvePoints[index].getY() - 5, 10, 10);
}
marks[marks.length - 1].setFrame(marks[0].getFrame());
for (int index = 0; index < curvePoints.length - 1; index++) {
lines[index] = new Line2D.Double(curvePoints[index], curvePoints[index + 1]);
}
lines[3] = null;
lines[4] = null;
lines[5] = null;
animator.init();
}
}

Categories

Resources