Java: white frames while painting canvas - java

public class Screen extends Canvas implements Runnable {
private static final int MAX_FPS = 60;
private static final int FPS_SAMPLE_SIZE = 6;
private boolean[] keysPressed = new boolean[256];
private ArrayList<Character> characters = new ArrayList<>();
private ArrayList<Character> ai = new ArrayList<>();
private Thread thread;
private BufferedImage bg;
//for testing putposes
private Player slime = new Player("Slime.png", 100, 100);
private Player bird = new Player("Bird.png", 250, 250);
private Player giant = new Player("Giant.png", 250, 500);
private Player swordsman = new Player("Swordsman.png", 500, 250);
//screen dimensions
private int height = ((Toolkit.getDefaultToolkit().getScreenSize().height-32)/5*4);
private int width = Toolkit.getDefaultToolkit().getScreenSize().width;
private long prevTick = -1;
private LinkedList<Long> frames = new LinkedList<>();
private int averageFPS;
private boolean running;
public Screen() {
setSize(width, height);
try {bg = ImageIO.read(new File("GUI Images/success.jpg"));}
catch (Exception e) {Utilities.showErrorMessage(this, e);}
characters.add(slime);
// ai.add(bird);
//ai.add(giant);
// ai.add(swordsman);
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {keysPressed[e.getKeyCode()] = true;}
public void keyReleased(KeyEvent e) {keysPressed[e.getKeyCode()] = false;}
public void keyTyped(KeyEvent e) {}
});
addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
});
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {}
});
setVisible(true);
start();
}
public void paint(Graphics g){
BufferStrategy bs = getBufferStrategy();
if(getBufferStrategy() == null){
createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
g.drawImage(bg,0,0,width,height, null);
g.drawString(String.valueOf(averageFPS), 0, 0);
for (Character character : ai){
character.setY(character.getY() + (int)(Math.random() * 10 - 5));
character.setX(character.getX() + (int)(Math.random() * 10 - 5));
}
for (Character character : ai) {g.drawImage(character.getImage(), character.getX(), character.getY(), null);}
for (Character character : characters) {g.drawImage(character.getImage(), character.getX(), character.getY(), null);}
g.dispose();
bs.show();
}
public void run() {
while (running) {
tick();
repaint();
}
}
public synchronized void start() {
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
try {thread.join();}
catch (InterruptedException e) {Utilities.showErrorMessage(this, e);}
}
public void tick() {
if (keysPressed[KeyEvent.VK_W] && (slime.getY() > 0)) {slime.setY(slime.getY() - 1);}
if (keysPressed[KeyEvent.VK_S] && (slime.getY() < height)) {slime.setY(slime.getY() + 1);}
if (keysPressed[KeyEvent.VK_A] && (slime.getY() > 0)) {slime.setX(slime.getX() - 1);}
if (keysPressed[KeyEvent.VK_D] && (slime.getY() < width)) {slime.setX(slime.getX() + 1);}
// System.out.println(slime.getX() + ", " + slime.getY());
long pastTime = System.currentTimeMillis() - prevTick;
prevTick = System.currentTimeMillis();
if (frames.size() == FPS_SAMPLE_SIZE) {
frames.remove();
}
frames.add(pastTime);
// Calculate average FPS
long sum = 0;
for (long frame : frames) {
sum += frame;
}
long averageFrame = sum / FPS_SAMPLE_SIZE;
averageFPS = (int)(1000 / averageFrame);
// Only if the time passed since the previous tick is less than one
// second divided by the number of maximum FPS allowed do we delay
// ourselves to give Time time to catch up to our rendering.
if (pastTime < 1000.0 / MAX_FPS) {
try {
Thread.sleep((1000 / MAX_FPS) - pastTime);
System.out.println(averageFPS);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
There's my code, essentially this is just test code for the screen to see if I can properly paint objects to the screen, but there's erratic white frames that keep getting painted. They don't seem to be caused by any sort of input in particular, they just happen seemingly randomly during frame refreshes. Any ideas as to what it might be?

Don't override paint and use a BufferStrategy within it. Painting is usually done on a need to do bases (AKA "passive" rendering). BufferStrategy is a "active" rendering approach, where you take control of the paint process and update the buffer directly, the two don't tend to play well together
Take the logic from the current paint method and place it within your game loop.
This will require you to remove your call to start within the constructor, as the component won't have been added to a valid native peer (a component which is displayed on the screen).
Instead, create an instance of Screen, add it to your frame and then call start, for example...
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestScreen {
public static void main(String[] args) {
new TestScreen();
}
public TestScreen() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Frame frame = new Frame("Testing");
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Screen screen = new Screen();
frame.add(screen);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
screen.start();
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
public class Screen extends Canvas implements Runnable {
private static final int MAX_FPS = 60;
private static final int FPS_SAMPLE_SIZE = 6;
private boolean[] keysPressed = new boolean[256];
private ArrayList<Character> characters = new ArrayList<>();
private ArrayList<Character> ai = new ArrayList<>();
private Thread thread;
private BufferedImage bg;
private long prevTick = -1;
private LinkedList<Long> frames = new LinkedList<>();
private int averageFPS;
private boolean running;
public Screen() {
try {
bg = ImageIO.read(new File("GUI Images/success.jpg"));
} catch (Exception e) {
e.printStackTrace();
}
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
keysPressed[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keysPressed[e.getKeyCode()] = false;
}
public void keyTyped(KeyEvent e) {
}
});
addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
});
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
}
});
}
#Override
public Dimension getPreferredSize() {
int height = ((Toolkit.getDefaultToolkit().getScreenSize().height - 32) / 5 * 4);
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
return new Dimension(width, height);
}
public void run() {
createBufferStrategy(3);
BufferStrategy bs = null;
while (running) {
bs = getBufferStrategy();
Graphics g = bs.getDrawGraphics();
g.drawImage(bg, 0, 0, getWidth(), getHeight(), null);
FontMetrics fm = g.getFontMetrics();
g.setColor(Color.RED);
g.drawString(String.valueOf(averageFPS), 0, fm.getAscent());
g.dispose();
bs.show();
tick();
}
}
public synchronized void start() {
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void tick() {
// if (keysPressed[KeyEvent.VK_W] && (slime.getY() > 0)) {
// slime.setY(slime.getY() - 1);
// }
// if (keysPressed[KeyEvent.VK_S] && (slime.getY() < height)) {
// slime.setY(slime.getY() + 1);
// }
// if (keysPressed[KeyEvent.VK_A] && (slime.getY() > 0)) {
// slime.setX(slime.getX() - 1);
// }
// if (keysPressed[KeyEvent.VK_D] && (slime.getY() < width)) {
// slime.setX(slime.getX() + 1);
// }
// // System.out.println(slime.getX() + ", " + slime.getY());
long pastTime = System.currentTimeMillis() - prevTick;
prevTick = System.currentTimeMillis();
if (frames.size() == FPS_SAMPLE_SIZE) {
frames.remove();
}
frames.add(pastTime);
// Calculate average FPS
long sum = 0;
for (long frame : frames) {
sum += frame;
}
long averageFrame = sum / FPS_SAMPLE_SIZE;
averageFPS = (int) (1000 / averageFrame);
// Only if the time passed since the previous tick is less than one
// second divided by the number of maximum FPS allowed do we delay
// ourselves to give Time time to catch up to our rendering.
if (pastTime < 1000.0 / MAX_FPS) {
try {
Thread.sleep((1000 / MAX_FPS) - pastTime);
System.out.println(averageFPS);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}

Related

Java Game - Not Painting until After Thread.sleep

I'm currently coding a game and I'm trying to have it where if you click on the first button on the front page, it shows a transition screen for 5 seconds, and then shows the game. Here is my code:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ForgottenMain extends JPanel implements KeyListener,MouseListener{
/**
*
*/
private static final int TIMER_DELAY = 35;
private static final long serialVersionUID = -4926251405849574401L;
public static BufferedImage attic,flashlight,player,killer,frontpage,transition;
public static boolean onFrontPage,up,down,left,right,inAttic,onTransition;
public static int px,py,kx,ky;
public static Thread th1,th2;
public static JFrame frame = new JFrame("Forgotten");
public static void main(String[] args){
onFrontPage = true;
px = 600;
py = 400;
ForgottenMain fm = new ForgottenMain();
frame.add(fm);
frame.setSize(1200,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.add(new ForgottenMain());
fm.repaint();
}
public ForgottenMain(){
init();
}
public void init(){
setSize(1200,800);
setVisible(true);
frame.addKeyListener(this);
frame.addMouseListener(this);
try{
player = ImageIO.read(new File("char.png"));
flashlight = ImageIO.read(new File("flashlightimage.png"));
attic = ImageIO.read(new File("attic.png"));
killer = ImageIO.read(new File("killer.png"));
frontpage = ImageIO.read(new File("frontpageoutline.png"));
transition = ImageIO.read(new File("transitionoutline.png"));
} catch (Exception e){
e.printStackTrace();
}
// Gameloop
new javax.swing.Timer(TIMER_DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
gameLoop();
}
}).start();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int fx = px - 1033;
int fy = py - 635;
kx = 500;
ky = 500;
// Removes the flickering of the images
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Resets the screen to make sure that it only shows the character once
g2.clearRect(0, 0, 1200, 800);
// Draws the background attic
if(inAttic == true){
System.out.println("Drawing attic");
g2.drawImage(attic,0,0,this);
}
if(onFrontPage == true){
g2.drawImage(frontpage, 0, 0, this);
}
// Draws the player
if(onFrontPage == false && onTransition == false){
g2.drawImage(player, px, py, this);
// Draws the Serial Killer
g2.drawImage(killer, kx, ky, this);
// Draws the flashlight
g2.drawImage(flashlight, fx, fy, this);
}
if(onTransition == true){
g2.drawImage(transition, 0, 0, this);
System.out.println("Drawing Transition");
try {
System.out.println("Sleeping for 5 Seconds");
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done sleeping.");
onTransition = false;
inAttic = true;
}
System.out.println(px + " " + py);
}
public void gameLoop(){
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("MouseLocation: " + arg0.getX() + ", " + arg0.getY());
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
if(e.getX() > 499 && e.getY() > 343 && e.getX() < 748 && e.getY() < 391){
onFrontPage = false;
onTransition = true;
repaint();
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
My problem is, in the paint method, in the if statement testing if onTransition is equal to true, it's supposed to draw the image transition, wait 5 seconds, and then draw the game.
However, right now it's waiting 5 seconds, then quickly drawing the transition screen and then the game. For some reason they are out of order.
How can I fix this? I have tried alternate methods of waiting 5 seconds, for example using currentTimeMillis();, but have the same outcome.
You have some serious problems:
you add panels twice
you have some circuitous use of frame etc
Beyond that the following will work: you have to realize that you don't have control of the painting process. Therefore you should launch a new thread to count the sleep and let the paint do its work uninhibited.
(Also I have removed static - if you really want them you can try to put them back in - if it doesnt work you just throw them out)
class F extends JPanel implements MouseListener{
/**
*
*/
private static final int TIMER_DELAY = 35;
private static final long serialVersionUID = -4926251405849574401L;
public BufferedImage attic,flashlight,player,killer,frontpage,transition;
public boolean onFrontPage,up,down,left,right,inAttic,onTransition;
public int px,py,kx,ky;
public static Thread th1,th2;
public JFrame frame = new JFrame("Forgotten");
public F(){
init();
}
public void init(){
setSize(1200,800);
setVisible(true);
onFrontPage = true;
px = 600;
py = 400;
frame.add(this);
frame.setSize(1200,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.addMouseListener(this);
try{
// player = ImageIO.read(new File("char.png"));
// flashlight = ImageIO.read(new File("flashlightimage.png"));
// attic = ImageIO.read(new File("attic.png"));
// killer = ImageIO.read(new File("killer.png"));
attic = ImageIO.read(new File(...));
frontpage = ImageIO.read(new File(...));
transition = ImageIO.read(new File(...));
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int fx = px - 1033;
int fy = py - 635;
kx = 500;
ky = 500;
// Removes the flickering of the images
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Resets the screen to make sure that it only shows the character once
g2.clearRect(0, 0, 1200, 800);
// Draws the background attic
if(inAttic == true){
System.out.println("Drawing attic"+System.currentTimeMillis());
g2.drawImage(attic,0,0,this);
}
if(onFrontPage == true){
g2.drawImage(frontpage, 0, 0, this);
}
// Draws the player
if(onFrontPage == false && onTransition == false){
g2.drawImage(player, px, py, this);
// Draws the Serial Killer
g2.drawImage(killer, kx, ky, this);
// Draws the flashlight
g2.drawImage(flashlight, fx, fy, this);
}
if(onTransition == true){
Graphics gt=transition.getGraphics();
gt.setColor(Color.red);
gt.drawString("xxx"+System.currentTimeMillis(), 10, 100);
g2.drawImage(transition, 0, 0, this);
onTransition = false;
inAttic = true;
}
System.out.println(px + " " + py);
}
public void gameLoop(){
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("MouseLocation: " + arg0.getX() + ", " + arg0.getY());
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
onFrontPage = false;
onTransition = true;
Thread th=new Thread() {
public void run() {
repaint();
System.out.println("Drawing Transition"+System.currentTimeMillis());
try {
System.out.println("Sleeping for 5 Seconds"+System.currentTimeMillis());
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done sleeping."+System.currentTimeMillis());
repaint();
}
};
th.start();
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}

2D AI Fighting game, I need threads so that the human player and AI can both move at once

//This is the human class
//I have added runnable method to make it work but the AI is not moving.
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.awt.Color;
public class Human implements Runnable{
private double position=100000;
private double xa=0;
private int attack=0;
private Game game;
private long time;
private long lastTime;
private long MIN_DELAY;
private int health;
private int combo;
private Random r;
Thread thread;
public void start(){
thread = new Thread (this);
thread.start();
public void stop(){
thread.stop();
}
public void run1(){
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true)
{
game.move();
if (Game.() < 0){
}
try
{
Thread.sleep (10);
}
catch (InterruptedException ex)
{
break;
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
public Human(Game game){
this.game = game;
MIN_DELAY = 150;
lastTime=0;
health=100;
combo=0;
r = new Random();
}
public Human getPlayer(){
return this;
}
public double getPosition(){
return position;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT){
xa = -1;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
xa = 1;
}
if(e.getKeyCode()== KeyEvent.VK_Z){
attack = 1;
}
if(e.getKeyCode()== KeyEvent.VK_X){
attack = 2;
}
if(e.getKeyCode()== KeyEvent.VK_C){
attack = 3;
}
}
public String printHealth(){
String st = "Human Health: ";
st = st + Integer.toString(health);
return st;
}
public String printCombo(){
String st = "Combo: ";
st = st + Integer.toString(combo);
return st;
}
public boolean isAlive(){
if(health>0){
return true;
}else{
return false;
}
}
public int attack(){
int dam = 0;
time = System.currentTimeMillis();
if(time-lastTime>MIN_DELAY){
System.out.println("COMBO" + combo);
if(combo<3){
if(attack==1){
System.out.println("Human Punch");
dam = r.nextInt(6-1)+1;;
combo++;
}else if(attack==2){
System.out.println("Human Kick");
dam = r.nextInt(11-5)+5;
combo++;
}else if(attack==3){
System.out.println("Human Uppercut");
dam = r.nextInt(16-10)+10;
combo++;
}
}else{
if(attack == 1){
System.out.println(" SUPER Human PUNCH");
dam = r.nextInt(11-1)+1;
combo = 0;
}else if(attack ==2){
System.out.println(" SUPER Human KICK");
dam = r.nextInt(21-10)+10;
combo = 0;
}else if(attack == 3){
System.out.println(" SUPER Human UPPERCUT");
dam = r.nextInt(31-20)+20;
combo = 0;
}
}
}
lastTime = time;
return dam;
}
public void keyReleased(KeyEvent e) {
xa = 0;
attack = 0;
}
public int getAttack(){
return attack;
}
public void paint(Graphics2D g) {
g.fillRect(position-30, 200, 30, 30);
}
public void move(double opp) {
//if(time-lastTime>mDelay){
if (position + xa > 30 && position + xa < opp-17000)
position = position + xa/500;
//}
}
public int getHealth(){
return health;
}
public void takeHealth(int dam){
health = health - dam;
combo = 0;
}
// private Thread t;
public void run() {
try {
move(game.getAIPosition());
// Let the thread sleep for a while.
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Human Thread interrupted.");
}
System.out.println("Human Thread exiting.");
}
/*public void start ()
{
System.out.println("Starting Human" );
if (t == null)
{
t = new Thread (this);
t.start ();
}
}*/``
// This is the game class
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel{
public Human human = new Human(this);
public AIPlayer ai = new AIPlayer(this);
public Game(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
init();
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
human.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
human.keyPressed(e);
}
});
setFocusable(true);
}
double x=ai.getPosition();
int z=75; //Enemy Position
int y = 200;
public void move(){
human.move(ai.getPosition());
ai.move((ai.getPosition()-human.getPosition()), human.getHealth(), human.getPosition()); //CAN'T GET THIS TO WORK WITH HUMAN MOVING
System.out.println("Human position: " + human.getPosition());
System.out.println("AI Position: " + ai.getPosition());
System.out.println("Range: " + (ai.getPosition()-human.getPosition()));
}
public void makeSound(){
Random r = new Random();
int x = r.nextInt(10);
if(x==5 || x==6){
ai.makeSound(human.getHealth());
}
}
public double getAIPosition(){
return ai.getPosition();
}
public double getHumanPosition(){
return human.getPosition();
}
public int getHumanHealth(){
return human.getHealth();
}
public double getDistance(){
return (ai.getPosition()-human.getPosition());
}
public void attack(){
int hDec = human.getAttack();
System.out.println("Human Decision: " + hDec);
if(checkDistance(hDec)){
ai.takeHealth(human.attack());
}
human.takeHealth(ai.attack(ai.getPosition()-human.getPosition()));
ai.attack(ai.getPosition()-human.getPosition());
}
public boolean checkDistance(int mve){
double dist = ai.getPosition() - human.getPosition();
if(mve==1 && dist<=25364){
return true;
}else if(mve ==2 && dist<=29040){
return true;
}else if(mve==3 && dist<=20536){
return true;
}else{
return false;
}
}
public void decreaseAnger(){
ai.decreaseAnger();
}
public boolean gameAlive(){
if(ai.isAlive()&&human.isAlive()){
return true;
}else{
return false;
}
}
public void displayDetails(Graphics g){
Font myFont = new Font("Courier New", 1, 17);
g.setColor(Color.YELLOW);
g.setFont(myFont);
g.drawString(human.printHealth(), 10,15);
g.drawString(human.printCombo(), 10, 30);
g.drawString(ai.printHealth(), 550,15);
g.drawString(ai.printCombo(), 550, 30);
g.drawString(ai.printAnger(), 550, 45);
}
public static void main(String[] args) throws Exception {
TODO Auto-generated method stub
JFrame frame = new JFrame("Mini Tekken");
Game game = new Game();
frame.add(game);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (game.gameAlive()) {
game.move();
game.attack();
game.decreaseAnger();
game.repaint();
game.makeSound();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
Game game = new Game();
JFrame window = new JFrame("Mini-Tekken");
window.setContentPane(game);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
while(game.gameAlive()){
game.move();
game.attack();
game.decreaseAnger();
game.makeSound();
game.repaint();
}
}
//Dimensions
public static final int WIDTH = 736;
public static final int HEIGHT = 309;
BufferedImage background;
BufferedImage playerOne;
BufferedImage playerTwo;
public void paintComponent(Graphics g){
super.paintComponent(g);
if (background != null) {
g.drawImage(background, 0, 0, null);
}
if(playerOne != null){
g.drawImage(playerOne, ((int)human.getPosition()/500), 200, null);
}
if(playerTwo != null){
g.drawImage(playerTwo, ((int)ai.getPosition()/500), 210, null);
}
displayDetails(g);
}
private void init() {
try {
background = ImageIO.read(getClass().getResourceAsStream("/images/background.jpg"));
playerOne = ImageIO.read(getClass().getResourceAsStream("/images/p1.fw.png"));
playerTwo = ImageIO.read(getClass().getResourceAsStream("/images/p2.fw.png"));
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Trouble with mouseDragged and multiple objects

We are playing around with mouseDragged and multipleObjects.
We are trying to create a board game that has 8 pieces that can be individually clicked and dragged to their respective location on the board (without using jpanel, jframe, etc). As of now we have created 8 individual pieces for the board game, however when you go to click/drag piece '2', it causes all of the pieces to come together under the top piece.
Our initial solution (not shown) is to use a button to cycle between players pieces, but we would like to try to do this without the use of a button. Any suggestions are welcome.
Board:
import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.net.MalformedURLException;
import java.net.URL;
public class GameBoard extends Applet implements ActionListener,
MouseListener, MouseMotionListener
{
GamePiece gp1;
GamePiece gp2;
GamePiece gp3;
GamePiece gp4;
GamePiece gp5;
GamePiece gp6;
GamePiece gp7;
GamePiece gp8;
Image bg;
int xposR;
int yposR;
#Override
public void init()
{
System.out.println(getCodeBase().getPath().toString());
MediaTracker tracker = new MediaTracker(this);
try
{
bg = getImage(new URL("file:/C:/Backdroptest.png"));
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
tracker.addImage(bg, 0);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(d);
gp1 = new GamePiece(0, 0, "blue");
gp2 = new GamePiece(40, 0, "red");
gp3 = new GamePiece(80, 0, "yellow");
gp4 = new GamePiece(120, 0, "green");
gp5 = new GamePiece(160, 0, "orange");
gp6 = new GamePiece(200, 0, "cyan");
gp7 = new GamePiece(240, 0, "gray");
gp8 = new GamePiece(280, 0, "magenta");
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void paint(Graphics g)
{
g.drawImage(bg, 0, 0, this);
gp1.display(g);
gp2.display(g);
gp3.display(g);
gp4.display(g);
gp5.display(g);
gp6.display(g);
gp7.display(g);
gp8.display(g);
}
#Override
public void actionPerformed(ActionEvent ev)
{
}
#Override
public void mousePressed(MouseEvent e)
{
}
#Override
public void mouseReleased(MouseEvent e)
{
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
#Override
public void mouseMoved(MouseEvent e)
{
}
#Override
public void mouseClicked(MouseEvent e)
{
}
#Override
public void mouseDragged(MouseEvent e)
{
gp1.setLocation(xposR, yposR);
gp2.setLocation(xposR, yposR);
xposR = e.getX();
yposR = e.getY();
repaint();
}
}
GamePieces
This part denotes the 8 individual pieces
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class GamePiece implements MouseListener, MouseMotionListener
{
int xpos;
int ypos;
int circleWidth = 30;
int circleHeight = 30;
Boolean mouseClick;
Color c;
public GamePiece(int x, int y, String cc)
{
xpos = x;
ypos = y;
mouseClick = true;
if (!mouseClick)
{
xpos = 50;
ypos = 50;
}
setColor(cc);
}
public void setLocation(int x, int y)
{
xpos = x;
ypos = y;
// mouseClick = true;
}
public void setColor(String s)
{
if (s.equals("blue"))
{
c = Color.blue;
}
else if (s.equals("red"))
{
c = Color.red;
}
else if (s.equals("yellow"))
{
c = Color.yellow;
}
else if (s.equals("green"))
{
c = Color.green;
}
else if (s.equals("orange"))
{
c = Color.orange;
}
else if (s.equals("cyan"))
{
c = Color.cyan;
}
else if (s.equals("gray"))
{
c = Color.gray;
}
else
c = Color.magenta;
}
public void display(Graphics g)
{
g.setColor(c);
g.fillOval(xpos, ypos, circleWidth, circleHeight);
}
#Override
public void mousePressed(MouseEvent e)
{
mouseClick = true;
}
#Override
public void mouseReleased(MouseEvent e)
{
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
#Override
public void mouseMoved(MouseEvent e)
{
}
#Override
public void mouseClicked(MouseEvent e)
{
}
#Override
public void mouseDragged(MouseEvent e)
{
if (mouseClick)
{
xpos = e.getX();
ypos = e.getY();
}
}
}

Repaint() not calling paint() in Java

Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now.
With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program.
Entire code is below:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
public class Reflexology1 extends JFrame{
private static final long serialVersionUID = -1295261024563143679L;
private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25);
private Timer moveBallTimer;
int _ballXpos, _ballYpos;
JButton button1, button2;
JButton movingButton;
JTextArea textArea1;
int buttonAClicked, buttonDClicked;
private long _openTime = 0;
private long _closeTime = 0;
JPanel thePanel = new JPanel();
JPanel thePlacebo = new JPanel();
final JFrame frame = new JFrame("Reflexology");
final JFrame frame2 = new JFrame("The Test");
JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can.");
public static void main(String[] args){
new Reflexology1();
}
public Reflexology1(){
frame.setSize(600, 475);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Reflexology 1.0");
frame.setResizable(false);
frame2.setSize(600, 475);
frame2.setLocationRelativeTo(null);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setTitle("Reflexology 1.0");
frame2.setResizable(false);
button1 = new JButton("Accept");
button2 = new JButton("Decline");
//movingButton = new JButton("Click Me");
ListenForAcceptButton lForAButton = new ListenForAcceptButton();
ListenForDeclineButton lForDButton = new ListenForDeclineButton();
button1.addActionListener(lForAButton);
button2.addActionListener(lForDButton);
//movingButton.addActionListener(lForMButton);
JTextArea textArea1 = new JTextArea(24, 50);
textArea1.setText("Tracking Events\n");
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
textArea1.setSize(15, 50);
textArea1.setEditable(false);
FileReader reader = null;
try {
reader = new FileReader("EULA.txt");
textArea1.read(reader, "EULA.txt");
} catch (IOException exception) {
System.err.println("Problem loading file");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
AdjustmentListener listener = new MyAdjustmentListener();
thePanel.add(scrollBar1);
thePanel.add(button1);
thePanel.add(button2);
frame.add(thePanel);
ListenForMouse lForMouse = new ListenForMouse();
thePlacebo.addMouseListener(lForMouse);
thePlacebo.add(label1);
frame2.add(thePlacebo);
ListenForWindow lForWindow = new ListenForWindow();
frame.addWindowListener(lForWindow);
frame2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();}
}
});
frame.setVisible(true);
moveBallTimer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveBall();
System.out.println("Timer started!");
repaint();
}
});
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(frame2.isVisible()){ moveBallTimer.start(); }
}
});
}
private class ListenForAcceptButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
Calendar ClCDateTime = Calendar.getInstance();
System.out.println(ClCDateTime.getTimeInMillis() - _openTime);
_closeTime = ClCDateTime.getTimeInMillis() - _openTime;
//frame.getContentPane().remove(thePanel);
//thePlacebo.addKeyListener(lForKeys);
//frame.getContentPane().add(thePlacebo);
//frame.repaint();
//moveBallTimer.start();
frame.setVisible(false);
frame2.setVisible(true);
frame2.revalidate();
frame2.repaint();
}
}
}
private class ListenForDeclineButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button2){
JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}
private class ListenForWindow implements WindowListener{
public void windowActivated(WindowEvent e) {
//textArea1.append("Window is active");
}
// if this.dispose() is called, this is called:
public void windowClosed(WindowEvent arg0) {
}
// When a window is closed from a menu, this is called:
public void windowClosing(WindowEvent arg0) {
}
// Called when the window is no longer the active window:
public void windowDeactivated(WindowEvent arg0) {
//textArea1.append("Window is NOT active");
}
// Window gone from minimized to normal state
public void windowDeiconified(WindowEvent arg0) {
//textArea1.append("Window is in normal state");
}
// Window has been minimized
public void windowIconified(WindowEvent arg0) {
//textArea1.append("Window is minimized");
}
// Called when the Window is originally created
public void windowOpened(WindowEvent arg0) {
//textArea1.append("Let there be Window!");
Calendar OlCDateTime = Calendar.getInstance();
_openTime = OlCDateTime.getTimeInMillis();
//System.out.println(_openTime);
}
}
private class MyAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent arg0) {
AdjustmentEvent scrollBar1;
//System.out.println(scrollBar1.getValue()));
}
}
public void paint(Graphics g) {
//super.paint(g);
frame2.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
System.out.println("Calling fill()");
}
protected void moveBall() {
//System.out.println("I'm in the moveBall() function!");
int width = getWidth();
int height = getHeight();
int min, max, randomX, randomY;
min =200;
max = -200;
randomX = min + (int)(Math.random() * ((max - min)+1));
randomY = min + (int)(Math.random() * ((max - min)+1));
//System.out.println(randomX + ", " + randomY);
Rectangle ballBounds = ball.getBounds();
//System.out.println(ballBounds.x + ", " + ballBounds.y);
if (ballBounds.x + randomX < 0) {
randomX = 200;
} else if (ballBounds.x + ballBounds.width + randomX > width) {
randomX = -200;
}
if (ballBounds.y + randomY < 0) {
randomY = 200;
} else if (ballBounds.y + ballBounds.height + randomY > height) {
randomY = -200;
}
ballBounds.x += randomX;
ballBounds.y += randomY;
_ballXpos = ballBounds.x;
_ballYpos = ballBounds.y;
ball.setFrame(ballBounds);
}
public void start() {
moveBallTimer.start();
}
public void stop() {
moveBallTimer.stop();
}
private class ListenForMouse implements MouseListener{
// Called when the mouse is clicked
public void mouseClicked(MouseEvent e) {
//System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n");
if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) {
System.out.println("TRUE");
}
System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos);
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
// System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos);
// Mouse over
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
// Mouse left the mouseover area:
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.
You should not paint directly on JFrame. JPanel or extension of JComponent should be used. For painting override paintComponent() rather than paint(). Don't forget to call super.paintComponent(g);.
Also, keep in mind that repaint() only schedules component update, it does not trigger immediate paint().
For more details see Performing Custom Painting and Painting in AWT and Swing.
For example you can apply the following changes. TestPanel will paint the ball.
class TestPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
}
}
Then, update thePlacebo panel:
JPanel thePlacebo = new TestPanel();
Add repaint in moveBall():
thePlacebo.repaint();
Here is an example based on original code:
package so;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.Random;
import javax.swing.*;
public class TestBall {
private static void createAndShowUI() {
final TestPanel panel = new TestPanel();
panel.validate();
JFrame frame = new JFrame("TestBall");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 300));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ActionListener timerAction = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.moveBall();
}
};
Timer timer = new Timer(1000, timerAction);
timer.setRepeats(true);
timer.start();
}
static class TestPanel extends JPanel {
public static int BALL_SIZE = 25;
private Ellipse2D ball = new Ellipse2D.Double(0, 0, BALL_SIZE,
BALL_SIZE);
Random rand = new Random();
public TestPanel() {
this.addMouseListener(new MouseAdapter() {
// Called when the mouse is clicked
public void mouseClicked(MouseEvent e) {
if (ball.contains(e.getPoint())) {
System.out.println("hit the ball");
}
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
}
public void moveBall() {
Rectangle ballBounds = ball.getBounds();
ball.setFrame(ballBounds);
ballBounds.x = rand.nextInt(getWidth() - BALL_SIZE + 1) + 1;
ballBounds.y = rand.nextInt(getHeight() - BALL_SIZE + 1) + 1;
ball.setFrame(ballBounds);
repaint();
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Why does this JDialog flicker in Win7 when modal?

In Windows 7, and Java 1.7 (or if 1.6, comment-out the two lines indicated), create a NetBeans/Eclipse project named "test" with two classes, Test and DroppableFrame, and paste this code into it. And then run it.
If you run with modal = true, it flickers. If you run with modal = false, it doesn't. What am I doing wrong?
// test.java
package test;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Test implements KeyListener, MouseListener
{
public Test(boolean m_modal)
{
Dimension prefSize;
Insets inset;
Font fontLabel, fontInput, fontButtons;
int buttonCenters, buttonBackoff, buttonWidth, buttonCount, thisButton, buttonTop;
String caption;
JLayeredPane m_pane;
JLabel m_lblBackground;
JScrollPane m_txtInputScroll;
int m_width, m_height, m_actual_width, m_actual_height;
boolean m_singleLineInput = true;
String m_caption = "Sample Modal Input";
m_width = 450;
m_height = m_singleLineInput ? /*single line*/180 : /*multi-line*/250;
m_frame = new DroppableFrame(false);
caption = m_caption;
m_frame.setTitle(caption);
// Compute the actual size we need for our window, so it's properly centered
m_frame.pack();
Insets fi = m_frame.getInsets();
m_actual_width = m_width + fi.left + fi.right;
m_actual_height = m_height + fi.top + fi.bottom;
m_frame.setSize(m_width + fi.left + fi.right,
m_height + fi.top + fi.bottom);
prefSize = new Dimension(m_width + fi.left + fi.right,
m_height + fi.top + fi.bottom);
m_frame.setMinimumSize(prefSize);
m_frame.setPreferredSize(prefSize);
m_frame.setMinimumSize(prefSize);
m_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
m_frame.setSize(m_width, m_height);
m_frame.setLocationRelativeTo(null); // Center window
m_frame.setLayout(null); // We handle all redraws
Container c = m_frame.getContentPane();
c.setBackground(Color.WHITE);
c.setForeground(Color.BLACK);
m_pane = new JLayeredPane();
m_pane.setLayout(null);
m_pane.setBounds(0, 0, m_width, m_height);
m_pane.setVisible(true);
m_pane.setBorder(BorderFactory.createEmptyBorder());
c.add(m_pane);
// Set the background image
m_lblBackground = new JLabel();
m_lblBackground.setBounds(0, 0, m_width, m_height);
m_lblBackground.setHorizontalAlignment(JLabel.LEFT);
m_lblBackground.setVerticalAlignment(JLabel.TOP);
m_lblBackground.setVisible(true);
m_lblBackground.setBackground(Color.WHITE);
m_pane.add(m_lblBackground);
m_pane.moveToFront(m_lblBackground);
// Create the fonts
fontLabel = new Font("Calibri", Font.BOLD, 20);
fontInput = new Font("Calibri", Font.BOLD, 14);
fontButtons = fontLabel;
// Create the visible label contents
JLabel m_lblLabel = new JLabel();
m_lblLabel.setBounds(15, 52, 423, 28);
m_lblLabel.setHorizontalAlignment(JLabel.LEFT);
m_lblLabel.setVerticalAlignment(JLabel.CENTER);
m_lblLabel.setFont(fontLabel);
m_lblLabel.setForeground(Color.BLUE);
m_lblLabel.setText("A sample input:");
m_lblLabel.setVisible(true);
m_pane.add(m_lblLabel);
m_pane.moveToFront(m_lblLabel);
// Create the input box
if (m_singleLineInput)
{ // It's a single-line input box
m_txtInputSingleLine = new JTextField();
m_txtInputSingleLine.setBounds(15, 85, 421, 25);
m_txtInputSingleLine.setFont(fontInput);
m_txtInputSingleLine.setText("Initial Value");
m_txtInputSingleLine.setVisible(true);
m_txtInputSingleLine.addKeyListener(this);
m_pane.add(m_txtInputSingleLine);
m_pane.moveToFront(m_txtInputSingleLine);
} else {
m_txtInput = new JTextArea();
m_txtInputScroll = new JScrollPane(m_txtInput);
m_txtInputScroll.setBounds(15, 83, 421, 100);
m_txtInputScroll.setAutoscrolls(true);
m_txtInputScroll.setVisible(true);
m_txtInput.setFont(fontInput);
m_txtInput.setLineWrap(true);
m_txtInput.setWrapStyleWord(true);
m_txtInput.setTabSize(2);
m_txtInput.setText("Initial Value");
m_txtInput.setVisible(true);
m_pane.add(m_txtInputScroll);
m_pane.moveToFront(m_txtInputScroll);
}
// Determine which buttons are specified
buttonCount = 0;
m_buttons = _CANCEL_BUTTON + _OKAY_BUTTON;
if ((m_buttons & _NEXT_BUTTON) != 0)
{
m_btnNext = new JButton("Next");
m_btnNext.setFont(fontButtons);
m_btnNext.addMouseListener(this);
inset = m_btnNext.getInsets();
inset.left = 3;
inset.right = 3;
m_btnNext.setMargin(inset);
m_pane.add(m_btnNext);
m_pane.moveToFront(m_btnNext);
++buttonCount;
}
if ((m_buttons & _CANCEL_BUTTON) != 0)
{
m_btnCancel = new JButton("Cancel");
m_btnCancel.setFont(fontButtons);
m_btnCancel.addMouseListener(this);
inset = m_btnCancel.getInsets();
inset.left = 3;
inset.right = 3;
m_btnCancel.setMargin(inset);
m_pane.add(m_btnCancel);
m_pane.moveToFront(m_btnCancel);
++buttonCount;
}
if ((m_buttons & _ACCEPT_BUTTON) != 0)
{
m_btnAccept = new JButton("Accept");
m_btnAccept.setFont(fontButtons);
m_btnAccept.addMouseListener(this);
inset = m_btnAccept.getInsets();
inset.left = 3;
inset.right = 3;
m_btnAccept.setMargin(inset);
m_pane.add(m_btnAccept);
m_pane.moveToFront(m_btnAccept);
++buttonCount;
}
if ((m_buttons & _OKAY_BUTTON) != 0)
{
m_btnOkay = new JButton("Okay");
m_btnOkay.setFont(fontButtons);
m_btnOkay.addMouseListener(this);
inset = m_btnOkay.getInsets();
inset.left = 3;
inset.right = 3;
m_btnOkay.setMargin(inset);
m_pane.add(m_btnOkay);
m_pane.moveToFront(m_btnOkay);
++buttonCount;
}
// Determine the coordinates for each button
buttonCenters = (m_width / (buttonCount + 1));
buttonWidth = (int)((double)buttonCenters * 0.80);
buttonBackoff = (m_width / (buttonCount + 2)) / 2;
// Position the buttons
thisButton = 1;
buttonTop = m_singleLineInput ? 130 : 200;
if (m_btnNext != null)
{ // Position and make visible this button
m_btnNext.setBounds( + (thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnNext.setVisible(true);
++thisButton;
}
if (m_btnCancel != null)
{ // Position and make visible this button
m_btnCancel.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnCancel.setVisible(true);
++thisButton;
}
if (m_btnAccept!= null)
{ // Position and make visible this button
m_btnAccept.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnAccept.setVisible(true);
++thisButton;
}
if (m_btnOkay != null)
{ // Position and make visible this button
m_btnOkay.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnOkay.setVisible(true);
++thisButton;
}
// The modal code causes some slow component rendering.
// Needs looked at to figure out why
if (m_modal)
{ // Make it a modal window
m_frame.setModal(m_width, m_height, fi, m_pane);
} else {
// Make it a non-modal window
m_frame.setVisible(true);
m_frame.forceWindowToHaveFocus();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
m_frame.dispose();
System.exit(0);
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args)
{
boolean modal = true;
Test t = new Test(modal);
}
private DroppableFrame m_frame;
private int m_buttons;
private JTextField m_txtInputSingleLine;
private JTextArea m_txtInput;
private JButton m_btnNext;
private JButton m_btnCancel;
private JButton m_btnAccept;
private JButton m_btnOkay;
public static final int _NEXT_BUTTON = 1;
public static final int _CANCEL_BUTTON = 2;
public static final int _ACCEPT_BUTTON = 4;
public static final int _OKAY_BUTTON = 8;
public static final int _NEXT_CANCEL = 3;
public static final int _ACCEPT_CANCEL = 6;
public static final int _OKAY_CANCEL = 10;
}
// DroppableFrame.java
package test;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.io.*;
import java.util.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.awt.event.ComponentListener;
import java.awt.event.InputEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.*;
public class DroppableFrame extends JFrame
implements DropTargetListener,
DragSourceListener,
DragGestureListener,
ComponentListener
{
public DroppableFrame(boolean isResizeable)
{
super("JFrame");
m_dragSource = DragSource.getDefaultDragSource();
m_dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
this.setDropTarget(new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this));
addComponentListener(this);
m_isResizeable = isResizeable;
m_modal = false;
setResizable(isResizeable);
}
/**
* Sets the frame to a modal state
* #param width
* #param height
*/
public void setModal(int width,
int height,
Insets fi,
JLayeredPane m_pan)
{
int i;
Component[] comps;
Component c;
Point p;
m_modal = true;
m_modalDialog = new Dialog((JFrame)null, getTitle(), true);
m_modalDialog.setLayout(null);
m_modalDialog.setResizable(m_isResizeable);
m_modalDialog.setSize(width + fi.left + fi.right, height + fi.top + (fi.bottom * 2));
m_modalDialog.setAlwaysOnTop(true);
m_modalDialog.setLocationRelativeTo(null);
if (m_pan != null)
{ // Add/copy the pane's components
comps = m_pan.getComponents();
if (comps != null)
for (i = 0; i < comps.length; i++)
{ // Add and reposition the component taking into account the insets
c = m_modalDialog.add(comps[i]);
p = c.getLocation();
c.setLocation(p.x + fi.left, p.y + fi.top + fi.bottom);
}
}
m_modalDialog.setVisible(true);
}
#Override
public void paint(Graphics g)
{
Dimension d = getSize();
Dimension m = getMaximumSize();
boolean resize = d.width > m.width || d.height > m.height;
d.width = Math.min(m.width, d.width);
d.height = Math.min(m.height, d.height);
if (resize)
{
Point p = getLocation();
setVisible(false);
setSize(d);
setLocation(p);
setVisible(true);
}
super.paint(g);
}
#Override
public void dragDropEnd(DragSourceDropEvent DragSourceDropEvent){}
#Override
public void dragEnter(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dragExit(DragSourceEvent DragSourceEvent){}
#Override
public void dragOver(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dropActionChanged(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dragEnter (DropTargetDragEvent dropTargetDragEvent)
{
dropTargetDragEvent.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
#Override
public void dragExit (DropTargetEvent dropTargetEvent) {}
#Override
public void dragOver (DropTargetDragEvent dropTargetDragEvent) {}
#Override
public void dropActionChanged (DropTargetDragEvent dropTargetDragEvent){}
#Override
public synchronized void drop(DropTargetDropEvent dropTargetDropEvent)
{
try
{
Transferable tr = dropTargetDropEvent.getTransferable();
if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
{
dropTargetDropEvent.acceptDrop (DnDConstants.ACTION_COPY_OR_MOVE);
java.util.List fileList = (java.util.List)tr.getTransferData(DataFlavor.javaFileListFlavor);
Iterator iterator = fileList.iterator();
while (iterator.hasNext())
{
File file = (File)iterator.next();
if (file.getName().toLowerCase().endsWith(".xml"))
{ // Do something with the file here
} else {
System.out.println("Ignored dropped file: " + file.getAbsolutePath());
}
}
dropTargetDropEvent.getDropTargetContext().dropComplete(true);
} else {
dropTargetDropEvent.rejectDrop();
}
} catch (IOException io) {
dropTargetDropEvent.rejectDrop();
} catch (UnsupportedFlavorException ufe) {
dropTargetDropEvent.rejectDrop();
}
}
#Override
public void dragGestureRecognized(DragGestureEvent dragGestureEvent)
{
}
public void setTranslucency(float opaquePercent)
{
try
{
if (System.getProperty("java.version").substring(0,3).compareTo("1.6") <= 0)
{ // Code for translucency works in 1.6, raises exception in 1.7
Class awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
Method mSetWindowOpacity;
mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
if (mSetWindowOpacity != null)
{
if (!m_modal)
mSetWindowOpacity.invoke(null, this, opaquePercent);
}
} else {
// If compiling in 1.6 or earlier, comment-out these next two lines
if (!m_modal)
setOpacity(opaquePercent);
}
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) {
} catch (ClassNotFoundException ex) {
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException ex) {
} catch (IllegalComponentStateException ex) {
} catch (Throwable t) {
} finally {
}
}
#Override
public void componentResized(ComponentEvent e)
{
Dimension d = getSize();
Dimension m = getMaximumSize();
boolean resize = d.width > m.width || d.height > m.height;
d.width = Math.min(m.width, d.width);
d.height = Math.min(m.height, d.height);
if (resize)
setSize(d);
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
#Override
public void dispose()
{
if (m_modal)
{
m_modalDialog.setVisible(false);
m_modalDialog = null;
}
super.dispose();
}
public void forceWindowToHaveFocus()
{
Rectangle bounds;
Insets insets;
Robot robot = null;
if (m_modal)
m_modalDialog.setVisible(true);
setVisible(true);
toFront();
bounds = getBounds();
insets = getInsets();
try {
robot = new Robot();
robot.mouseMove(bounds.x + bounds.width / 2, bounds.y + insets.top / 2);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (AWTException ex) {
}
}
protected DragSource m_dragSource;
protected boolean m_isResizeable;
protected boolean m_modal;
protected Dialog m_modalDialog;
}
Looks like you're adding Swing components to an AWT Dialog. This will definitely cause problems. Using JDialog seems to remove the flickering.

Categories

Resources