JOptionPane.showInputDialog() is called twice, why? - java

In the showDebugWindow() method inside a class I called, [TinyDebug], the JOptionPane.showInputDialog() is called twice even after I input the correct password, why is that?
Additionally, this code is being executed from an update() method in my Game class, which is called once every second.
Take a look below at the following sets of code for the problem.
Game:
public class Game extends TinyPixel {
private static Game game;
private static KeyManager keyManager;
private static MouseManager mouseManager;
private static GameStateManager sManager;
private boolean isRunning;
private int targetTime;
private final int frameCap = 60;
public Game(String gameTitle, String gameVersion, int gameWidth, int gameRatio, int gameScale) {
super(gameTitle, gameVersion, gameWidth, gameRatio, gameScale);
init();
}
public void init() {
Utilities.printMessage("\t\t-[" + Library.gameTitle + "]-" +
"\n[Game Version]: " + gameVersion +
"\n[Unique Build Number]: " + Utilities.generateCode(16));
ResourceLoader.loadImages();
ResourceLoader.loadMusic();
ResourceLoader.loadSound();
ResourceLoader.loadFonts();
keyManager = new KeyManager(this);
mouseManager = new MouseManager(this);
sManager = new GameStateManager(this);
}
#Override public void update() {
sManager.update();
mouseManager.update();
}
#Override public void render() {
BufferStrategy bs = tinyWindow.getCanvas().getBufferStrategy();
if (bs == null) {
tinyWindow.getCanvas().createBufferStrategy(3);
tinyWindow.getCanvas().requestFocus();
return;
}
Graphics g = bs.getDrawGraphics();
g.clearRect(0, 0, gameWidth, gameHeight);
sManager.render(g);
g.dispose();
bs.show();
}
public void start() {
if(isRunning) return;
isRunning = true;
new Thread(this, gameTitle + " " + gameVersion).start();
}
public void stop() {
if(!isRunning) return;
isRunning = false;
}
#Override public void run() {
isRunning = true;
targetTime = 1000 / frameCap;
long start = 0;
long elapsed = 0;
long wait = 0;
while (isRunning) {
start = System.nanoTime();
update();
render();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if (wait < 0) wait = 5;
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
Utilities.printErrorMessage("Failed to Load " + gameTitle + " " + gameVersion);
}
}
stop();
}
public static KeyManager getKeyManager() {
return keyManager;
}
public static GameStateManager getsManager() {
return sManager;
}
public static Game getGame() {
return game;
}
}
GameLauncher:
public class GameLauncher {
public static void main(String[] args) {
new Game(Library.gameTitle, Library.gameVersion, 640, TinyPixel.Square, 1).start();
}
}
GameStateManager:
public class GameStateManager {
private int numStates = 3;
public static final int MenuState = 0;
public static final int LoadingState = 1;
public static final int GameState = 2;
public static GameState[] gStates;
private static int currentState;
private static String currentMusic;
protected Game game;
public GameStateManager(Game game) {
this.game = game;
init();
}
private void init() {
gStates = new GameState[numStates];
currentState = MenuState;
//currentMusic = Library.backgroundMusic;
//TinyPlayer.playMusic(currentMusic);
loadState(currentState);
}
private void loadState(int gState) {
if (gState == MenuState) gStates[gState] = new MenuState(game, this);
if (gState == LoadingState) gStates[gState] = new LoadingState(game, this);
if (gState == GameState) gStates[gState] = new PlayState(game, this);
}
private void unloadState(int gState) {
gStates[gState] = null;
}
public void setState(int gState) {
unloadState(gState);
currentState = gState;
loadState(gState);
}
private void changeMusic(String key) {
if (currentMusic.equals(key)) return;
TinyPlayer.stopMusic(currentMusic);
currentMusic = key;
TinyPlayer.loop(currentMusic);
}
public void update() {
try {
gStates[currentState].update();
} catch (Exception e) {}
}
public void render(Graphics g) {
try {
gStates[currentState].render(g);
} catch (Exception e) {}
}
public static int getCurrentState() {
return currentState;
}
}
GameState:
public abstract class GameState {
protected Game game;
protected GameStateManager sManager;
public GameState(Game game, GameStateManager sManager) {
this.game = game;
this.sManager = sManager;
init();
}
public abstract void init();
public abstract void update();
public abstract void render(Graphics g);
}
MenuState:
public class MenuState extends GameState {
private Rectangle playBtn, exitBtn;
private TinyDebug tinyDebug;
public static final Color DEFAULT_COLOR = new Color(143, 48, 223);
public MenuState(Game game, GameStateManager sManager) {
super(game, sManager);
init();
}
public void init() {
tinyDebug = new TinyDebug();
int xOffset = 90, yOffset = 70;
playBtn = new Rectangle(Game.getWidth() / 2 - xOffset, Game.getHeight() / 2, 180, 40);
exitBtn = new Rectangle(Game.getWidth() / 2 - xOffset, Game.getHeight() / 2 + yOffset, 180, 40);
}
public void update() {
if (Game.getKeyManager().debug.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_Q, true);
tinyDebug.showDebugWindow();
}
if (Game.getKeyManager().space.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_SPACE, true);
sManager.setState(GameStateManager.LoadingState);
}
if (Game.getKeyManager().exit.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_ESCAPE, true);
System.exit(0);
}
}
public void render(Graphics g) {
//Render the Background
g.drawImage(Library.menuBackground, 0, 0, Game.getWidth(), Game.getHeight(), null);
//Render the Game Version
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Version: " + Library.gameVersion, Game.getWidth() / 2 + 245, Game.getHeight() - 30);
//Render the Social Section
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#nickadamou", 20, Game.getHeight() - 60);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#nicholasadamou", 20, Game.getHeight() - 45);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Ever Tried? Ever Failed? No Matter. Try Again. Fail Again. Fail Better.", 20, Game.getHeight() - 30);
//Render the Debug Section
tinyDebug.renderDebug(g);
g.setColor(Color.white);
g.drawRect(playBtn.x, playBtn.y, playBtn.width, playBtn.height);
g.drawRect(exitBtn.x, exitBtn.y, exitBtn.width, exitBtn.height);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 14), Color.white, "Play Game [space]", playBtn.x + 10, playBtn.y + 25);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 14), Color.white, "Exit Game [esc]", exitBtn.x + 20, exitBtn.y + 25);
}
}
keyManager:
public class KeyManager implements KeyListener {
private Game game;
public KeyManager(Game game) {
this.game = game;
game.getTinyWindow().getCanvas().addKeyListener(this);
}
public class Key {
private int amtPressed = 0;
private boolean isPressed = false;
public int getAmtPressed() {
return amtPressed;
}
public boolean isPressed() {
return isPressed;
}
public void toggle(boolean isPressed) {
this.isPressed = isPressed;
if (isPressed) amtPressed++;
}
}
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public Key space = new Key();
public Key debug = new Key();
public Key exit = new Key();
public void keyPressed(KeyEvent key) {
toggleKey(key.getKeyCode(), true);
}
public void keyReleased(KeyEvent key) {
toggleKey(key.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {}
public void toggleKey(int keyCode, boolean isPressed) {
game.getTinyWindow().getFrame().requestFocus();
game.getTinyWindow().getCanvas().requestFocus();
if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) {
up.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) {
down.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) {
left.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) {
right.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_SPACE) {
space.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_Q) {
debug.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_ESCAPE) {
exit.toggle(isPressed);
}
}
#SuppressWarnings("unused")
private void debug(KeyEvent key) {
System.out.println("[keyCode]: " + key.getKeyCode());
}
}
TinyDebug:
public class TinyDebug {
private final String appTitle = Library.gameTitle;
private String tinyPassword, tinyBuildCode;
private boolean isAllowedDebugging = false;
private boolean isShowingTinyText = false;
public TinyDebug() {
tinyPassword = "test123"; // - Standard Password (Non-Renewable)
//tinyPassword = Utilities.generateCode(16); // - Stronger Password (Renewable)
writePasswordToFile(tinyPassword);
tinyBuildCode = Utilities.generateCode(16);
}
//TODO: This method invokes JOptionPane.showInputDialog() twice even after I input the correct password, why?
public void showDebugWindow() {
boolean hasRun = true;
if (hasRun) {
Clipboard cBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
cBoard.setContents(new StringSelection(tinyPassword), null);
if (isAllowedDebugging() && isShowingTinyText()) return;
String userPassword = JOptionPane.showInputDialog("Input Password to Enter [TinyDebug].");
do {
if (userPassword.equals(tinyPassword)) {
JOptionPane.showMessageDialog(null, "[" + appTitle + "]: The Password Entered is Correct.", appTitle + " Message", JOptionPane.PLAIN_MESSAGE);
isAllowedDebugging(true);
isShowingTinyText(true);
break;
} else {
JOptionPane.showMessageDialog(null, "[Error Code]: " + Utilities.generateCode(16) + "\n[Error]: Password is Incorrect.", appTitle + " Error Message", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} while (userPassword != null || userPassword.trim().isEmpty() != true);
}
hasRun = false;
}
#SuppressWarnings("unused")
public void renderDebug(Graphics g) {
if (isAllowedDebugging()) {
//TODO: Render Debug Information.
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Tiny Pixel [Debug]", 5, 10);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#. [Options are Shown Here]", 10, 25);
if (isShowingTinyText()) {
String debugHeader = appTitle + " Information";
String debugPasswordField = appTitle + " Information:";
String debugBuildNumber = appTitle + " Unique Build #: " + getTinyBuildCode();
}
}
}
//TODO: This method prints the [Utilities.printMessage(appTitle + ": [tinyPassword] Generated and Stored # FilePath: \n" + logFile.getAbsolutePath());] twice, why?
private void writePasswordToFile(String tinyPassword) {
BufferedWriter bWriter = null;
try {
File logFile = new File("tinyPassword.txt");
Utilities.printMessage(appTitle + ": [tinyPassword] Generated and Stored # FilePath: \n" + logFile.getAbsolutePath());
bWriter = new BufferedWriter(new FileWriter(logFile));
bWriter.write(appTitle + " debug Password: " + tinyPassword);
} catch (Exception e) {
Utilities.printErrorMessage("Failed to Write [tinyPassword] to File.");
} finally {
try {
bWriter.close();
} catch (Exception e) {
Utilities.printErrorMessage("Failed to Close [bWriter] Object.");
}
}
}
public String getTinyPassword() {
return tinyPassword;
}
public String getTinyBuildCode() {
return tinyBuildCode;
}
public void isShowingTinyText(boolean isShowingTinyText) {
this.isShowingTinyText = isShowingTinyText;
}
public boolean isShowingTinyText() {
return isShowingTinyText;
}
public void isAllowedDebugging(boolean isAllowedDebugging) {
this.isAllowedDebugging = isAllowedDebugging;
if (isAllowedDebugging) showDebugWindow();
}
public boolean isAllowedDebugging() {
return isAllowedDebugging;
}
}

In showDebugWindow() method, you have this statement:
if (userPassword.equals(tinyPassword)) {
...
isAllowedDebugging(true); // Problematic statement
...
}
Which calls this method:
public void isAllowedDebugging(boolean isAllowedDebugging) {
this.isAllowedDebugging = isAllowedDebugging;
if (isAllowedDebugging) showDebugWindow(); // Second call?
}
As you see, when you set isAllowedDebugging switch, you also call the method, so when you enter password correct, this second call happens.

Related

why applyLinearImpulse is not working, using libgdx?

I need some help when I try make a game, which is controlled by commands. I need to use textarea and I try to pass the value from textarea to contructer. But my game is not working. I know what mistake is appeared because I call contructer 2 times. I add some code:
public class inputs extends Game implements Disposable {
private Skin skin;
private Viewport viewport;
public Stage stage;
private Table table;
private TextButton button;
public TextArea TF;
private Main game;
public SpriteBatch spriteBatch;
public inputs(final SpriteBatch sb, final Main game){
viewport = new FitViewport(1200, 624, new OrthographicCamera());
stage = new Stage(viewport, sb);
skin = new Skin(Gdx.files.internal("data/uiskin.json"));
button = new TextButton("Send", skin, "default");
TF = new TextArea("", skin);
TF.setWidth(300);
TF.setHeight(570);
TF.setPosition(0,54);
button.setWidth(300);
button.setHeight(54);
button.setPosition(0, 0);
button.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
spriteBatch = new SpriteBatch();
setScreen(new MainCodeProgram(game,TF.getText(),spriteBatch));
TF.setText("");
button.setTouchable(Touchable.disabled);
}
});
stage.addActor(TF);
stage.addActor(button);
Gdx.input.setInputProcessor(stage);
Gdx.input.setInputProcessor(stage);
}
public void setButtonTouchable(){
button.setTouchable(Touchable.enabled);
}
#Override
public void create() {
}
#Override
public void dispose() {
stage.dispose();
}
}
Main.java :
public class Main extends Game {
public SpriteBatch spriteBatch;
public static int Width = 400;
public static int Height = 208;
public static final short objectwhit = 32;
public static final short mariowhit= 2;
public static final short itemwhit = 256;
public static float PPM = 100;
public static final short marioheadwhit = 512;
public static final short blockwhit = 4;
public static final short coinwhit = 8;
public static final short nothing = 0;
public static final short ground = 1;
public static final short destroyedwhit = 16;
public static final short enemywhit = 64;
public static final short enemyheadwhit = 128;
public static inputs inp1;
#Override
public void create () {
spriteBatch = new SpriteBatch();
inp1 = new inputs(spriteBatch,this);
setScreen(new MainCodeProgram(this,null,spriteBatch));
}
#Override
public void dispose() {
super.dispose();
spriteBatch.dispose();
}
}
Pseudocode recognize :
public class MainCodeProgram extends JFrame implements Screen, TextInputListener, Disposable {
static ArrayList<String> firstintkint = new ArrayList<String>();
static ArrayList<Integer> firstintvalue = new ArrayList<Integer>(); //int
private Main game;
private OrthographicCamera orthographicCamera;
private TextureAtlas textureAtlas;
public static int whichlevel=1;
private Mario player;
public Stage stage;
private Hud hud;
private TmxMapLoader maploader;
private TiledMap tilemap;
static int walks = 0;
private OrthogonalTiledMapRenderer renderer;
private Viewport viewport;
private World world;
private Array<Item> items;
private LinkedBlockingQueue<ItemVector> itemstoSpawn;
String text="";
private Box2DDebugRenderer b2dr;
private OtherWorldCreator otherWorldCreator;
public String kodas;
public boolean b =false;
public MainCodeProgram(){
}
public MainCodeProgram(Main game, String text,SpriteBatch spriteBatch) {
if(text == null){
textureAtlas = new TextureAtlas("All.pack");
this.game= game;
orthographicCamera = new OrthographicCamera();
viewport = new FitViewport(Main.Width / Main.PPM, Main.Height / Main.PPM, orthographicCamera);
viewport.apply();
hud = new Hud(game.spriteBatch);
newlevel();
otherWorldCreator = new OtherWorldCreator(this);
player = new Mario( this);
world.setContactListener(new WorldContact());
items = new Array<Item>();
itemstoSpawn = new LinkedBlockingQueue<ItemVector>();
}
if(text != null){
b = true;
textureAtlas = new TextureAtlas("All.pack");
this.game= game;
orthographicCamera = new OrthographicCamera();
viewport = new FitViewport(Main.Width / Main.PPM, Main.Height / Main.PPM, orthographicCamera);
viewport.apply();
hud = new Hud(spriteBatch);
newlevel();
otherWorldCreator = new OtherWorldCreator(this);
player = new Mario( this);
world.setContactListener(new WorldContact());
items = new Array<Item>();
itemstoSpawn = new LinkedBlockingQueue<ItemVector>();
input(text);
}
}
public TextureAtlas getAtlas(){return textureAtlas;}
#Override
public void show() {}
int i = 0, kur = 1;
public void handleInput(float dt) {
if (player.currentstate!= Mario.State.died) {
;
}
}
public void spawnItem(ItemVector idef)
{
itemstoSpawn.add(idef);
}
public void handleSpawningItems(){
if(!itemstoSpawn.isEmpty())
{
ItemVector idef = itemstoSpawn.poll();
if(idef.type == Mushroom.class){items.add(new Mushroom(this, idef.position.x,idef.position.y));}
}
}
public void update(float dt)
{
handleInput(dt);
handleSpawningItems();
world.step(1 / 60f, 6, 2);
player.update(dt);
for (Enemy enemy: otherWorldCreator.getEbemies()) {
enemy.update(dt);
if(enemy.getX() < player.getX() + 224 / Main.PPM){enemy.b2body.setActive(true);}
}
for(Item item : items){item.update(dt);}
hud.refresh(dt);
if(player.currentstate!= Mario.State.died){orthographicCamera.position.x = player.b2body.getPosition().x;}
orthographicCamera.update();
renderer.setView(orthographicCamera);
}
public boolean gameOver()
{
if(player.currentstate== Mario.State.died && palyer.getStateTimer() > 3){return true;}
if(whichlevel== 5){return true;}
else if(player.getY() <0){return true;}
else{return false;}
}
public boolean Youwonn()
{
if(whichlevel==4){return true;}
else{return false;}
}
#Override
public void render(float delta) {
update(delta);
int k = 0;
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
b2dr.render(world, orthographicCamera.combined);
game.spriteBatch.setProjectionMatrix(orthographicCamera.combined);
game.spriteBatch.begin();
game.draw(game.spriteBatch);
for (Enemy enemy: otherWorldCreator.getEbemies())
enemy.draw(game.spriteBatch);
for(Item item : items)
item.draw(game.spriteBatch);
game.spriteBatch.end();
game.spriteBatch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
if(gameOver())
{
whichlevel= 1;
game.setScreen(new GameOverWorld(game));
dispose();
}
if ((player.getX() > 15 && whichlevel< 4)) {
whichlevel++;
if(whichlevel!=4){
game.setScreen(new MainCodeProgram(game,"",""));
dispose();
}
}
if (whichlevel==4)
{
game.setScreen(new WinWindow(game));
dispose();
}
Main.inp1.stage.draw();
}
#Override
public void resize(int width, int height) {viewport.update(width,height);}
public World getWorld(){ return world;}
public TiledMap getMap(){return tilemap;}
#Override
public void pause() {}
#Override
public void resume() {}
#Override
public void hide() {}
public void newlevel()
{
maploader = new TmxMapLoader();
if(whichlevel== 1){tilemap = maploader.load("mario1lvl.tmx");
}
if (whichlevel== 2){tilemap = maploader.load("mario2lvl.tmx");}
if (whichlevel== 3){tilemap = maploader.load("mario3lvl.tmx");}
if (whichlevel== 4){
game.setScreen(new WinWindow(game));}
renderer = new OrthogonalTiledMapRenderer(tilemap, 1 / Main.PPM);
orthographicCamera.position.set(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2, 0);
world = new World(new Vector2(0, -10 ), true);
b2dr = new Box2DDebugRenderer();
}
#Override
public void dispose() {
tilemap.dispose();
renderer.dispose();
world.dispose();
b2dr.dispose();
hud.dispose();
}
public void input(String text) {
ArrayList<String> pseudocode = new ArrayList<String>();
this.text = text;
i = 0;
String str = text;
String split[] = str.split("/");
for (String spacebar : split) {
pseudocode.add(spacebar);
i = 0;
}
int foras = 0;
for (int i = 0;i < pseudocode.size(); i++) {
if(pseudocode.get(i).equals("jump")||pseudocode.get(i).equals("jump;")){jump();}
if(pseudocode.get(i).startsWith("int")){recognizeint(pseudocode.get(i));}
if(pseudocode.get(i).startsWith("for"))
{
recognizefor(pseudocode.get(i));
foras++;
}
if(pseudocode.get(i).startsWith("while")){ recognizewhile(pseudocode.get(i));}
if(pseudocode.get(i).endsWith("--")||pseudocode.get(i).endsWith("--;"))
{
if(foras == 0){minuminus(pseudocode.get(i));}
else{foras--;}
}
if(pseudocode.get(i).endsWith("++")||pseudocode.get(i).endsWith("++;"))
{
if(foras==0){plusplus(pseudocode.get(i));}
else{foras--;}
}
if(istheend){
walks = 0;
istheend = false;
}
}
}
#Override
public void canceled() {
}
public void jump()
{
if(istheend){
try {Thread.sleep(1*walks);
} catch (InterruptedException e) {e.printStackTrace();}}
else{try {Thread.sleep(50*walks);
} catch (InterruptedException e) {e.printStackTrace();}}
walks = 0;
if(player.b2body.getLinearVelocity().y == 0){
if(b == true) {
player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true); //Mistake is here
}
}
else if(player.b2body.getLinearVelocity().y != 0){
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
}
}
}
Mistake is here:
public void jump()
{
if(istheend){
try {Thread.sleep(1*walks);
} catch (InterruptedException e) {e.printStackTrace();}}
else{try {Thread.sleep(50*walks);
} catch (InterruptedException e) {e.printStackTrace();}}
walks = 0;
if(player.b2body.getLinearVelocity().y == 0){
if(b == true) {
player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true); //Mistake is here
}
}
else if(player.b2body.getLinearVelocity().y != 0){
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
}
}
Thank you very much for help
I believe your code it is a little confusing, for the ApplyLinearImpulse works in your HandleInput you send a command jump() and inside the Entity you make the jump() method and also to make the animation to join the b2body, with update(dt) method + getState() + getFrame().
Your jump() method should be simple like this
public void jump(){
if(currentState != State.Jumping){
b2body.applyLinearImpulse(new Vector2(0,4f), b2body.getWorldCenter(), true);
currentState=State.JUMPING
}
}
What should be stuck the applyLinearImpulse are the conditions you included. Try to remove it all and leave only the main stuff. Use also LOGS everywhere Gdx.app.log("MESSAGE:", "" + variable); and you can start seeing what is going in and out with your methods and variables, and find your mistake.
Also, if you would like to learn more and don't forget any detail regarding map / viewport / b2bodies, follow this tutorial that I use as my guide for B2Box (Youtube / Github), it is very quick and easy to follow and you are going to love use B2Box for everything :-) and also continue with LibGdx Framework developments.
Click here Youtube Tutorial.
Click here GitHub codes.
I hope it helps you.
Cheers!!

Accessing a string from another class in Java

This is slightly different from the usual issue. I know how I would do this if I could set the string to public static String passcode;but the problem is I can't. I need a solution from what I am trying to achieve here:
public class EncryptionSubtask {
public static void main(String[] args) {
Main m2 = new Main();
m2.setVisible(true);
m2.setResizable(true);
m2.setLayout(new FlowLayout());
}
public EncryptionSubtask() {
log("Running Substask");
Random rand = new Random();
int n1 = 33 + rand.nextInt(94);
int n2 = 33 + rand.nextInt(94);
int n3 = 33 + rand.nextInt(94);
int n4 = 33 + rand.nextInt(94);
int n5 = 33 + rand.nextInt(94);
int n6 = 33 + rand.nextInt(94);
int n7 = 33 + rand.nextInt(94);
int n8 = 33 + rand.nextInt(94);
String c1 = Character.toString ((char) n1);
String c2 = Character.toString ((char) n2);
String c3 = Character.toString ((char) n3);
String c4 = Character.toString ((char) n4);
String c5 = Character.toString ((char) n5);
String c6 = Character.toString ((char) n6);
String c7 = Character.toString ((char) n7);
String c8 = Character.toString ((char) n8);
String passcode = (c1+c2+c3+c4+c5+c6+c7+c8);
System.out.println(passcode);
}
Where I want to get "passcode" to here:
public class Main extends Frame implements Runnable, KeyListener, MouseListener, WindowListener {
private static final long serialVersionUID = 1L;
Thread thread;
BufferedImage backbuffer;
Graphics2D g2d;
AffineTransform transform = new AffineTransform();
enum Modes {
Menu, Encrypt, Decrypt
}
Modes mode = Modes.Menu;
public Image background;
public static void main(String[] args) {
Main m = new Main();
m.setVisible(true);
m.setResizable(true);
m.setLayout(new FlowLayout());
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
dispose();
log("Exiting...");
System.exit(0);
}
#Override
public void windowDeactivated(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX() - 8;
int y = e.getY() - 30;
// System.out.println(y);
if (x >= 50 && x <= 143 && y >= 50 && y <= 75) { //if statement for encrypt button bounds
log("Button Pressed. Encrypt Screen Opened.");
// Frame f = new Frame();
// f.setVisible(true);
// f.setSize(100, 100);
mode = Modes.Encrypt;
new EncryptionSubtask();
}
if (x >= 500 && x <= 595 && y >= 50 && y <= 75) { // if statement for decrypt button bounds
log("Button Pressed. Decrypt Screen Opened.");
mode = Modes.Decrypt;
}
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
System.out.println("Key pressed = " + key);
if (key == 27) {
mode = Modes.Menu;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
public enum LogLevel {
Info, Warn
}
private static int width = 300;
private static int height = width / 16 * 9;
private static int scale = 3;
public Main() {
addWindowListener(this);
log("Initialising...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
this.start();
log("Setting title...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
this.setTitle("LOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOL");
log("Creating backbuffer for window...");
setSize(width * scale, height * scale);
backbuffer = new BufferedImage(640 * 3, 480 * 2, BufferedImage.TYPE_INT_RGB);
log("Buffering Image, standby...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
g2d = backbuffer.createGraphics();
File fileThis = new File(System.getProperty("java.class.path"));
File parentFile = fileThis.getAbsoluteFile().getParentFile(); // the
// project
// folder
log(parentFile.getAbsolutePath());
File resources = new File(parentFile.toString() + "/resources/");
log(resources.getAbsolutePath());
try {
background = ImageIO.read(new File(resources + "/guitar.jpg")); // CHANGE
// THIS
// IMAGE!
File tempFile = new File(resources + "/guitar.jpg");
log(tempFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
addKeyListener(this);
addMouseListener(this);
}
#Override
public void run() {
Thread t = Thread.currentThread();
while (t == thread) {
try {
// log("Running...");
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
repaint();
}
}
public void start() {
thread = new Thread(this);
thread.start();
}
public void stop() {
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public void update(Graphics g) {
g2d.setTransform(transform);
g2d.setPaint(Color.black);
g2d.fillRect(0, 0, getWidth(), getHeight());
switch (mode) {
case Menu:
g2d.drawImage(background, 0, 0, getWidth(), getHeight(), this);
g2d.setPaint(Color.blue);
g2d.fillRect(50, 50, 93, 25);
g2d.fillRect(500, 50, 95, 25);
g2d.setPaint(Color.red);
g2d.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g2d.drawString("Encrypt", 50, 70);
g2d.drawString("Decrypt", 500, 70);
break;
case Encrypt:
g2d.setPaint(Color.green);
g2d.drawString("Encrypt screen", 50, 70);
break;
case Decrypt:
g2d.setPaint(Color.green);
g2d.drawString("Decrypt Screen", 50, 70);
break;
}
paint(g);
}
public void log(String s) {
log(s, 0, 0);
}
public void log(String s, int i) {
log(s, i, 0);
}
public void log(String s, int i, int j) {
String logmsg = "";
for (int k = 0; k < i; k++) {
logmsg += " ";
}
if (j == 0) {
logmsg = "[Info]" + logmsg;
} else {
logmsg = "[Warn]" + logmsg;
}
System.out.println("[" + System.currentTimeMillis() + "]["
+ Thread.currentThread().getStackTrace()[1].toString() + "]" + logmsg + s);
}
public void paint(Graphics g) {
g.drawImage(backbuffer, 8, 31, this);
}
}
So that I can use it to be drawn to my frame etc.
Okay, you call the constructor of EncryptionSubtask in the mouseClicked method and you do nothing with it.
First of all, you need to assign it to a variable, like this:
EncryptionSubtask veryStrangeTask = new EncryptionSubtask();
Than have the local variable passcode as a class field like this:
public class EncryptionSubtask {
String passcode;
...
}
Now you can use this field in your "other" class with
veryStrangeTask.passcode;
Maybe an Observer?
You could create an interface which has a method to pass your passcode
public interface PasscodeNotify{
public void notifyPasscode(String passcode);
}
Then you modify EncryptionSubtask constructor to accept an instance of this class, this way:
public EncryptionSubtask(PasscodeNotify observer) {
...
if(observer != null)
observer.notifyPasscode(c1+c2+c3+c4+c5+c6+c7+c8);
}
And finally you make that your Main class implements another interface, the PasscodeNotify I just created, and implements the method to retrieve your passcode.
Does it serves your purpose?
Hope it helps!

command doesn't work in a canvas j2me program

i made a canvas J2ME program and i used key press and key code to complete the program! now i have a big problem with two screen commands!
I need to use the command labels "Ersal" and "Virayesh" as below code but the command code doesn't work! i could use the key Codes(-6) but then i don't have command labels in the screen.
So whats your solution?
can i just add two labels in the screen not command?!
or how can i active these command void!
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.*;
import com.sun.midp.io.j2me.comm.WAP;
import com.sun.midp.io.j2me.comm.SDA;
public class Demo extends MIDlet
{
Command ersal = new Command("Ersal", Command.STOP, 1);
Command virayesh = new Command("Virayesh", Command.SCREEN, 1);
private Canvas m_canvas = new DemoCanvas();
private Display m_disp;
int v = 0;
public static final int IME_NOTIFY = -6;
public static final int KEY_ASTERISK = 42;
public static final int KEY_HASH = 35;
String a;
int step = -1;
public Demo() {
// TODO Auto-generated constructor stub
m_disp = Display.getDisplay(this);
m_disp.setCurrent(m_canvas);
}
private class DemoCanvas extends Canvas implements CommandListener
{
private String info = "Barname Estelam\n*:Meno Aval\n\nYek dokme ` `ra\nfeshar dahid";
public DemoCanvas(){}
public void paint(Graphics g)
{
g.setColor(0xFFFFFF);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(0);
g.drawString(info, 0, 5, Graphics.LEFT|Graphics.TOP);
/*
if(step==-1){
step=0;
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
info = "1:moshakhasat\nkhodro \n2:estelam taghib \n3:etelaat malek \n4:estelam khalafi";
repaint();
}
*
*/
}
protected void keyPressed(int keyCode)
{
/*
if(IME_NOTIFY == keyCode){
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
}
*
*/
if(keyCode==42 || step==-1){
info="1:moshakhasat\nkhodro \n2:estelam taghib \n3:etelaat malek \n4:estelam khalafi";
step=0;
a="";
m_canvas.removeCommand(ersal);
m_canvas.removeCommand(virayesh);
//m_disp.setCurrent(m_canvas);
WAP.WAP_InputMethodContents("");
}
String content = WAP.GetT9String();
if(step==2){
step=3;
//tayid T9
m_canvas.addCommand(ersal);
m_canvas.addCommand(virayesh);
String n = WAP.GetT9String();
if(a.equals("11") && n.length()>7)
info = "moshakhasat\nkhodro\n\npelak:\n" + pelakSp(content);
if(a.equals("12") && n.length()>7)
info = "moshakhasat\nkhodro\n\nshomare shasi:\n" + content;
if(a.equals("13") && n.length()>7)
info = "moshakhasat\nkhodro\n\nshomare motor:\n" + content;
if(a.equals("21") && n.length()>7)
info = "estelam taghib\n\npelak:\n" + pelakSp(content);
if(a.equals("31") && n.length()>7)
info = "etelaat malek\n\npelak:\n" + pelakSp(content);
if(a.equals("41") && n.length()>7)
info = "estelam khalafi\n\npelak:\n" + pelakSp(content);
repaint();
}
if(step==1){
if(keyCode==49){
step=2;
a+="1";
//pelak
String c = info;
WAP.WAP_InputMethodContentsLength(8);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = WAP.GetT9String();
repaint();
}
if(keyCode==50 && a.equals("1")){
step=2;
a+="2";
//shomare shasi0-9
String c = info;
WAP.WAP_InputMethodContentsLength(14);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = com.sun.midp.io.j2me.comm.WAP.GetT9String();
}
repaint();
if(keyCode==51 && a.equals("1")){
step=2;
a+="3";
//shomare motor
String c = info;
WAP.WAP_InputMethodContentsLength(10);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = com.sun.midp.io.j2me.comm.WAP.GetT9String();
repaint();
}
}
if(step==0){
if(keyCode==49){
a="1";
info="*Moshakhasat\nkhodro*\n1:Pelak\n2:Shomare Shasi\n3:Shomare Motor";
step=1;
}
if(keyCode==50){
a="2";
info="*Estelam Taghib*\n1:Pelak";
step=1;
}
if(keyCode==51){
a="3";
info="*Moshakhast Malek*\n1:Pelak";
step=1;
}
if(keyCode==52){
a="4";
info="*Estelam Khalafi*\n1:Pelak";
step=1;
}
}
repaint();
}
public void commandAction(Command c, Displayable d) {
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
// throw new UnsupportedOperationException("Not supported yet.");
}
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
// TODO Auto-generated method stub
notifyDestroyed();
}
protected void pauseApp() {}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
public String pelakSp(String a){
//tafkike pelak
String m = a.substring(0, 2) + " " + a.substring(2, 3) + " " + a.substring(3, 6) + "-" + a.substring(6, 8);
return m;
}
}
Try
this.addCommand(...)
in your constructor
i got the problem!
i didn't used command listener for my canvas!
i add this and it solved:
m_canvas.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
}
});

How to set Borders graphics G JAVA

I just now trying to make a game where there are few borders on the map, which is being generated from a text document. The text document has 1s and 0s where ther is 1 it shows a wall. So how do I make it so the character stops infront of the wall
My Code:
MAIN CLASS:
public class JavaGame {
public static void main(String[] args) {
final Platno p = new Platno();
final JFrame okno = new JFrame("Test");
Mapa map = new Mapa();
okno.setResizable(false);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
okno.setSize(800, 600);
okno.setVisible(true);
map.nacti();
okno.add(p);
p.mapa = map;
okno.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int kod = e.getKeyCode();
if(kod == KeyEvent.VK_LEFT)
{
Platno.x -= 3;
p.repaint();
}
else if(kod == KeyEvent.VK_RIGHT)
{
Platno.x +=3;
p.repaint();
}
else if(kod == KeyEvent.VK_UP)
{
Platno.y -=3;
p.repaint();
}
else if(kod == KeyEvent.VK_DOWN)
{
Platno.y +=3;
p.repaint();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
/* Timer = new Timer(1, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
Platno.y -=3;
p.repaint();
}
}); */
}`
Map loader class:
public void nacti()
{
try (BufferedReader br = new BufferedReader(new FileReader("map1-1.txt")))
{
String radek;
int cisloRadku = 0;
while((radek = br.readLine()) != null)
{
for(int i = 0; i < radek.length(); i++)
{
char znak = radek.charAt(i);
int hodnota = Integer.parseInt(String.valueOf(znak));
pole[i][cisloRadku] = hodnota;
}
cisloRadku++;
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
public void vykresli(Graphics g)
{
try {
wall = ImageIO.read(ClassLoader.getSystemResource("Images/wall.gif"));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
for(int i = 0; i < pole[0].length; i++)
{
for(int j = 0; j < pole.length; j++)
{
if(pole[j][i] == 1)
{
g.setColor(Color.RED);
// g.fillRect(j*40, i*40, 40, 40);
g.drawImage(wall, j*40, i*40, null);
}
}
}
}`
and the Hero class:
public class Hero {
public int poziceX;
public int poziceY;
public static boolean upB = false;
public static boolean downB = false;
public static boolean rightB = false;
public static boolean leftB = false;
BufferedImage up;
BufferedImage down;
BufferedImage right;
BufferedImage left;
public Hero()
{
try {
up = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Up.png"));
down = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Down.png"));
right = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Right.png"));
left = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Left.png"));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
public void vykreslit(Graphics g)
{
if(upB == true)
{
g.drawImage(up, poziceX, poziceX, null);
}
else if(downB == true)
{
g.drawImage(down, poziceX, poziceX, null);
}
else if(leftB == true)
{
g.drawImage(left, poziceX, poziceX, null);
}
else if(rightB == true)
{
g.drawImage(right, poziceX, poziceX, null);
}
}`
Thanks for your help :)
You could calculate the 'future position' for a move, and test for collisions.
If a collision occur, dont'move, otherwise you're ok to move.
See if this logic can help you:
public boolean willCollide(int row, int col, Board map)
{
return map[row][col] == 1;
}
public void moveLeft(Hero hero, Board map)
{
//watch for index out of bounds!
int futureCol = hero.y - 1;
if (! willCollide(hero.row, futureCol)
hero.y = futureCol;
}

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