I'm trying to make a simulation on our school's enrollment system. But I'm stuck on a problem that i can't figure out why, the box that i rendered are blinking. I need it not to. can you help me? thanks.
import java.awt.Color;
import java.awt.*;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates and open the template
* in the editor.
*/
/**
*
* #author paolo
*/
public class simulator extends JPanel {
Thread tr;
Image i;
Graphics gbfr;
Dimension size;
int num = 0, check, wid, hyt, oq;
Random rand = new Random();
Dimension locs[];
list waiting, queue;
boolean allowMove = false;
simulator(int w, int h) {
oq = 0;
wid = w;
hyt = h;
tr = new tr1();
locs = new Dimension[30];
waiting = new list(50);
queue = new list(30);
int tw, u;
for (u = 0, tw = 64; u < 10; u++, tw += 55) {
locs[u] = new Dimension(tw, 275);
locs[19 - u] = new Dimension(tw, 325);
locs[u + 20] = new Dimension(tw, 375);
}
}
public void paint(Graphics g) {
i = createImage(getWidth(), getHeight());
gbfr = i.getGraphics();
gbfr.setColor(getBackground());
gbfr.fillRect(0, 0, getWidth(), getHeight());
gbfr.setColor(getForeground());
paintComponent(gbfr);
g.drawImage(i, 0, 0, this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
drawSettings(g);
drawStudents(g);
}
protected void drawSettings(Graphics g) {
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, 600, 200);
g.setColor(Color.black);
g.drawRect(0, 200, 20, 20);
g.drawRect(145, 200, 20, 20);
g.drawRect(290, 200, 20, 20);
g.drawRect(435, 200, 20, 20);
g.drawRect(580, 200, 20, 20);
g.drawRect(0, 0, 600, 200);
g.setColor(new Color(200, 200, 200));
g.fillRect(1, 180, 19, 40);
g.fillRect(146, 180, 19, 40);
g.fillRect(291, 180, 19, 40);
g.fillRect(436, 180, 19, 40);
g.fillRect(581, 180, 19, 40);
g.setColor(Color.black);
g.drawString("Cashier 1", 62, 190);
g.drawString("Cashier 2", 207, 190);
g.drawString("Cashier 3", 352, 190);
g.drawString("Cashier 4", 497, 190);
g.fillRect(20, 270, 560, 20);//
g.fillRect(20, 320, 560, 20);
g.fillRect(20, 370, 560, 20);
}
protected void drawStudents(Graphics g) {
waiting.drawStudents(g);
}
public class tr1 extends Thread implements Runnable {
public void run() {
for (check = 0;; check++) {
num++;
try {
if (num % 100 == 0 && waiting.max != waiting.countL) {
waiting.add();
}
repaint();
Thread.sleep(1);
} catch (InterruptedException e) {
}
//repaint();
}
}
}
public class list {
int max, countL;
students temp, head;
list() {
head = new students();
countL = 0;
head.setNext(null);
max = 0;
}
list(int m) {
countL = 0;
head = new students(1);
list();
max = m;
head.setNext(null);
}
void add() {
students t;
t = head;
if (countL == 0) {
countL++;
t.setNext(new students());
} else {
temp = head.getNext();
while (temp != null) {
temp = temp.getNext();
}
countL++;
head.setNext(new students());
//updateCount();
}
}
void delete(int c) {
students t = head, t1;
int aa = 1;
if (countL == 1) {
if (c == 1) {
t.setNext(null);
}
} else {
if (c == 1) {
t.setNext(t.getNext());
} else {
for (t = t.getNext(); aa < c; aa++, t = t.getNext()) {
}
t.setNext(t.getNext().getNext());
}
}
}
void updateCount() {
students t = new students();
t = head;
t = t.getNext();
System.out.println(countL + "__");
for (int q = 1; q < countL; q++) {
System.out.println(t);
t.setCount(q);
t = t.getNext();
}
}
void drawStudents(Graphics g) {
students t = head;
if (countL != 0) {
t = t.getNext();
while (t != null) {
g.setColor(t.getClr());
g.fillRect(t.xpos, t.ypos, 10, 10);
t = t.getNext();
}
}
}
}
public class students {
int xpos, ypos, year, level, servtime, waittime, pos, destx, desty, count;
Color clr;
boolean active, onq;
students next;
students() {
//System.out.print("Recieved");
xpos = rand.nextInt((wid - 580) + 1) + 580;
onq = false;
ypos = rand.nextInt((hyt - 280) + 1) + 280;
waittime = rand.nextInt((100 - 50) + 1) + 50;
servtime = rand.nextInt((200 - 100) + 1) + 100;
count = 0;
level = 0;
next = null;
year = rand.nextInt((4 - 1) + 1) + 1;
clr = new Color(12, 12, 12);
if (year == 1) {
clr = Color.GREEN;
} else if (year == 2) {
clr = Color.YELLOW;
} else if (year == 3) {
clr = Color.RED;
} else {
clr = Color.BLUE;
}
pos = 0;
active = false;
}
students(int i) {
count = 0;
}
void setxpos(int x) {
xpos = x;
}
void setypos(int y) {
ypos = y;
}
void setpos(int p) {
pos = p;
}
void setCount(int q) {
count = q;
}
students getNext() {
return next;
}
Color getClr() {
return clr;
}
void setNext(students n) {
next = n;
}
int getpos() {
return pos;
}
boolean isActive() {
return active;
}
void activate() {
active = true;
}
}
}
Don't override the simulator JPanel's paint(Graphics g) method
Don't call paintComponent directly. You mess with all of Swing's graphics by doing these two things.
Draw your stable background image to a BufferedImage, and then draw the image in your JPanel's paintComponent(Graphics g) method.
Note that your code does not reproduce your problem for me. I don't see any blinking. Should there be some animation going on that we're not seeing?
e.g.,
// class names should begin with an upper-case letter
public class Simulator extends JPanel {
// ....
private BufferedImage settings = null;
Simulator(int w, int h) {
// ....
settings = createSettings();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(wid, hyt);
}
// public void paint(Graphics g) {
// i = createImage(getWidth(), getHeight());
// gbfr = i.getGraphics();
// gbfr.setColor(getBackground());
// gbfr.fillRect(0, 0, getWidth(), getHeight());
//
// gbfr.setColor(getForeground());
// paintComponent(gbfr);
//
// g.drawImage(i, 0, 0, this);
// }
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
if (settings != null) {
g.drawImage(settings, 0, 0, this);
}
// !! drawSettings(g);
drawStudents(g);
}
private BufferedImage createSettings() {
int width = 700;
int height = 500;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, 600, 200);
g.setColor(Color.black);
g.drawRect(0, 200, 20, 20);
g.drawRect(145, 200, 20, 20);
g.drawRect(290, 200, 20, 20);
g.drawRect(435, 200, 20, 20);
g.drawRect(580, 200, 20, 20);
g.drawRect(0, 0, 600, 200);
g.setColor(new Color(200, 200, 200));
g.fillRect(1, 180, 19, 40);
g.fillRect(146, 180, 19, 40);
g.fillRect(291, 180, 19, 40);
g.fillRect(436, 180, 19, 40);
g.fillRect(581, 180, 19, 40);
g.setColor(Color.black);
g.drawString("Cashier 1", 62, 190);
g.drawString("Cashier 2", 207, 190);
g.drawString("Cashier 3", 352, 190);
g.drawString("Cashier 4", 497, 190);
g.fillRect(20, 270, 560, 20);//
g.fillRect(20, 320, 560, 20);
g.fillRect(20, 370, 560, 20);
g.dispose();
return img;
}
// ...
}
Related
I'm trying to create a moving sprite in java, which I have managed to do, except every time I move it there is an afterimage that follows the sprite. Are there any ways I could easily fix this problem without radically changing my code?
I'm completely stumped as to any kind of ways I could fix this problem.
To get the full context I have to post all three files.
Here's the first file:
package gameproject;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class CarMovement {
private int dx;
private int dy;
private int x = 635;
private int y = 550;
private int w;
private int h;
private Image moveimage;
public CarMovement() {
loadImage();
}
private void loadImage() {
ImageIcon q = new ImageIcon("racecar.png");
moveimage = q.getImage();
w = moveimage.getWidth(null);
h = moveimage.getHeight(null);
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public Image getImage() {
return moveimage;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = -10;
}
if (key == KeyEvent.VK_D) {
dx = 10;
}
if (key == KeyEvent.VK_W) {
dy = -10;
}
if (key == KeyEvent.VK_S) {
dy = 10;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = 0;
}
if (key == KeyEvent.VK_D) {
dx = 0;
}
if (key == KeyEvent.VK_W) {
dy = 0;
}
if (key == KeyEvent.VK_S) {
dy = 0;
}
}
}
The second:
package gameproject;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CarMovement2 extends JPanel implements ActionListener {
private Timer timer;
private CarMovement racecar;
private final int DELAY = 10;
public CarMovement2() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
racecar = new CarMovement();
timer = new Timer(DELAY, this);
timer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0, 204, 0));
g.fillRect(0, 0, 400, 1100);
g.fillRect(1525, 0, 400, 1100);
g.setColor(new Color(102, 102, 102));
g.fillRect(400, 0, 1125, 1100);
g.setColor(new Color(255, 255, 255));
g.fillRect(940, 25, 25, 100);
g.fillRect(940, 325, 25, 100);
g.fillRect(940, 475, 25, 100);
g.fillRect(940, 625, 25, 100);
g.fillRect(940, 775, 25, 100);
g.fillRect(940, 925, 25, 100);
g.setColor(new Color(255, 255, 255));
g.fillRect(400, 175, 1125, 100);
g.setColor(new Color(0, 0, 0));
g.fillRect(400, 225, 50, 50);
g.fillRect(450, 175, 50, 50);
g.fillRect(500, 225, 50, 50);
g.fillRect(550, 175, 50, 50);
g.fillRect(600, 225, 50, 50);
g.fillRect(650, 175, 50, 50);
g.fillRect(700, 225, 50, 50);
g.fillRect(750, 175, 50, 50);
g.fillRect(800, 225, 50, 50);
g.fillRect(850, 175, 50, 50);
g.fillRect(900, 225, 50, 50);
g.fillRect(950, 175, 50, 50);
g.fillRect(1000, 225, 50, 50);
g.fillRect(1050, 175, 50, 50);
g.fillRect(1100, 225, 50, 50);
g.fillRect(1150, 175, 50, 50);
g.fillRect(1200, 225, 50, 50);
g.fillRect(1250, 175, 50, 50);
g.fillRect(1300, 225, 50, 50);
g.fillRect(1350, 175, 50, 50);
g.fillRect(1400, 225, 50, 50);
g.fillRect(1450, 175, 50, 50);
g.fillRect(1500, 225, 25, 50);
g.setColor(new Color(255, 255, 255));
g.fillRect(380, 0, 20, 1100);
g.fillRect(1525, 0, 20, 1100);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(racecar.getImage(), racecar.getX(),
racecar.getY(), this);
}
#Override
public void actionPerformed(ActionEvent e) {
step();
}
private void step() {
racecar.move();
repaint(racecar.getX()-1, racecar.getY()-1,
racecar.getWidth()+2, racecar.getHeight()+2);
}
private class TAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
racecar.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
racecar.keyPressed(e);
}
}
}
The third:
package gameproject;
import java.awt.EventQueue;
import javax.swing.JFrame;
public final class CarMovement3 extends JFrame {
public CarMovement3() {
InitUI();
}
private void InitUI() {
add(new CarMovement2());
setTitle("Top Speed Triumph");
setSize(1900, 1100);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
CarMovement3 ex = new CarMovement3();
ex.setVisible(true);
});
}
}
And the link to the sprite :
http://www.clker.com/clipart-red-sports-car-top-view.html
So, your problem stems from using...
repaint(racecar.getX() - 1, racecar.getY() - 1,
racecar.getWidth() + 2, racecar.getHeight() + 2);
Basically, you're not covering enough of the "existing" area that use to occupy to completely "remove" it.
You can simply use repaint() instead and it will solve your basic problem. I'd avoid worrying about this level of optimisation until it actually becomes a problem.
If you want to use it, then I would take a snap shot of the location of the care before it was moved (ie grab it's current x/y position) and merge that with it's new location so you cover both areas. That, or call repaint(x, y, width, height) twice, once with the old position and once with the new
private void step() {
Rectangle old = new Rectangle(racecar.getX(), racecar.getY(), racecar.getWidth(), racecar.getHeight());
racecar.move();
Rectangle now = new Rectangle(racecar.getX(), racecar.getY(), racecar.getWidth(), racecar.getHeight());
repaint(old);
repaint(now);
}
Also, you'll find that KeyListener is unreliable, I would suggest making use of the key bindings API which will solve the issues which KeyListener suffers from
I would also recommend using ImageIO over ImageIcon as more reliable way of loading your images, see Reading/Loading an Image for more details
I'm trying to make is so that multiple squares appear on the level screen. For some reason the only square it renders will be the last one in the order I type it in. Been at it for 2 hours and is extremely annoying. Any help would be awesome and greatly appreciated.
public class Level1 extends JFrame implements ActionListener, KeyListener {
LevelRender render;
static Square square;
static Player player;
static Square squares;
public static Timer timer;
boolean fail, Over, Reset = false, create = false;
static int enemyCount = 5;
static int eX = 200, eY, z;
ArrayList <Enemys> squareList = new ArrayList();
public static Level1 level;
ImageIcon Level1 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Level1.png");
public Level1(Player player){
timer = new Timer(50,this);
render = new LevelRender();
setVisible(true);
setSize(1000,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(render);
addKeyListener(this);
this.player = player;
timer.start();
player.x = 0;
player.y = 387;
}
public void render(Graphics2D g){
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if(!fail){
Level1.paintIcon(MainMenu.level1, g, -4, -25);
player.GameCount = 1;
player.render(g);
square = new Square(50,397);
squares = new Square(200,397);
square.render(g);
squares.render(g);
reset();
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", 1, 30));
g.drawString(String.valueOf("Health:"), 40, 80);
//lots of other string
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", 1, 15));
g.drawString(String.valueOf("Level:"), 900, 20);
g.drawString(String.valueOf("1"), 950, 20);
}
if(fail){
g.setColor(Color.black);
g.fillRect(0, 0, 1200, 500);
g.setColor(Color.red);
g.setFont(new Font("Arial", 1, 50));
g.drawString(String.valueOf("You Have Failed"), 200, 150);
g.setFont(new Font("Arial", 1, 50));
g.drawString(String.valueOf("Press ENTER to Continue"), 120, 220);
}
if(enemyCount == 0){
g.setColor(Color.black);
g.fillRect(0, 0, 1200, 500);
g.setColor(Color.green);
g.setFont(new Font("Arial", 1, 50));
g.drawString(String.valueOf("You Won"), 200, 150);
g.setFont(new Font("Arial", 1, 50));
g.drawString(String.valueOf("Press ENTER to Continue"), 120, 220);
}
}
public void createEnemys(){
for(int i = 0; i < 5; i++){
eX += 50;
//squares = new Enemys(player, eX, 397);
squareList.add(squares);
create = true;
}
}
public void update(){
player.update();
if(!create){
createEnemys();
}
if(Player.health <= 0){
fail = true;
Over = true;
Player.health = 10;
}
if(enemyCount == 0){
fail = false;
Over = true;
}
System.out.println(Enemys.health + " , " + enemyCount + " , " + squareList.get(3).x );
}
public void reset(){
if(Reset){
enemyCount = 5;
Reset = false;
create = false;
}
}
#Override
public void actionPerformed(ActionEvent e) {
update();
render.repaint();
}
}
...................
public class Enemys {
public static int health, damage,x,y;
static boolean hit;
static int count;
public Enemys(int x, int y){
this.x = x;
this.y = y;
}
public void hit(){
if(Player.x == x)
{
Player.health -= damage;
}
}
public void update(){
hit();
}
public void hello(){
System.out.println("Hello");
}
public void render(Graphics g){}
}
.......................
public class Square extends Enemys {
static int count;
static boolean hit;
public Square(int x, int y){
super(x,y);
damage = 1;
health = 30;
}
public void render(Graphics g){
g.setColor(Color.red);
g.fillRect(x, y, 50, 50);
g.setColor(Color.green);
g.fillRect(x, y - 20, (50*(health / 30)), 7);
}
public void update(){
x += 1;
}
}
........................
public class LevelRender extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
MainMenu.level1.render((Graphics2D)g);
}
}
...................
I am working on a project that simulates a traffic intersection. So far I did the map, traffic lights. Now I want to add some movement, some cars in my project. The problem that I am facing is that i can't add graphics on the same Panel from different classes. And can someone give me a good tutorial where I can learn how to move multiple graphics (cars in my case) .
Main class:
import java.awt.Color;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
MyMap map = new MyMap();
MyCar car = new MyCar();
Thread x = new Thread(map);
x.start();
JFrame f = new JFrame("Broadway Intersection");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
map.setBackground(Color.white);
f.add(map);
f.add(car);
f.setSize(1366, 738);
f.setVisible(true);
}
}
Map class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyMap extends JPanel implements Runnable {
Color color = Color.RED;
Color color2 = Color.RED;
Color color3 = Color.RED;
Color color4 = Color.RED;
int[] faza = new int[4];
int k;
int faza_curenta = 0;
public MyMap() {
faza[0] = 20;
faza[1] = 20;
faza[2] = 20;
faza[3] = 20;
}
public void run() {
color = Color.GREEN;
while (true) {
System.out.println("Faza = " + faza_curenta + " k= " + k);
k++;
if (k == faza[0]) {
faza_curenta = 1;
color = Color.RED;
color2 = Color.GREEN;
} else if (k == (faza[0] + faza[1])) {
faza_curenta = 2;
color = Color.RED;
color2 = Color.RED;
color3 = Color.GREEN;
} else if (k == (faza[0] + faza[1] + faza[2])) {
faza_curenta = 3;
color = Color.RED;
color3 = Color.RED;
color4 = Color.GREEN;
} else if (k == (faza[0] + faza[1] + faza[2] + faza[3])) {
faza_curenta = 0;
color = Color.GREEN;
color4 = Color.RED;
k = 0;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void paintComponent(final Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 250); // stanga sus
g.fillRect(900, 0, 500, 250); // dreapta sus
g.fillRect(0, 500, 500, 250);// stanga jos
g.fillRect(900, 500, 500, 250); // dreapta jos
g.setColor(Color.GRAY);
g.fillRect(500, 0, 400, 900);
g.fillRect(0, 250, 500, 250);
g.fillRect(900, 250, 500, 250);
g.setColor(Color.WHITE);
g.fillRect(695, 0, 5, 100);// linii verticale
g.fillRect(695, 150, 5, 100);
g.fillRect(695, 500, 5, 100);
g.fillRect(695, 650, 5, 50);
g.fillRect(0, 370, 50, 5);
g.fillRect(100, 370, 100, 5); // linii orizontale
g.fillRect(250, 370, 100, 5);
g.fillRect(400, 370, 100, 5);
g.fillRect(900, 370, 100, 5);
g.fillRect(1050, 370, 100, 5);
g.fillRect(1200, 370, 100, 5);
g.setColor(Color.BLACK);
g.fillRect(470, 220, 30, 30); // semafor Nord
g.setColor(color);
g.fillOval(475, 225, 20, 20); // semafor Nord
g.setColor(Color.BLACK);
g.fillRect(900, 220, 30, 30); // semafor Est
g.setColor(color2);
g.fillOval(905, 225, 20, 20); // semafor Nord
g.setColor(Color.BLACK);
g.fillRect(470, 500, 30, 30); // semafor Vest
g.setColor(color4);
g.fillOval(475, 505, 20, 20); // semafor Nord
g.setColor(Color.BLACK);
g.fillRect(900, 500, 30, 30); // semafor Sud
g.setColor(color3);
g.fillOval(905, 505, 20, 20); // semafor Nord
repaint();
}
}
And finally MyCar class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyCar extends JPanel {
int x; // X position
int y; // Y position
int xSpeed; // Speed in the X direction
int ySpeed; // Speed in the Y direction
public void paintComponent(final Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(420, 200, 30, 30);
repaint();
}
}
You can set Panel.setLayout(null); and add JButton by setting image icon on it now you can control Button (CAR) location by button.setLocation(x,y);
So I have my keyListener called TAdapter. For some reason i can't get this to work right. I have set the focus to the panel and it still doesnt work. I have searched and searched the web and found absolutely nothing on why this isn't working correctly. I'm new to java and completely stumped
import java.awt.*;
import javax.swing.JPanel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.TimerTask;
import java.util.Timer;
import java.awt.Toolkit;
public class Game extends JPanel implements Shared{
private static Brick bricks[];
private static Ball ball;
private static Paddle paddle;
Timer timer;
public Game(){
super();
this.addKeyListener(new TAdapter());
this.setFocusable(true);
this.requestFocusInWindow();
setSize(Shared.WIDTH, Shared.HEIGHT);
bricks = new Brick[100];
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(), 1000, 10);
}
public void addNotify(){
super.addNotify();
gameInit();
}
public static void gameInit(){
ball = new Ball();
paddle = new Paddle();
GradientPaint gp = new GradientPaint(75, 75, Color.BLACK, 95, 95, Color.GREEN, true);
int k = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
switch(i){
case 0:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 0, 255), true);
break;
case 1:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 20, 127), true);
break;
case 2:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 0, 0), true);
break;
case 3:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 127, 0), true);
break;
case 4:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 255, 0), true);
break;
case 5:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 255, 0), true);
break;
case 6:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 255, 127), true);
break;
case 7:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 127, 255), true);
break;
case 8:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 0, 255), true);
break;
case 9:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(127, 0, 255), true);
break;
}
bricks[k] = new Brick((j*BRICK_WIDTH) + (j*BRICK_SEP), (i*BRICK_HEIGHT) + BRICK_Y_OFFSET+(i*BRICK_SEP), gp);
k++;
}
}
}
public void paint(Graphics g){
super.paint(g);
GradientPaint gp = new GradientPaint(75, 75, Color.BLACK, 95, 95, Color.RED, true);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(gp);
g2.fillOval(ball.getX(), ball.getY(), BALL_RADIUS, BALL_RADIUS);
g2.fillRoundRect((Shared.WIDTH/2) - PADDLE_WIDTH/2, Shared.HEIGHT - PADDLE_Y_OFFSET*2, PADDLE_WIDTH, PADDLE_HEIGHT, 3, 3);
for(int i = 0; i< 100; i++){
if(!bricks[i].isDestroyed()){
g2.setPaint(bricks[i].getPaint());
g2.fillRoundRect(bricks[i].getX(), bricks[i].getY(), bricks[i].getWidth(), bricks[i].getHeight(), 5, 5);
}
}
Toolkit.getDefaultToolkit().sync();
g2.dispose();
}
private class TAdapter extends KeyAdapter{
public void keyReleased(KeyEvent e){
paddle.keyReleased(e);
}
public void keyPressed(KeyEvent e){
paddle.keyPressed(e);
}
}
class ScheduleTask extends TimerTask{
public void run(){
ball.move();
paddle.move();
checkCollision();
repaint();
}
}
public void stopGame(){
timer.cancel();
}
public void checkCollision() {
if (ball.getRect().getMaxY() > Shared.HEIGHT) {
stopGame();
}
for (int i = 0, j = 0; i < 100; i++) {
if (bricks[i].isDestroyed()) {
j++;
}
if (j == 100) {
stopGame();
}
}
if ((ball.getRect()).intersects(paddle.getRect())) {
int paddleLPos = (int)paddle.getRect().getMinX();
int ballLPos = (int)ball.getRect().getMinX();
int first = paddleLPos + 8;
int second = paddleLPos + 16;
int third = paddleLPos + 24;
int fourth = paddleLPos + 32;
if (ballLPos < first) {
ball.setXDir(-1);
ball.setYDir(-1);
}
if (ballLPos >= first && ballLPos < second) {
ball.setXDir(-1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos >= second && ballLPos < third) {
ball.setXDir(0);
ball.setYDir(-1);
}
if (ballLPos >= third && ballLPos < fourth) {
ball.setXDir(1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos > fourth) {
ball.setXDir(1);
ball.setYDir(-1);
}
}
for (int i = 0; i < 100; i++) {
if ((ball.getRect()).intersects(bricks[i].getRect())) {
int ballLeft = (int)ball.getRect().getMinX();
int ballHeight = (int)ball.getRect().getHeight();
int ballWidth = (int)ball.getRect().getWidth();
int ballTop = (int)ball.getRect().getMinY();
Point pointRight =
new Point(ballLeft + ballWidth + 1, ballTop);
Point pointLeft = new Point(ballLeft - 1, ballTop);
Point pointTop = new Point(ballLeft, ballTop - 1);
Point pointBottom =
new Point(ballLeft, ballTop + ballHeight + 1);
if (!bricks[i].isDestroyed()) {
if (bricks[i].getRect().contains(pointRight)) {
ball.setXDir(-1);
}
else if (bricks[i].getRect().contains(pointLeft)) {
ball.setXDir(1);
}
if (bricks[i].getRect().contains(pointTop)) {
ball.setYDir(1);
}
else if (bricks[i].getRect().contains(pointBottom)) {
ball.setYDir(-1);
}
bricks[i].setDestroyed(true);
}
}
}
}
}`
then here is the main
import javax.swing.*;
public class BreakOut extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
static Game game =new Game();
public BreakOut()
{
add(game);
setTitle("Breakout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(Shared.WIDTH, Shared.HEIGHT);
setResizable(false);
setVisible(true);
setIgnoreRepaint(true);
}
public static void main(String arg[]){
new BreakOut();a
}
}
Your key listener just sends the events to paddle.
You might want to include the code (or at least look in the code) for paddle.keyPressed(e) and paddle.keyReleased(e); but really, you probably shouldn't have your paddle object handling the keys directly. It is nice to translate your key presses to in-game meaningful calls, like paddle.moveUp() or something.
Im not sure where the shared interface comes from/does, but try implementing KeyListener. "Public class Game extends JPanel implements Shared, KeyListner" if you keep using the shared but like i said idk what its purpose is or what it does right off the top of my head.
I want to create a program that can use mouse to move picture around the program here is my code. My code is set position of shape with tempX and tempY that I set it to get position of mouse while draging when drag mouse a picture will move along mouse.
* I can't make this picture repaint while draging mouse anything I miss?
* Add chagnePositionVectors()
public class SiaemsiMouse extends JPanel implements MouseListener,MouseMotionListener {
int tempX = 330;
int tempY = 95;
// position of Siaemsi box
int posX[] = {tempX-30,tempX-30,tempX-30};
int posY[] = {tempY+305,tempY+80,tempY+55};
// position of Siaemsi stick
int posXS1[] = {tempX,tempX,tempX-3,tempX+8,tempX+20,tempX+17};
int posXS2[] = {tempX+20,tempX+20,tempX+17,tempX+28,tempX+40,tempX+37};
int posXS3[] = {tempX+40,tempX+40,tempX+37,tempX+48,tempX+60,tempX+57};
int posXS4[] = {tempX+60,tempX+60,tempX+57,tempX+68,tempX+80,tempX+77};
int posXS5[] = {tempX+80,tempX+80,tempX+77,tempX+88,tempX+100,tempX+97};
int posXS6[] = {tempX+100,tempX+100,tempX+97,tempX+108,tempX+120,tempX+117};
int posXS7[] = {tempX+120,tempX+120,tempX+117,tempX+128,tempX+140,tempX+137};
// All of y for stick are equals
int posYS1[] = {tempY,tempY,tempY-10,tempY-15,tempY-10,tempY};
public SiaemsiMouse(){
addMouseMotionListener(this);
addMouseListener(this);
}
public static void main(String[] args) {
SiaemsiMouse siaemsimouse = new SiaemsiMouse();
JFrame frame = new JFrame();
frame.add(siaemsimouse);
frame.setSize(800,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics graphics){
super.paintComponent(graphics);
Graphics2D g2 = (Graphics2D) graphics;
Random random = new Random();
// Draw Siaemsi
Ellipse2D.Double floor = new Ellipse2D.Double(posX[0],posY[0],200,50);
Rectangle2D.Double body = new Rectangle2D.Double(posX[1],posY[1],200,250);
Ellipse2D.Double top = new Ellipse2D.Double(posX[2],posY[2],200,50);
g2.setPaint(Color.RED);
g2.fill(floor);
g2.fill(body);
g2.setPaint(Color.BLACK);
g2.fill(top);
// Draw siaemsi's stick
Rectangle2D.Double stick1 = new Rectangle2D.Double(posXS1[0],posYS1[0],18,100);
GeneralPath path1 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS1.length);
path1.moveTo(posXS1[1],posYS1[1]);
for (int i = 2; i < posXS1.length; i++) {
path1.lineTo(posXS1[i],posYS1[i]);
}
path1.closePath();
Rectangle2D.Double stick2 = new Rectangle2D.Double(posXS2[0],posYS1[0],18,100);
GeneralPath path2 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS2.length);
path2.moveTo(posXS2[1],posYS1[1]);
for (int i = 2; i < posXS2.length; i++) {
path2.lineTo(posXS2[i],posYS1[i]);
}
path2.closePath();
Rectangle2D.Double stick3 = new Rectangle2D.Double(posXS3[0],posYS1[0],18,100);
GeneralPath path3 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS3.length);
path3.moveTo(posXS3[1],posYS1[1]);
for (int i = 2; i < posXS3.length; i++) {
path3.lineTo(posXS3[i],posYS1[i]);
}
path3.closePath();
Rectangle2D.Double stick4 = new Rectangle2D.Double(posXS4[0],posYS1[0],18,100);
GeneralPath path4 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS4.length);
path4.moveTo(posXS4[1],posYS1[1]);
for (int i = 2; i < posXS4.length; i++) {
path4.lineTo(posXS4[i],posYS1[i]);
}
path4.closePath();
Rectangle2D.Double stick5 = new Rectangle2D.Double(posXS5[0],posYS1[0],18,100);
GeneralPath path5 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS5.length);
path5.moveTo(posXS5[1],posYS1[1]);
for (int i = 2; i < posXS5.length; i++) {
path5.lineTo(posXS5[i],posYS1[i]);
}
path5.closePath();
Rectangle2D.Double stick6 = new Rectangle2D.Double(posXS6[0],posYS1[0],18,100);
GeneralPath path6 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS6.length);
path6.moveTo(posXS6[1],posYS1[1]);
for (int i = 2; i < posXS6.length; i++) {
path6.lineTo(posXS6[i],posYS1[i]);
}
path6.closePath();
Rectangle2D.Double stick7 = new Rectangle2D.Double(posXS7[0],posYS1[0],18,100);
GeneralPath path7 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS7.length);
path7.moveTo(posXS7[1],posYS1[1]);
for (int i = 2; i < posXS7.length; i++) {
path7.lineTo(posXS7[i],posYS1[i]);
}
path7.closePath();
g2.setPaint(new Color(153,153,0));
g2.fill(stick1);
g2.fill(path1);
g2.setPaint(Color.BLACK);
g2.draw(stick1);
g2.draw(path1);
g2.setPaint(new Color(153, 76, 0));
g2.fill(stick2);
g2.fill(path2);
g2.setPaint(Color.BLACK);
g2.draw(stick2);
g2.draw(path2);
g2.setPaint(new Color(255, 255, 0));
g2.fill(stick3);
g2.fill(path3);
g2.setPaint(Color.BLACK);
g2.draw(stick3);
g2.draw(path3);
g2.setPaint(new Color(0, 255, 128));
g2.fill(stick4);
g2.fill(path4);
g2.setPaint(Color.BLACK);
g2.draw(stick4);
g2.draw(path4);
g2.setPaint(new Color(102, 0, 56));
g2.fill(stick5);
g2.fill(path5);
g2.setPaint(Color.BLACK);
g2.draw(stick5);
g2.draw(path5);
g2.setPaint(new Color(255, 0, 127));
g2.fill(stick6);
g2.fill(path6);
g2.setPaint(Color.BLACK);
g2.draw(stick6);
g2.draw(path6);
g2.setPaint(new Color(224, 224, 56));
g2.fill(stick7);
g2.fill(path7);
g2.setPaint(Color.BLACK);
g2.draw(stick7);
g2.draw(path7);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
changePositionVectors(e.getX(),e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
public void changePositionVectors(int xPos, int yPos){
tempX = xPos;
tempY = yPos;
repaint();
}
}
Try this, here based on #HovercraftFullOfEels's comment I have separated moving from the paintComponent()...
EDIT 1:
Added floor, body and top objects. Throws null pointer exception on O/P screen but works
EDIT 2:
Still shows NPE, Fixed: Image(a cake) was not moving as posX,posY,... arrays were not updated
class SiaemsiMouse extends JPanel implements MouseListener, MouseMotionListener {
private int tempX = 330;
private int tempY = 95;
// position of Siaemsi box
private int posX[] = {tempX - 30, tempX - 30, tempX - 30};
private int posY[] = {tempY + 305, tempY + 80, tempY + 55};
// position of Siaemsi stick
private int posXS1[] = {tempX, tempX, tempX - 3, tempX + 8, tempX + 20, tempX + 17};
private int posXS2[] = {tempX + 20, tempX + 20, tempX + 17, tempX + 28, tempX + 40, tempX + 37};
private int posXS3[] = {tempX + 40, tempX + 40, tempX + 37, tempX + 48, tempX + 60, tempX + 57};
private int posXS4[] = {tempX + 60, tempX + 60, tempX + 57, tempX + 68, tempX + 80, tempX + 77};
private int posXS5[] = {tempX + 80, tempX + 80, tempX + 77, tempX + 88, tempX + 100, tempX + 97};
private int posXS6[] = {tempX + 100, tempX + 100, tempX + 97, tempX + 108, tempX + 120, tempX + 117};
private int posXS7[] = {tempX + 120, tempX + 120, tempX + 117, tempX + 128, tempX + 140, tempX + 137};
// All of y for stick are equals
private int posYS1[] = {tempY, tempY, tempY - 10, tempY - 15, tempY - 10, tempY};
public SiaemsiMouse() {
addMouseMotionListener(this);
addMouseListener(this);
}
public static void main(String[] args) throws InterruptedException {
SiaemsiMouse siaemsimouse = new SiaemsiMouse();
JFrame frame = new JFrame();
frame.add(siaemsimouse);
frame.setSize(800, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//added objects here
private Rectangle2D.Double stick1, stick2, stick3, stick4, stick5, stick6, stick7;
private GeneralPath path1, path2, path3, path4, path5, path6, path7;
//added more objects
private Ellipse2D.Double floor;
private Rectangle2D.Double body;
private Ellipse2D.Double top;
#Override
public void paintComponent(Graphics graphics) {
Graphics2D g2 = (Graphics2D) graphics;
super.paintComponent(graphics); //If you use paintComponents() the previous image persists
//Random random = new Random(); //No use for Random??
// Draw Siaemsi
g2.setPaint(Color.RED);
g2.fill(floor);
g2.fill(body);
g2.setPaint(Color.BLACK);
g2.fill(top);
g2.setPaint(new Color(153, 153, 0));
g2.fill(stick1);
g2.fill(path1);
g2.setPaint(Color.BLACK);
g2.draw(stick1);
g2.draw(path1);
g2.setPaint(new Color(153, 76, 0));
g2.fill(stick2);
g2.fill(path2);
g2.setPaint(Color.BLACK);
g2.draw(stick2);
g2.draw(path2);
g2.setPaint(new Color(255, 255, 0));
g2.fill(stick3);
g2.fill(path3);
g2.setPaint(Color.BLACK);
g2.draw(stick3);
g2.draw(path3);
g2.setPaint(new Color(0, 255, 128));
g2.fill(stick4);
g2.fill(path4);
g2.setPaint(Color.BLACK);
g2.draw(stick4);
g2.draw(path4);
g2.setPaint(new Color(102, 0, 56));
g2.fill(stick5);
g2.fill(path5);
g2.setPaint(Color.BLACK);
g2.draw(stick5);
g2.draw(path5);
g2.setPaint(new Color(255, 0, 127));
g2.fill(stick6);
g2.fill(path6);
g2.setPaint(Color.BLACK);
g2.draw(stick6);
g2.draw(path6);
g2.setPaint(new Color(224, 224, 56));
g2.fill(stick7);
g2.fill(path7);
g2.setPaint(Color.BLACK);
g2.draw(stick7);
g2.draw(path7);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
changePositionVectors(e.getX(), e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
#SuppressWarnings("empty-statement")
public void changePositionVectors(int xPos, int yPos) {
tempX = xPos;
tempY = yPos;
//calc pos...
posX = new int[]{tempX - 30, tempX - 30, tempX - 30};
posY = new int[]{tempY + 305, tempY + 80, tempY + 55};
// position of Siaemsi stick
posXS1 = new int[]{tempX, tempX, tempX - 3, tempX + 8, tempX + 20, tempX + 17};
posXS2 = new int[]{tempX + 20, tempX + 20, tempX + 17, tempX + 28, tempX + 40, tempX + 37};
posXS3 = new int[]{tempX + 40, tempX + 40, tempX + 37, tempX + 48, tempX + 60, tempX + 57};
posXS4 = new int[]{tempX + 60, tempX + 60, tempX + 57, tempX + 68, tempX + 80, tempX + 77};
posXS5 = new int[]{tempX + 80, tempX + 80, tempX + 77, tempX + 88, tempX + 100, tempX + 97};
posXS6 = new int[]{tempX + 100, tempX + 100, tempX + 97, tempX + 108, tempX + 120, tempX + 117};
posXS7 = new int[]{tempX + 120, tempX + 120, tempX + 117, tempX + 128, tempX + 140, tempX + 137};
// All of y for stick are equals
posYS1 = new int[]{tempY, tempY, tempY - 10, tempY - 15, tempY - 10, tempY};
floor = new Ellipse2D.Double(posX[0], posY[0], 200, 50);
body = new Rectangle2D.Double(posX[1], posY[1], 200, 250);
top = new Ellipse2D.Double(posX[2], posY[2], 200, 50);
// Draw siaemsi's stick
stick1 = new Rectangle2D.Double(posXS1[0], posYS1[0], 18, 100);
path1 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS1.length);
path1.moveTo(posXS1[1], posYS1[1]);
for (int i = 2; i < posXS1.length; i++) {
path1.lineTo(posXS1[i], posYS1[i]);
}
path1.closePath();
stick2 = new Rectangle2D.Double(posXS2[0], posYS1[0], 18, 100);
path2 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS2.length);
path2.moveTo(posXS2[1], posYS1[1]);
for (int i = 2; i < posXS2.length; i++) {
path2.lineTo(posXS2[i], posYS1[i]);
}
path2.closePath();
stick3 = new Rectangle2D.Double(posXS3[0], posYS1[0], 18, 100);
path3 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS3.length);
path3.moveTo(posXS3[1], posYS1[1]);
for (int i = 2; i < posXS3.length; i++) {
path3.lineTo(posXS3[i], posYS1[i]);
}
path3.closePath();
stick4 = new Rectangle2D.Double(posXS4[0], posYS1[0], 18, 100);
path4 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS4.length);
path4.moveTo(posXS4[1], posYS1[1]);
for (int i = 2; i < posXS4.length; i++) {
path4.lineTo(posXS4[i], posYS1[i]);
}
path4.closePath();
stick5 = new Rectangle2D.Double(posXS5[0], posYS1[0], 18, 100);
path5 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS5.length);
path5.moveTo(posXS5[1], posYS1[1]);
for (int i = 2; i < posXS5.length; i++) {
path5.lineTo(posXS5[i], posYS1[i]);
}
path5.closePath();
stick6 = new Rectangle2D.Double(posXS6[0], posYS1[0], 18, 100);
path6 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS6.length);
path6.moveTo(posXS6[1], posYS1[1]);
for (int i = 2; i < posXS6.length; i++) {
path6.lineTo(posXS6[i], posYS1[i]);
}
path6.closePath();
stick7 = new Rectangle2D.Double(posXS7[0], posYS1[0], 18, 100);
path7 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS7.length);
path7.moveTo(posXS7[1], posYS1[1]);
for (int i = 2; i < posXS7.length; i++) {
path7.lineTo(posXS7[i], posYS1[i]);
}
path7.closePath();
repaint();
}
}
I see what I think is your problem.
You are assuming that if you change tempX and tempY that all variables that are derived from them will change as well,
but this is not so. Any variables created with tempX or tempY will not magically know to change once they have been created.
You need to change any variables that need to be changed yourself, and the easiest way to do this is to create a method that takes your tempX and tempY values and re-calculates all the other fields that need to be recalculated.
Consider creating and moving your Shape and path objects outside of paintComponent, perhaps in the Mouse adapter code and simply painting the Shape in paintComponent.
i.e.,
public void changePositionVectors(int xPos, int yPos) {
// set the fields that need to be set with x and y
repaint();
}
Edit
Regarding your new code:
public void changePositionVectors(int xPos, int yPos){
tempX = xPos;
tempY = yPos;
repaint();
}
This fixes nothing since all this does is set's tempX and tempY, and again, changing these values will not magically change any value that was originally created with these fields. Again, your changePositionVectors method must contain more code that in fact sets the values of all the vectors needed for drawing your GUI.
Edit I would take a completely different tack from what you and boxed are doing. I would:
Draw everything to a BufferedImage
Place that BufferedImage into an ImageIcon
Place that ImageIcon into a JLabel
Place that JLabel into a JLayeredPane
Add a MouseListener and MouseMotionListener to the JLabel.
Done.
For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
#SuppressWarnings("serial")
public class SimpleDrawing {
private static final int PREF_W = 780;
private static final int PREF_H = 570;
private static final int GAP = 1;
private static final int BI_WIDTH = 200 + 2 * GAP;
private static final int BI_HEIGHT = 300 + 2 * GAP;
private static final int ELLIPSE_WIDTH = BI_WIDTH - 2 * GAP;
private static final int ELLIPSE_HEIGHT = 50;
private static final Color CAN_COLOR = Color.red;
private JLayeredPane layeredPane = new JLayeredPane() {
public Dimension getPreferredSize() {
return SimpleDrawing.this.getPreferredSize();
};
};
private JLabel imageLabel;
private Point imageLabelPoint = new Point();
public SimpleDrawing() {
layeredPane.setOpaque(true);
layeredPane.setBackground(Color.white);
imageLabel = drawImageLabel();
imageLabel.setLocation(imageLabelPoint);
imageLabel.setSize(imageLabel.getPreferredSize());
layeredPane.add(imageLabel, JLayeredPane.DEFAULT_LAYER);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
imageLabel.addMouseListener(myMouseAdapter);
imageLabel.addMouseMotionListener(myMouseAdapter);
}
private JLabel drawImageLabel() {
BufferedImage img = new BufferedImage(BI_WIDTH, BI_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(CAN_COLOR);
int x = GAP;
int y = BI_HEIGHT - ELLIPSE_HEIGHT - GAP;
int width = ELLIPSE_WIDTH;
int height = ELLIPSE_HEIGHT;
g2.fillOval(x, y, width, height);
y = GAP + ELLIPSE_HEIGHT / 2;
width = ELLIPSE_WIDTH;
height = BI_HEIGHT - ELLIPSE_HEIGHT / 2 - GAP - y;
g2.fillRect(x, y, width, height);
g2.setColor(Color.black);
y = GAP;
height = ELLIPSE_HEIGHT;
g2.fillOval(x, y, width, height);
g2.dispose();
ImageIcon icon = new ImageIcon(img);
return new JLabel(icon);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public JLayeredPane getLayeredPane() {
return layeredPane;
}
private class MyMouseAdapter extends MouseAdapter {
private boolean dragging = false;
private Point srcLoc;
private Point msePressLoc;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
dragging = true;
srcLoc = ((Component) e.getSource()).getLocation();
msePressLoc = e.getLocationOnScreen();
}
#Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
dragging = false;
moveTo(e);
}
#Override
public void mouseDragged(MouseEvent e) {
if (!dragging) {
return;
}
moveTo(e);
}
private void moveTo(MouseEvent e) {
Point loc = e.getLocationOnScreen();
Component comp = (Component) e.getSource();
int x = loc.x - msePressLoc.x + srcLoc.x;
int y = loc.y - msePressLoc.y + srcLoc.y;
comp.setLocation(x, y);
layeredPane.repaint();
}
}
private static void createAndShowGui() {
SimpleDrawing simpleDrawing = new SimpleDrawing();
JFrame frame = new JFrame("Simple Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(simpleDrawing.getLayeredPane());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}