Java Snake Game using Queue - java

Im supposed to create a Snake game using a Queue in Java.
I'm supposed to only use the three classes down below, however I do not know how I should modify my move() function in order to move the snake, since it is a Queue and I cannot access the tail of the snake.
I came up with the following:
Snake.java
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Snake extends JFrame implements Runnable, KeyListener {
int length=40, width = 30;
int time;
int factor=10;
Specialqueue q;
int direction = 6;
Thread t;
int[][] food;
private boolean started;
public Snake() {
super("Snake");
setSize(length*factor+30, width*factor+60);
setVisible(true);
addKeyListener(this);
started = false;
time = 0;
}
public void paint(Graphics g){
if (g == null) return;
g.clearRect(0,0,getWidth(),getHeight());
if (!gestartet){
g.drawString("start the game by pressing 5",10,50);
g.drawString("Controll the snake with W,A,S,D",10,80);
return;
}
g.setColor(Color.blue);
for (int k = 0; k < length; k++)
for (int j = 0; j < breite; j++)
if (food[k][j]==1)
g.fillOval(k*10,20+j*10,10,10);
}
public void run() {
time = 0;
while (started){
try {Thread.sleep(300);}
catch (Exception e){};
move();
time++;
Graphics g = this.getGraphics();
}
}
public void stop() {
started=false;
t = null;
}
public void initFood() {
food = new int[length][breite];
for (int k = 0; k < length; k++) {
for (int j = 0; j < breite; j++) {
if (Math.random() < 0.01) futter[k][j] = 1;
else food[k][j] = 0;
}
}
}
public void initSnake(){
q = new Specialqueue();
direction = 6;
q.append(new Point(20,20));
q.append(new Point(19,20));
q.append(new Point(18,20));
q.append(new Point(17,20));
Graphics g = this.getGraphics();
repaint();
g.setColor(Color.red);
g.fillOval(20*10,20+20*10,10,10);
g.fillOval(19*10,20+20*10,10,10);
g.fillOval(18*10,20+20*10,10,10);
g.fillOval(17*10,20+20*10,10,10);
g.setColor(Color.black);
}
public void move()
{
Graphics g = this.getGraphics();
Point p = (Point)q.tail();
Point newPoint = null;
int size = 4;
if (direction == 6) {
for(int i=0;i<3;i++) {
q.remove();
}
for(int q=0;q<3;q++) {
newPoint = new Point(p.x+1, p.y);
}
if (newPoint.x >= length) {stoppe(); return;}
}
else if (direction == 4) {
newPoint = new Point(p.x-1, p.y);
if (newPoint.x < 0) {stoppe(); return;}
}
else if (direction == 8)
{
newPoint = new Point(p.x, p.y-1);
if (newPoint.y < 0) {stoppe(); return;}
}
else if (direction == 2)
{
newPoint = new Point(p.x, p.y+1);
if (newPoint.y >= width) {stoppe(); return;}
}
q.append(newPoint);
p = (Point)q.tail();
g.setColor(Color.red);
g.fillOval(p.x*10,20+p.y*10,10,10);
if(food[newPoint.x][newPoint.y] == 0){
p = (Point)q.first();
g.setColor(Color.white);
g.fillOval(p.x*10,20+p.y*10,10,10);
q.remove();
}
else {
food[newPoint.x][newPoint.y]=0;
}
}
public void keyPressed(KeyEvent ke)
{
char c = ke.getKeyChar();
if (c=='5' && started) {started = false; t = null; repaint(); return; }
if (c=='5' && !started){
gestartet=true;
initSnake();
initFutter();
t = new Thread(this);
try {Thread.sleep(150);} catch (Exception e){};
t.start();
return;
}
if ((c =='6' || c=='d') && direction != 4) direction = 6;
else if ((c =='2' || c=='s') && direction != 8) direction = 2;
else if ((c =='4' || c=='a') && direction != 6) direction = 4;
else if ((c =='8' || c=='w') && direction != 2) direction = 8;
}
}
SpecialQueue.java
public class Specialqueue <ContentType> {
Queue<ContentType> s;
public Specialqueue()
{
s = new Queue<ContentType>();
}
public ContentType tail(){
if (s.isEmpty()) return null;
return s.front();
}
public boolean isEmpty(){
return s.isEmpty();
}
public void append(ContentType pContent)
{
s.enqueue(pContent);
}
public void remove()
{
if(!s.isEmpty()) {
s.dequeue();
}
}
public ContentType first(){
if (this.isEmpty())
{
return null;
}
else{
return s.front();
}
}
}
**Queue.java**
public class Queue {
protected class QueueNode {
protected ContentType content = null;
protected QueueNode nextNode = null;
public QueueNode(ContentType pContent) {
content = pContent;
nextNode = null;
}
public void setNext(QueueNode pNext) {
nextNode = pNext;
}
public QueueNode getNext() {
return nextNode;
}
public ContentType getContent() {
return content;
}
}
protected QueueNode head;
protected QueueNode tail;
public Queue() {
head = null;
tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void enqueue(ContentType pContent) {
if (pContent != null) {
QueueNode newNode = new QueueNode(pContent);
if (this.isEmpty()) {
head = newNode;
tail = newNode;
} else {
tail.setNext(newNode);
tail = newNode;
}
}
}
public void dequeue() {
if (!this.isEmpty()) {
head = head.getNext();
if (this.isEmpty()) {
head = null;
tail = null;
}
}
}
public ContentType front() {
if (this.isEmpty()) {
return null;
} else {
return head.getContent();
}
}
}

Related

How can I avoid java.lang.ArrayIndexOutOfBoundsException when joining a Queue?

I'm working on a simple(?) exercise for my Data Structures class. It works fine right up until I have an element leave the queue then try to add another one on at which point I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at queueExercise.IntegerQueue.join(IntegerQueue.java:20)
at queueExercise.IntegerQueueTest.main(IntegerQueueTest.java:27)
My code is as follows:
Queue Constructor Class:
public class IntegerQueue {
private int[] queue;
private int front;
private int end;
private int noInQueue;
private int count;
private boolean full;
public IntegerQueue(int max) {
queue = new int[max];
front = end = 0;
full = false;
}
public void join(int newValue) {
if (isFull()==false) {
queue[end] = newValue;
count++;
if (end == queue.length) {
end = 0;
}
else {
end++;
}
}else
System.out.println("Error: Queue Full");
}
public int leave() {
if (isEmpty()==false) {
noInQueue = queue[front];
queue[front]=0;
front++;
if (front==queue.length) {
front = 0;
}
count--;
}
else {
System.out.println("Error: Queue Empty");
}
System.out.println("Leaving: "+noInQueue);
return noInQueue;
}
public boolean isEmpty() {
if (count == 0){
return true;
}
else
return false;
}
public boolean isFull() {
if (count >= queue.length) {
return true;
}
else
return false;
}
public void printQueue() {
if (!isEmpty()) {
System.out.println("Printing Queue");
int pos = front;
int i =0;
while(i<queue.length) {
System.out.println(queue[pos]);
pos++;
i++;
if (pos >=queue.length) {
pos = 0;
}
}
}
}
}
Test Class
public class IntegerQueueTest {
static IntegerQueue q = new IntegerQueue(10);
public static void main(String[] args) {
int j;
System.out.println("Creating Queue");
for (int i = 0; i <10; i++) {
j = (int)(Math.random()*100);
if (!q.isFull()) {
q.join(j);
System.out.println("Adding: "+j);
}
}
q.printQueue();
q.join(112);
q.leave();
q.leave();
q.leave();
q.printQueue();
q.join(112);
q.join(254);
q.printQueue();
}
}
The problem is in the join method and more precisely in the condition if (end == queue.length). All you have to do is change it to if (end == queue.length - 1).

Java Maze Solver - Stack does not pop when pop() is called

I'm working on an assignment where I have to solve a maze through backtracking (using a stack!) and the logic of the code is basically done, but the main problem is whenever I call pop() on my stack, it does not pop.So for now I have manually added (hardcoded) the parts in the maze where it is supposed to pop(). I am using my own stack that is using Linked Nodes and have ran JUnit and Main tests and it does indeed work (doubting myself here now). I have also used the Java stack and I get the same result.
Here is my code logic: As you can see in the method mazeSolver, at the bottom, I have a few if statements that check if i (operations performed) is at a certain point and it will "backtrack", but I am manually setting the position. The very last else statement is the part where I pop(). Any help would very much be appreciated.
public class MazeSolver {
private char[][] printMaze;
private char[][] solveMaze;
public MazeSolver() {
super();
}
private class Position {
private int x;
private int y;
Position(int y, int x) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
public boolean solve(boolean printUpdates) {
char space = ' ';
Stack<Position> stack = new Stack<Position>();
//Stack stack = new Stack();
Position cp = new Position(1, 0);
boolean done = true;
char c = 'C';
char x = 'X';
int i = 0;
while (done) {
// check right
if (printMaze[cp.getY()][cp.getX() + 1] == space && printMaze[cp.getY()][cp.getX() + 1] != x) {
cp.setX(cp.getX() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check bottom
else if (printMaze[cp.getY() + 1][cp.getX()] == space && printMaze[cp.getY() + 1][cp.getX()] != x
&& printMaze[cp.getY() + 1][cp.getX()] != x) {
cp.setY(cp.getY() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check top
else if (printMaze[cp.getY() - 1][cp.getX()] == space && printMaze[cp.getY() - 1][cp.getX()] != x) {
cp.setY(cp.getY() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check left
else if (printMaze[cp.getY()][cp.getX() - 1] == space && printMaze[cp.getY()][cp.getX() - 1] != x) {
cp.setX(cp.getX() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
//else {
/*
if (i == 6) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(5);
} else if (i == 27) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(20);
}
else if (i == 37) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(2);
cp.setX(18);
}
else if (i == 68) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(13);
cp.setX(22);
} else if (i == 69) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(14);
cp.setX(22);
}
else if (i == 70) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(15);
cp.setX(22);
} else if (i == 71) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(16);
cp.setX(22);
} else if (i == 72) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(17);
cp.setX(22);
} else if (i == 103) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(21);
cp.setX(31);
} */else {
printMaze[cp.getY()][cp.getX()] = 'X';
stack.pop();
cp.setY(((Position) stack.top()).getY());
cp.setX(((Position) stack.top()).getX());
}
//}
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println(stack.top().getX() + ", " + stack.top().getY());
System.out.println(cp.getY() + ", " + cp.getX() + " i = " + i);
printMaze();
}
System.out.println("success");
return false;
}
public void printMaze() {
for (int i = 0; i < printMaze.length; i++) {
for (int j = 0; j < printMaze[i].length; j++) {
System.out.print(printMaze[i][j]);
}
System.out.println("");
}
}
public boolean loadMaze(String filename) {
BufferedReader br = null;
FileReader fr = null;
ArrayList<String> lines = new ArrayList<String>();
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
lines.add(line);
}
printMaze = new char[lines.size()][];
solveMaze = new char[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
printMaze[i] = new char[lines.get(i).length()];
solveMaze[i] = new char[lines.get(i).length()];
for (int j = 0; j < lines.get(i).length(); j++) {
solveMaze[i][j] = lines.get(i).charAt(j);
printMaze[i][j] = lines.get(i).charAt(j);
if (solveMaze[i][j] == 'S') {
// hint you need to do this but you do not have the
// instance variable yet
// start = new Position(i, j);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
return false;
}
}
return true;
}
Here is my stack implementation if interested.
public class Stack<Item> implements StackInterface<Item> {
private int size;
private class Link {
private Item data;
public Link next;
public Link(Item data, Link next) {
this.data = data;
this.next = next;
}
public Item getData() {
return data;
}
}
private Link topStackLink = null;
public Stack() {
this.size = 0;
}
#Override
public void push(Item item) {
if (topStackLink == null) {
topStackLink = new Link(item, null);
} else {
topStackLink = new Link(item, topStackLink);
}
this.size++;
}
#Override
public void pop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
topStackLink = topStackLink.next;
this.size--;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item top() {
if (topStackLink != null) {
return topStackLink.data;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item topAndPop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
Item item = topStackLink.data;
pop();
return item;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public boolean isEmpty() {
if (topStackLink == null) {
return true;
} else {
return false;
}
}
#Override
public void makeEmpty() {
// TODO Auto-generated method stub
topStackLink = null;
this.size = 0;
}
#Override
public int size() {
return this.size;
}

Java 2D Game Programming : Missile shooting is too fast?

Hello I'm fairly new to programming and this is my first time posting here so any help would be appreciated so:
my problem is that I"m trying to create some kind of 2D shooter game in java but I don't know if my simple game loop is good because when i shoot a missile it shoots a one every 20 ms and it's too fast and shoots a ton of missiles at once so is there any way to adjust it ? Like to keep some delay between every missile and the other??
and please tell me if i have problems or bad programming in my code !!
this is my game panel where most of the game happens and where my loop and adding missiles method in
public class GamePanel extends JPanel implements KeyListener {
Measurments mesure = new Measurments();
int panel_width = mesure.getUniversalWidth();
int panel_height = mesure.getUniversalHeight();
Timer timer;
Random rand = new Random();
ArrayList<Enemy> enemies = new ArrayList<>();
ArrayList<Missile> missiles = new ArrayList<>();
Player player = new Player(0, 0);
boolean up = false;
boolean down = false;
boolean right = false;
boolean left = false;
boolean isShooting = false;
boolean isRunning = true;
public boolean gameRunning() {
return isRunning;
}
int count = 5;
int missilesCount = 6;
public GamePanel() {
timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent e) {
StartGame();
repaint();
}
});
setSize(panel_width, panel_height);
addKeyListener(this);
timer.start();
for (int i = 0; i < count; i++) {
addEnemy(new Enemy(rand.nextInt(750), rand.nextInt(500)));
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
player.paint(g2d);
for (int i = 0; i < enemies.size(); i++) {
Enemy temp = enemies.get(i);
temp.paint(g2d);
}
for (int i = 0; i < missiles.size(); i++) {
Missile mis = missiles.get(i);
mis.paint(g2d);
mis.behave();
}
}
public void StartGame() {
if (isRunning) {
runGame();
setBackground(Color.YELLOW);
} else {
setBackground(Color.BLACK);
}
}
public void runGame() {
update();
};
public void update() {
player.checkBorders();
checkColls();
if (up) {
player.updateUp();
}
if (down) {
player.updateDown();
}
if (right) {
player.updateRight();
}
if (left) {
player.updateLeft();
}
if (isShooting) {
for (int i = 0; i < 5; i++) {
missiles.add(new Missile(player.getX() + 16, player.getY() + 16));
}
}
for (int i = 0; i < missiles.size(); i++) {
Missile temp = missiles.get(i);
if (temp.getX() == panel_width) {
RemoveMissile(temp);
}
}
}
public void addEnemy(Enemy e) {
enemies.add(e);
}
public void removeEnemy(Enemy e) {
enemies.remove(e);
}
public void addMissile(Missile e) {
missiles.add(e);
}
public void RemoveMissile(Missile e) {
missiles.add(e);
}
public void checkColls() {
for (int i = 0; i < enemies.size(); i++) {
Enemy tempEnm = enemies.get(i);
for (int e = 0; e < missiles.size(); e++) {
Missile tempMis = missiles.get(e);
if (tempMis.missileRect().intersects(tempEnm.enemyRect())) {
enemies.remove(tempEnm);
missiles.remove(tempMis);
}
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = true;
}
if (key == e.VK_DOWN) {
down = true;
}
if (key == e.VK_RIGHT) {
right = true;
}
if (key == e.VK_LEFT) {
left = true;
}
if (key == e.VK_ENTER) {
isRunning = true;
}
if (key == e.VK_SPACE) {
isShooting = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = false;
}
if (key == e.VK_DOWN) {
down = false;
}
if (key == e.VK_RIGHT) {
right = false;
}
if (key == e.VK_LEFT) {
left = false;
}
if (key == e.VK_SPACE) {
isShooting = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
Thanks in advance !!
private long fired = 0L;
public void update() {
...
// firing missiles: only if the missile count is less than the max., and the elapsed
// time is more than a limit (100 ms)
if ( isShooting && missiles.size() < missilesCount &&
( System.currentTimeMilis() - this.fired ) > 100 ) {
missiles.add( new Missile( player.getX() + 16, player.getY() + 16 ) );
// time of last firing
this.fired = System.currentTimeMilis();
}
...
}
public void RemoveMissile(Missile e) {
// as Guest is asked in another answer, this method should remove, not add...
missiles.remove(e);
}

Applet does not load on html page

I have this applet and i cant figure out why it doesnt load on html page.I have added full permissions in java.policy file. I use the default html file from NetBeans Applet's output.
/* Hearts Cards Game with AI*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.awt.Graphics;
import java.awt.Image;
import java.security.AccessController;
import javax.swing.ImageIcon;
import javax.swing.*;
import javax.swing.JPanel;
public class Game extends JApplet implements MouseListener, Runnable {
int initNoCards = 13;
int width, height;
boolean endGame = false;
int turn = -1;
int firstCard = 0;
int firstTrick = 0;
String leadingSuit = null;
Cards leadingCard = null;
Cards playCard = null;
String startCard = "c2";
Cards[] trickCards = new Cards[4];
ArrayList<Cards>[] playerCards = new ArrayList[4];
ArrayList<Cards>[] takenCards = new ArrayList[4];
boolean heartsBroken = false;
ArrayList<Cards> cards = new ArrayList<Cards>();
String[] hearts = {"h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "h12", "h13", "h14", "h15"};
String queen = "s13";
int cardHeight = 76;
int cardWidth = 48;
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
int selectedCard = -1;
//set the background image
Image backImage = new ImageIcon("deck\\back2.png").getImage();
public void GetDataFromXML() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
boolean image = false;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
if (qName.equalsIgnoreCase("IMAGE")) {
image = true;
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (name) {
cards.add(new Cards(s));
name = false;
}
if (image) {
image = false;
}
}
};
saxParser.parse("deck\\deck.xml", handler);
} catch (Exception e) {
}
}
//function for comparing cards from same suite
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
//checks if a card is valid to play
public boolean ValidMove(Cards c) {
if (firstCard == 0) {
if (c.getName().equals(startCard)) {
firstCard = 1;
return true;
}
return false;
}
boolean result = playerCards[turn].indexOf(c) >= 0;
if (leadingSuit == null) {
return result;
}
boolean found = false;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) == leadingSuit.charAt(0)) {
found = true;
break;
}
}
if (!found) {
boolean justHearts = true;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) != 'h') {
justHearts = false;
break;
}
}
if (firstTrick == 0) {
if (c.getName().equals(queen)) {
return false;
}
if (!justHearts && c.getName().charAt(0) == 'h') {
return false;
}
} else {
if (c.getName().charAt(0) == 'h' && leadingSuit == null && !heartsBroken && !justHearts) {
return false;
}
}
} else {
if (c.getName().charAt(0) != leadingSuit.charAt(0)) {
return false;
}
}
return result;
}
#Override
public void init() {
GetDataFromXML();
setSize(500, 500);
width = super.getSize().width;
height = super.getSize().height;
setBackground(Color.white);
addMouseListener(this);
for (int i = 0; i < cards.size(); i++) {
System.out.println(cards.get(i).getName());
System.out.println(cards.get(i).getImage());
}
Shuffle();
}
public int GetTrickCount() {
int count = 0;
for (int i = 0; i < trickCards.length; i++) {
if (trickCards[i] != null) {
count++;
}
}
return count;
}
public void ResetTrick() {
for (int i = 0; i < trickCards.length; i++) {
trickCards[i] = null;
}
}
#Override
public void run() {
try {
PlayTurn();
} catch (InterruptedException ex) {
}
}
public void start() {
Thread th = new Thread(this);
th.start();
}
//function for shuffling cards and painting players cards
public void Shuffle() {
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
}
ArrayList<Cards> list = new ArrayList<Cards>();
list.addAll(cards);
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName() + " ");
}
//initializare liste carti
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
for (int j = 0; j < initNoCards; j++) {
playerCards[i].add((list.get(j + i * initNoCards)));
if (list.get(j + i * initNoCards).getName().equals(startCard)) {
turn = i;
}
}
Collections.sort(playerCards[i], c);
ShowCards(i);
}
for (int i = 0; i < playerCards[0].size() - 1; i++) {
rectangles.add(new Rectangle((141 + 1) + 13 * i - 2, 350 + 1, 13 - 2, cardHeight - 1));
}
rectangles.add(new Rectangle((141 + 1) + 13 * 12 - 2, 350 + 1, cardWidth, cardHeight - 1));
ShowPlayersCards();
}
Comparator<Cards> c = new Comparator<Cards>() {
#Override
public int compare(Cards o1, Cards o2) {
if (o2.getName().charAt(0) != o1.getName().charAt(0)) {
return o2.getName().charAt(0) - o1.getName().charAt(0);
} else {
int a, b;
a = Integer.parseInt(o1.getName().substring(1));
b = Integer.parseInt(o2.getName().substring(1));
return a - b;
}
}
};
public void PlayTurn() throws InterruptedException {
endGame = true;
System.out.println("Its " + turn);
for (int i = 0; i < 4; i++) {
if (!playerCards[i].isEmpty()) {
endGame = false;
}
}
if (endGame) {
System.out.println("Game over!");
GetPlayersScore();
return;
}
if (turn != 0) {
Random r = new Random();
int k = r.nextInt(playerCards[turn].size());
Cards AIcard = playerCards[turn].get(k);
while (!ValidMove(AIcard)) {
k = r.nextInt(playerCards[turn].size());
AIcard = playerCards[turn].get(k);
}
leadingCard = AIcard;
playCard = AIcard;
} else {
System.out.println("\nIt is player's (" + turn + ") turn");
System.out.println("Player (" + turn + ") enter card to play:");
leadingCard = null;
playCard = null;//new Cards(read);
while (true) {
if (playCard != null) {
break;
}
Thread.sleep(50);
}
}
repaint();
Thread.sleep(1000);
repaint();
if (playCard.getName().charAt(0) == 'h') {
heartsBroken = true;
}
playerCards[turn].remove(playCard);
trickCards[turn] = playCard;
if (GetTrickCount() == 1)//setez leading suit doar pentru trickCards[0]
{
leadingSuit = GetSuit(playCard);
}
System.out.println("Leading suit " + leadingSuit);
System.out.println("Player (" + turn + ") chose card " + playCard.getName() + " to play");
ShowTrickCards();
ShowPlayersCards();
if (GetTrickCount() < 4) {
turn = (turn + 1) % 4;
} else {
turn = GetTrickWinner();
leadingSuit = null;
firstTrick = 1;
playCard = null;
repaint();
}
PlayTurn();
}
public void ShowTrickCards() {
System.out.println("Cards in this trick are:");
for (int i = 0; i < 4; i++) {
if (trickCards[i] != null) {
System.out.print(trickCards[i].getName() + " ");
}
}
}
public String GetSuit(Cards c) {
if (c.getName().contains("c")) {
return "c";
}
if (c.getName().contains("s")) {
return "s";
}
if (c.getName().contains("h")) {
return "h";
}
if (c.getName().contains("d")) {
return "d";
}
return null;
}
public String GetValue(Cards c) {
String get = null;
get = c.getName().substring(1);
return get;
}
public int GetTrickWinner() {
int poz = 0;
for (int i = 1; i < 4; i++) {
if (trickCards[poz].getName().charAt(0) == trickCards[i].getName().charAt(0) && lowerThan(trickCards[poz], trickCards[i]) == true) {
poz = i;
}
}
System.out.println("\nPlayer (" + poz + ") won last trick with card " + trickCards[poz].getName());
ResetTrick();
return poz;
}
public void ShowPlayersCards() {
ShowCards(0);
ShowCards(1);
ShowCards(2);
ShowCards(3);
}
public void GetPlayersScore() {
GetScore(0);
GetScore(1);
GetScore(2);
GetScore(3);
}
public void ShowCards(int player) {
System.out.print("\nPlayer (" + player + ") cards: ");
for (int i = 0; i < playerCards[player].size(); i++) {
System.out.print(playerCards[player].get(i).getName() + " ");
}
System.out.println();
}
public int GetScore(int player) {
int score = 0;
for (int i = 0; i < takenCards[player].size(); i++) {
for (int j = 0; j < hearts.length; j++) {
if (takenCards[player].get(i).getName().equals(hearts[j])) {
score++;
break;
}
}
if (takenCards[player].get(i).getName().equals(queen)) {
score += 13;
}
}
return score;
}
#Override
public void paint(Graphics g) {
g.drawImage(backImage, 0, 0, getWidth(), getHeight(), this);
for (int i = 0; i < playerCards[0].size(); i++) {
if (selectedCard == i) {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 340, null);
} else {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 350, null);
}
if (trickCards[0] != null) {
g.drawImage(trickCards[0].getImage(), 225, 250, 48, 76, null);
}
if (trickCards[1] != null) {
g.drawImage(trickCards[1].getImage(), 177, 174, 48, 76, null);
}
if (trickCards[2] != null) {
g.drawImage(trickCards[2].getImage(), 225, 98, 48, 76, null);
}
if (trickCards[3] != null) {
g.drawImage(trickCards[3].getImage(), 273, 174, 48, 76, null);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
if (turn != 0) {
return;
}
for (int i = 0; i < rectangles.size(); i++) {
if (rectangles.get(i).contains(e.getPoint())) {
if (i == selectedCard) {
if (ValidMove(playerCards[0].get(i))) {
selectedCard = -1;
rectangles.get(rectangles.size() - 2).width = rectangles.get(rectangles.size() - 1).width;
playCard = playerCards[0].get(i);
leadingCard = playCard;
rectangles.remove(rectangles.size() - 1);
trickCards[0] = playerCards[0].remove(i);
} else {
if (firstCard == 0) {
JOptionPane.showMessageDialog(this, "You have to play 2 of clubs!");
}
}
} else {
selectedCard = i;
rectangles.get(i).y -= 10;
}
repaint();
break;
}
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
class Cards extends JPanel {
private String name;
private String image;
private Image img;
public Cards(String name) {
super();
this.name = name;
this.image = "deck\\" + name + ".png";
this.img = new ImageIcon(image).getImage();
}
public Cards() {
super();
this.name = null;
this.image = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Image getImage() {
return img;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Cards)) {
return false;
}
Cards c = (Cards) obj;
return name.equals(c.getName()) && image.equals(c.getImage());
}
#Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 31 * hash + (this.image != null ? this.image.hashCode() : 0);
return hash;
}
#Override
public void paint(Graphics g) {
g.drawImage(img, WIDTH, HEIGHT, this);
}
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
public int compareTo(Cards c) {
if (c.getName().charAt(0) != name.charAt(0)) {
return c.getName().charAt(0) - name.charAt(0);
} else {
int a, b;
a = Integer.parseInt(name.substring(1));
b = Integer.parseInt(c.getName().substring(1));
return a - b;
}
}
}
HTML
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="Game.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
Image backImage = new ImageIcon("deck\\back2.png").getImage();
If I am the user of the applet when it is on the internet, the will cause the JRE to search for a File relative to the current user directory on my PC, either that or the cache of FF. In either case, it will not locate an image by the name of back2.png.
For fear of sounding like a looping Clip:
Resources intended for an applet (icons, BG image, help files etc.) should be accessed by URL.
An applet will not need trust to access those resources, so long as the resources are on the run-time class-path, or on the same server as the code base or document base.
Further
I have added full permissions in java.policy file.
This is pointless. It will not be workable at time of deployment unless you control every machine it is intended to run on. If an applet needs trust in a general environment, it needs to be digitally signed. You might as well sign it while building the app.
cant figure out why it doesnt load on html page.
Something that would assist greatly is to configure the Java Console to open when an applet is loaded. There is a setting in the last tab of the Java Control Panel that configures it.

How to implement draggable tab using Java Swing?

How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.
EDIT: The Java Tutorials - Drag and Drop and Data Transfer.
Curses! Beaten to the punch by a Google search. Unfortunately it's true there is no easy way to create draggable tab panes (or any other components) in Swing. So whilst the example above is complete this one I've just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit clearer. The steps are:
Detect that a drag has occurred
Draw the dragged tab to an offscreen buffer
Track the mouse position whilst dragging occurs
Draw the tab in the buffer on top of the component.
The above example will give you what you want but if you want to really understand the techniques applied here it might be a better exercise to round off the edges of this example and add the extra features demonstrated above to it.
Or maybe I'm just disappointed because I spent time writing this solution when one already existed :p
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class DraggableTabbedPane extends JTabbedPane {
private boolean dragging = false;
private Image tabImage = null;
private Point currentMouseLocation = null;
private int draggedTabIndex = 0;
public DraggableTabbedPane() {
super();
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if(!dragging) {
// Gets the tab index based on the mouse position
int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY());
if(tabNumber >= 0) {
draggedTabIndex = tabNumber;
Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber);
// Paint the tabbed pane to a buffer
Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics totalGraphics = totalImage.getGraphics();
totalGraphics.setClip(bounds);
// Don't be double buffered when painting to a static image.
setDoubleBuffered(false);
paintComponent(totalGraphics);
// Paint just the dragged tab to the buffer
tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = tabImage.getGraphics();
graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this);
dragging = true;
repaint();
}
} else {
currentMouseLocation = e.getPoint();
// Need to repaint
repaint();
}
super.mouseDragged(e);
}
});
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if(dragging) {
int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10);
if(tabNumber >= 0) {
Component comp = getComponentAt(draggedTabIndex);
String title = getTitleAt(draggedTabIndex);
removeTabAt(draggedTabIndex);
insertTab(title, null, comp, null, tabNumber);
}
}
dragging = false;
tabImage = null;
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Are we dragging?
if(dragging && currentMouseLocation != null && tabImage != null) {
// Draw the dragged tab
g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this);
}
}
public static void main(String[] args) {
JFrame test = new JFrame("Tab test");
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(400, 400);
DraggableTabbedPane tabs = new DraggableTabbedPane();
tabs.addTab("One", new JButton("One"));
tabs.addTab("Two", new JButton("Two"));
tabs.addTab("Three", new JButton("Three"));
tabs.addTab("Four", new JButton("Four"));
test.add(tabs);
test.setVisible(true);
}
}
I liked Terai Atsuhiro san's DnDTabbedPane, but I wanted more from it. The original Terai implementation transfered tabs within the TabbedPane, but it would be nicer if I could drag from one TabbedPane to another.
Inspired by #Tom's effort, I decided to modify the code myself.
There are some details I added. For example, the ghost tab now slides along the tabbed pane instead of moving together with the mouse.
setAcceptor(TabAcceptor a_acceptor) should let the consumer code decide whether to let one tab transfer from one tabbed pane to another. The default acceptor always returns true.
/** Modified DnDTabbedPane.java
* http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html
* originally written by Terai Atsuhiro.
* so that tabs can be transfered from one pane to another.
* eed3si9n.
*/
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
public class DnDTabbedPane extends JTabbedPane {
public static final long serialVersionUID = 1L;
private static final int LINEWIDTH = 3;
private static final String NAME = "TabTransferData";
private final DataFlavor FLAVOR = new DataFlavor(
DataFlavor.javaJVMLocalObjectMimeType, NAME);
private static GhostGlassPane s_glassPane = new GhostGlassPane();
private boolean m_isDrawRect = false;
private final Rectangle2D m_lineRect = new Rectangle2D.Double();
private final Color m_lineColor = new Color(0, 100, 255);
private TabAcceptor m_acceptor = null;
public DnDTabbedPane() {
super();
final DragSourceListener dsl = new DragSourceListener() {
public void dragEnter(DragSourceDragEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}
public void dragExit(DragSourceEvent e) {
e.getDragSourceContext()
.setCursor(DragSource.DefaultMoveNoDrop);
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
s_glassPane.setPoint(new Point(-1000, -1000));
s_glassPane.repaint();
}
public void dragOver(DragSourceDragEvent e) {
//e.getLocation()
//This method returns a Point indicating the cursor location in screen coordinates at the moment
TabTransferData data = getTabTransferData(e);
if (data == null) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
/*
Point tabPt = e.getLocation();
SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
if (DnDTabbedPane.this.contains(tabPt)) {
int targetIdx = getTargetTabIndex(tabPt);
int sourceIndex = data.getTabIndex();
if (getTabAreaBound().contains(tabPt)
&& (targetIdx >= 0)
&& (targetIdx != sourceIndex)
&& (targetIdx != sourceIndex + 1)) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
return;
} // if
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
*/
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
}
public void dragDropEnd(DragSourceDropEvent e) {
m_isDrawRect = false;
m_lineRect.setRect(0, 0, 0, 0);
// m_dragTabIndex = -1;
if (hasGhost()) {
s_glassPane.setVisible(false);
s_glassPane.setImage(null);
}
}
public void dropActionChanged(DragSourceDragEvent e) {
}
};
final DragGestureListener dgl = new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent e) {
// System.out.println("dragGestureRecognized");
Point tabPt = e.getDragOrigin();
int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
if (dragTabIndex < 0) {
return;
} // if
initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);
try {
e.startDrag(DragSource.DefaultMoveDrop,
new TabTransferable(DnDTabbedPane.this, dragTabIndex), dsl);
} catch (InvalidDnDOperationException idoe) {
idoe.printStackTrace();
}
}
};
//dropTarget =
new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,
new CDropTargetListener(), true);
new DragSource().createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, dgl);
m_acceptor = new TabAcceptor() {
public boolean isDropAcceptable(DnDTabbedPane a_component, int a_index) {
return true;
}
};
}
public TabAcceptor getAcceptor() {
return m_acceptor;
}
public void setAcceptor(TabAcceptor a_value) {
m_acceptor = a_value;
}
private TabTransferData getTabTransferData(DropTargetDropEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DropTargetDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getDragSourceContext()
.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
class TabTransferable implements Transferable {
private TabTransferData m_data = null;
public TabTransferable(DnDTabbedPane a_tabbedPane, int a_tabIndex) {
m_data = new TabTransferData(DnDTabbedPane.this, a_tabIndex);
}
public Object getTransferData(DataFlavor flavor) {
return m_data;
// return DnDTabbedPane.this;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] f = new DataFlavor[1];
f[0] = FLAVOR;
return f;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.getHumanPresentableName().equals(NAME);
}
}
class TabTransferData {
private DnDTabbedPane m_tabbedPane = null;
private int m_tabIndex = -1;
public TabTransferData() {
}
public TabTransferData(DnDTabbedPane a_tabbedPane, int a_tabIndex) {
m_tabbedPane = a_tabbedPane;
m_tabIndex = a_tabIndex;
}
public DnDTabbedPane getTabbedPane() {
return m_tabbedPane;
}
public void setTabbedPane(DnDTabbedPane pane) {
m_tabbedPane = pane;
}
public int getTabIndex() {
return m_tabIndex;
}
public void setTabIndex(int index) {
m_tabIndex = index;
}
}
private Point buildGhostLocation(Point a_location) {
Point retval = new Point(a_location);
switch (getTabPlacement()) {
case JTabbedPane.TOP: {
retval.y = 1;
retval.x -= s_glassPane.getGhostWidth() / 2;
} break;
case JTabbedPane.BOTTOM: {
retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();
retval.x -= s_glassPane.getGhostWidth() / 2;
} break;
case JTabbedPane.LEFT: {
retval.x = 1;
retval.y -= s_glassPane.getGhostHeight() / 2;
} break;
case JTabbedPane.RIGHT: {
retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();
retval.y -= s_glassPane.getGhostHeight() / 2;
} break;
} // switch
retval = SwingUtilities.convertPoint(DnDTabbedPane.this,
retval, s_glassPane);
return retval;
}
class CDropTargetListener implements DropTargetListener {
public void dragEnter(DropTargetDragEvent e) {
// System.out.println("DropTarget.dragEnter: " + DnDTabbedPane.this);
if (isDragAcceptable(e)) {
e.acceptDrag(e.getDropAction());
} else {
e.rejectDrag();
} // if
}
public void dragExit(DropTargetEvent e) {
// System.out.println("DropTarget.dragExit: " + DnDTabbedPane.this);
m_isDrawRect = false;
}
public void dropActionChanged(DropTargetDragEvent e) {
}
public void dragOver(final DropTargetDragEvent e) {
TabTransferData data = getTabTransferData(e);
if (getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM) {
initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data);
} else {
initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data);
} // if-else
repaint();
if (hasGhost()) {
s_glassPane.setPoint(buildGhostLocation(e.getLocation()));
s_glassPane.repaint();
}
}
public void drop(DropTargetDropEvent a_event) {
// System.out.println("DropTarget.drop: " + DnDTabbedPane.this);
if (isDropAcceptable(a_event)) {
convertTab(getTabTransferData(a_event),
getTargetTabIndex(a_event.getLocation()));
a_event.dropComplete(true);
} else {
a_event.dropComplete(false);
} // if-else
m_isDrawRect = false;
repaint();
}
public boolean isDragAcceptable(DropTargetDragEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
public boolean isDropAcceptable(DropTargetDropEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
}
private boolean m_hasGhost = true;
public void setPaintGhost(boolean flag) {
m_hasGhost = flag;
}
public boolean hasGhost() {
return m_hasGhost;
}
/**
* returns potential index for drop.
* #param a_point point given in the drop site component's coordinate
* #return returns potential index for drop.
*/
private int getTargetTabIndex(Point a_point) {
boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM;
// if the pane is empty, the target index is always zero.
if (getTabCount() == 0) {
return 0;
} // if
for (int i = 0; i < getTabCount(); i++) {
Rectangle r = getBoundsAt(i);
if (isTopOrBottom) {
r.setRect(r.x - r.width / 2, r.y, r.width, r.height);
} else {
r.setRect(r.x, r.y - r.height / 2, r.width, r.height);
} // if-else
if (r.contains(a_point)) {
return i;
} // if
} // for
Rectangle r = getBoundsAt(getTabCount() - 1);
if (isTopOrBottom) {
int x = r.x + r.width / 2;
r.setRect(x, r.y, getWidth() - x, r.height);
} else {
int y = r.y + r.height / 2;
r.setRect(r.x, y, r.width, getHeight() - y);
} // if-else
return r.contains(a_point) ? getTabCount() : -1;
}
private void convertTab(TabTransferData a_data, int a_targetIndex) {
DnDTabbedPane source = a_data.getTabbedPane();
int sourceIndex = a_data.getTabIndex();
if (sourceIndex < 0) {
return;
} // if
Component cmp = source.getComponentAt(sourceIndex);
String str = source.getTitleAt(sourceIndex);
if (this != source) {
source.remove(sourceIndex);
if (a_targetIndex == getTabCount()) {
addTab(str, cmp);
} else {
if (a_targetIndex < 0) {
a_targetIndex = 0;
} // if
insertTab(str, null, cmp, null, a_targetIndex);
} // if
setSelectedComponent(cmp);
// System.out.println("press="+sourceIndex+" next="+a_targetIndex);
return;
} // if
if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
//System.out.println("press="+prev+" next="+next);
return;
} // if
if (a_targetIndex == getTabCount()) {
//System.out.println("last: press="+prev+" next="+next);
source.remove(sourceIndex);
addTab(str, cmp);
setSelectedIndex(getTabCount() - 1);
} else if (sourceIndex > a_targetIndex) {
//System.out.println(" >: press="+prev+" next="+next);
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex);
setSelectedIndex(a_targetIndex);
} else {
//System.out.println(" <: press="+prev+" next="+next);
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex - 1);
setSelectedIndex(a_targetIndex - 1);
}
}
private void initTargetLeftRightLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);
m_isDrawRect = true;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
}
}
private void initTargetTopBottomLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
}
}
private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {
//Point p = (Point) pt.clone();
getRootPane().setGlassPane(s_glassPane);
if (hasGhost()) {
Rectangle rect = getBoundsAt(a_tabIndex);
BufferedImage image = new BufferedImage(c.getWidth(),
c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
c.paint(g);
image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
s_glassPane.setImage(image);
} // if
s_glassPane.setPoint(buildGhostLocation(tabPt));
s_glassPane.setVisible(true);
}
private Rectangle getTabAreaBound() {
Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (m_isDrawRect) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(m_lineColor);
g2.fill(m_lineRect);
} // if
}
public interface TabAcceptor {
boolean isDropAcceptable(DnDTabbedPane a_component, int a_index);
}
}
class GhostGlassPane extends JPanel {
public static final long serialVersionUID = 1L;
private final AlphaComposite m_composite;
private Point m_location = new Point(0, 0);
private BufferedImage m_draggingGhost = null;
public GhostGlassPane() {
setOpaque(false);
m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);
}
public void setImage(BufferedImage draggingGhost) {
m_draggingGhost = draggingGhost;
}
public void setPoint(Point a_location) {
m_location.x = a_location.x;
m_location.y = a_location.y;
}
public int getGhostWidth() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getWidth(this);
}
public int getGhostHeight() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getHeight(this);
}
public void paintComponent(Graphics g) {
if (m_draggingGhost == null) {
return;
} // if
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(m_composite);
g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null);
}
}
Found this code out there on the tubes:
class DnDTabbedPane extends JTabbedPane {
private static final int LINEWIDTH = 3;
private static final String NAME = "test";
private final GhostGlassPane glassPane = new GhostGlassPane();
private final Rectangle2D lineRect = new Rectangle2D.Double();
private final Color lineColor = new Color(0, 100, 255);
//private final DragSource dragSource = new DragSource();
//private final DropTarget dropTarget;
private int dragTabIndex = -1;
public DnDTabbedPane() {
super();
final DragSourceListener dsl = new DragSourceListener() {
public void dragEnter(DragSourceDragEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}
public void dragExit(DragSourceEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
lineRect.setRect(0,0,0,0);
glassPane.setPoint(new Point(-1000,-1000));
glassPane.repaint();
}
public void dragOver(DragSourceDragEvent e) {
//e.getLocation()
//This method returns a Point indicating the cursor location in screen coordinates at the moment
Point tabPt = e.getLocation();
SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
Point glassPt = e.getLocation();
SwingUtilities.convertPointFromScreen(glassPt, glassPane);
int targetIdx = getTargetTabIndex(glassPt);
if(getTabAreaBound().contains(tabPt) && targetIdx>=0 &&
targetIdx!=dragTabIndex && targetIdx!=dragTabIndex+1) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}else{
e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
}
}
public void dragDropEnd(DragSourceDropEvent e) {
lineRect.setRect(0,0,0,0);
dragTabIndex = -1;
if(hasGhost()) {
glassPane.setVisible(false);
glassPane.setImage(null);
}
}
public void dropActionChanged(DragSourceDragEvent e) {}
};
final Transferable t = new Transferable() {
private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);
public Object getTransferData(DataFlavor flavor) {
return DnDTabbedPane.this;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] f = new DataFlavor[1];
f[0] = this.FLAVOR;
return f;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.getHumanPresentableName().equals(NAME);
}
};
final DragGestureListener dgl = new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent e) {
Point tabPt = e.getDragOrigin();
dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
if(dragTabIndex<0) return;
initGlassPane(e.getComponent(), e.getDragOrigin());
try{
e.startDrag(DragSource.DefaultMoveDrop, t, dsl);
}catch(InvalidDnDOperationException idoe) {
idoe.printStackTrace();
}
}
};
//dropTarget =
new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true);
new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);
}
class CDropTargetListener implements DropTargetListener{
public void dragEnter(DropTargetDragEvent e) {
if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction());
else e.rejectDrag();
}
public void dragExit(DropTargetEvent e) {}
public void dropActionChanged(DropTargetDragEvent e) {}
public void dragOver(final DropTargetDragEvent e) {
if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) {
initTargetLeftRightLine(getTargetTabIndex(e.getLocation()));
}else{
initTargetTopBottomLine(getTargetTabIndex(e.getLocation()));
}
repaint();
if(hasGhost()) {
glassPane.setPoint(e.getLocation());
glassPane.repaint();
}
}
public void drop(DropTargetDropEvent e) {
if(isDropAcceptable(e)) {
convertTab(dragTabIndex, getTargetTabIndex(e.getLocation()));
e.dropComplete(true);
}else{
e.dropComplete(false);
}
repaint();
}
public boolean isDragAcceptable(DropTargetDragEvent e) {
Transferable t = e.getTransferable();
if(t==null) return false;
DataFlavor[] f = e.getCurrentDataFlavors();
if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
return true;
}
return false;
}
public boolean isDropAcceptable(DropTargetDropEvent e) {
Transferable t = e.getTransferable();
if(t==null) return false;
DataFlavor[] f = t.getTransferDataFlavors();
if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
return true;
}
return false;
}
}
private boolean hasGhost = true;
public void setPaintGhost(boolean flag) {
hasGhost = flag;
}
public boolean hasGhost() {
return hasGhost;
}
private int getTargetTabIndex(Point glassPt) {
Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);
boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM;
for(int i=0;i<getTabCount();i++) {
Rectangle r = getBoundsAt(i);
if(isTB) r.setRect(r.x-r.width/2, r.y, r.width, r.height);
else r.setRect(r.x, r.y-r.height/2, r.width, r.height);
if(r.contains(tabPt)) return i;
}
Rectangle r = getBoundsAt(getTabCount()-1);
if(isTB) r.setRect(r.x+r.width/2, r.y, r.width, r.height);
else r.setRect(r.x, r.y+r.height/2, r.width, r.height);
return r.contains(tabPt)?getTabCount():-1;
}
private void convertTab(int prev, int next) {
if(next<0 || prev==next) {
//System.out.println("press="+prev+" next="+next);
return;
}
Component cmp = getComponentAt(prev);
String str = getTitleAt(prev);
if(next==getTabCount()) {
//System.out.println("last: press="+prev+" next="+next);
remove(prev);
addTab(str, cmp);
setSelectedIndex(getTabCount()-1);
}else if(prev>next) {
//System.out.println(" >: press="+prev+" next="+next);
remove(prev);
insertTab(str, null, cmp, null, next);
setSelectedIndex(next);
}else{
//System.out.println(" <: press="+prev+" next="+next);
remove(prev);
insertTab(str, null, cmp, null, next-1);
setSelectedIndex(next-1);
}
}
private void initTargetLeftRightLine(int next) {
if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
lineRect.setRect(0,0,0,0);
}else if(next==getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount()-1);
lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
}else if(next==0) {
Rectangle rect = getBoundsAt(0);
lineRect.setRect(-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
}else{
Rectangle rect = getBoundsAt(next-1);
lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
}
}
private void initTargetTopBottomLine(int next) {
if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
lineRect.setRect(0,0,0,0);
}else if(next==getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount()-1);
lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
}else if(next==0) {
Rectangle rect = getBoundsAt(0);
lineRect.setRect(rect.x,-LINEWIDTH/2,rect.width,LINEWIDTH);
}else{
Rectangle rect = getBoundsAt(next-1);
lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
}
}
private void initGlassPane(Component c, Point tabPt) {
//Point p = (Point) pt.clone();
getRootPane().setGlassPane(glassPane);
if(hasGhost()) {
Rectangle rect = getBoundsAt(dragTabIndex);
BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
c.paint(g);
image = image.getSubimage(rect.x,rect.y,rect.width,rect.height);
glassPane.setImage(image);
}
Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane);
glassPane.setPoint(glassPt);
glassPane.setVisible(true);
}
private Rectangle getTabAreaBound() {
Rectangle lastTab = getUI().getTabBounds(this, getTabCount()-1);
return new Rectangle(0,0,getWidth(),lastTab.y+lastTab.height);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(dragTabIndex>=0) {
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(lineColor);
g2.fill(lineRect);
}
}
}
class GhostGlassPane extends JPanel {
private final AlphaComposite composite;
private Point location = new Point(0, 0);
private BufferedImage draggingGhost = null;
public GhostGlassPane() {
setOpaque(false);
composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
}
public void setImage(BufferedImage draggingGhost) {
this.draggingGhost = draggingGhost;
}
public void setPoint(Point location) {
this.location = location;
}
public void paintComponent(Graphics g) {
if(draggingGhost == null) return;
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(composite);
double xx = location.getX() - (draggingGhost.getWidth(this) /2d);
double yy = location.getY() - (draggingGhost.getHeight(this)/2d);
g2.drawImage(draggingGhost, (int)xx, (int)yy , null);
}
}
#Tony: It looks like Euguenes solution just overlooks preserving TabComponents during a swap.
The convertTab method just needs to remember the TabComponent and set it to the new tabs it makes.
Try using this:
private void convertTab(TabTransferData a_data, int a_targetIndex) {
DnDTabbedPane source = a_data.getTabbedPane();
System.out.println("this=source? " + (this == source));
int sourceIndex = a_data.getTabIndex();
if (sourceIndex < 0) {
return;
} // if
//Save the tab's component, title, and TabComponent.
Component cmp = source.getComponentAt(sourceIndex);
String str = source.getTitleAt(sourceIndex);
Component tcmp = source.getTabComponentAt(sourceIndex);
if (this != source) {
source.remove(sourceIndex);
if (a_targetIndex == getTabCount()) {
addTab(str, cmp);
setTabComponentAt(getTabCount()-1, tcmp);
} else {
if (a_targetIndex < 0) {
a_targetIndex = 0;
} // if
insertTab(str, null, cmp, null, a_targetIndex);
setTabComponentAt(a_targetIndex, tcmp);
} // if
setSelectedComponent(cmp);
return;
} // if
if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
return;
} // if
if (a_targetIndex == getTabCount()) {
source.remove(sourceIndex);
addTab(str, cmp);
setTabComponentAt(getTabCount() - 1, tcmp);
setSelectedIndex(getTabCount() - 1);
} else if (sourceIndex > a_targetIndex) {
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex);
setTabComponentAt(a_targetIndex, tcmp);
setSelectedIndex(a_targetIndex);
} else {
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex - 1);
setTabComponentAt(a_targetIndex - 1, tcmp);
setSelectedIndex(a_targetIndex - 1);
}
}
Add this to isDragAcceptable to avoid Exceptions:
boolean transferDataFlavorFound = false;
for (DataFlavor transferDataFlavor : t.getTransferDataFlavors()) {
if (FLAVOR.equals(transferDataFlavor)) {
transferDataFlavorFound = true;
break;
}
}
if (transferDataFlavorFound == false) {
return false;
}

Categories