i have a problem with the DS Desktop Notify library
in this library, all of notify banners has left to right orientation
i want to change the direction of these notifies from LTR to RTL
(the icons most be in the right side of the banner, also title and message need to start from right side of the banner
how can i do this in this library?
https://i.imgur.com/uTlOpqs.png "screenshot"
i have tried using the "applyComponentOrientation" for the frame, but it's not working
private static class DesktopLayoutFrame extends JDialog {
Image bg;
boolean nativeTrans;
boolean finished=true;
boolean clicked=false;
public DesktopLayoutFrame() {
super((JFrame)null,"DesktopLayoutFrame");
setUndecorated(true);
nativeTrans=Utils.isTranslucencySupported();
setBackground(new Color(0,0,0,nativeTrans? 0:255));
setContentPane(new JComponent(){
#Override
public void paintComponent(Graphics g){
render((Graphics2D)g);
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt){
clicked=true;
}
});
setFocusableWindowState(false);
setAlwaysOnTop(true);
System.out.println("Desktop Notify Frame deployed.");
}
#Override
public void setVisible(boolean visible) {
boolean bool=isVisible();
if (visible) {
Rectangle screenSize = Utils.getScreenSize();
setBounds(screenSize.x+screenSize.width-310, screenSize.y,
305, screenSize.height-5);
if (!bool && !nativeTrans)
bg=Utils.getBackgroundCap(getBounds());
}
super.setVisible(visible);
}
/**
* Paints the window contents.
* #param rd a graphics2D object received from the original paint event.
*/
public void render(Graphics2D rd) {
Point p = getMousePosition();
finished = false;
int x = 0, y = getHeight();
long l = System.currentTimeMillis();
if (windows.isEmpty()) finished = true;
int cur = Cursor.DEFAULT_CURSOR;
if (!nativeTrans) rd.drawImage(bg, 0, 0, this);
for (int i = 0; i < windows.size(); i++) {
DesktopNotify window = windows.get(i);
if (window.isVisible()) {
y -= window.h;
if (window.popupStart == 0) {
window.popupStart = System.currentTimeMillis();
}
if (y > 0) {
boolean hover = false;
if (p != null) {
if (p.y > y && p.y < y + window.h) {
hover = true;
if (window.getAction() != null) {
cur = Cursor.HAND_CURSOR;
}
if (clicked) {
if (window.getAction() != null) {
final DesktopNotify w = window;
final long lf = l;
java.awt.EventQueue.invokeLater(new Runnable(){#Override public void run(){
w.getAction().actionPerformed(new ActionEvent(w, ActionEvent.ACTION_PERFORMED, "fireAction", lf, 0));
}});
}
if (window.expTime() == Long.MAX_VALUE) {
window.timeOut = l - window.popupStart + 500;
}
}
}
}
window.render(x, y, hover, rd, l);
if (window.markedForHide) {
window.timeOut = l - window.popupStart + 500;
window.markedForHide = false;
}
} else {
window.popupStart = l;
}
if (l > window.expTime() || (y <= 0 && window.markedForHide)) {
window.markedForHide = false;
window.setVisible(false);
windows.remove(window);
i--;
}
y -= 5;
}
}
clicked = false;
setCursor(new Cursor(cur));
}
}
i think above code in "DesktopNotifyDriver.java" has to be edited for this. sorry for my english
Please Help Me Through This
Related
I'm working on a snake game, and I'm trying to make the snake move to the right. The issue here is the snake isn't actually moving, it just seems to copy itself to the right and also it's not going to the right automatically you have to keep pressing the key.
I am really not sure what the issue is, I made some code without any images. That should make the code run able for testing as it is.
public class Game{
static Graphics g;
public static void main(String[] args) {
JFrame b = new JFrame("Snake");
b.setBounds(300,60,905,700);
b.setBackground(Color.DARK_GRAY);
b.setResizable(false);
Snake snake = new Snake();
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.add(snake);
b.setVisible(true);
}
}
public class Snake extends JPanel implements KeyListener,ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private int[] snakeXlength = new int [750];
private int[] snakeYlength = new int [750];
private boolean right = true;
private boolean left = false;
private boolean up = false;
private boolean down = false;
private ImageIcon rightmouth;
private ImageIcon snakeimage;
private ImageIcon leftmouth;
private ImageIcon downmouth;
private ImageIcon upmouth;
private ImageIcon enemy;
private Timer timer;
private int snakeDelay = 100;
private int moves = 1;
private int lengtOfSnake = 3;
public Snake(){
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(snakeDelay, this);
timer.start();
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.drawRect (20, 24, 851, 612);
g.setColor(Color.BLACK);
g.fillRect (21, 25, 850, 610);
if (moves == 0) {
snakeXlength[2]= 63;
snakeXlength[1]= 83;
snakeXlength[0]= 100;
snakeYlength[2]= 100;
snakeYlength[1]= 100;
snakeYlength[0]= 98;
rightmouth = new ImageIcon("rightmouth.png");
rightmouth.paintIcon(this, g, snakeXlength[0], snakeYlength[0]);
}
for(int a = 0; a < lengtOfSnake; a++) {
if (a == 0 && right) {
if (a == 0 && right) {
g.setColor(Color.RED);
g.drawRect(5,10,snakeXlength[a],snakeYlength[a]);
g.fillRect (snakeXlength[a],snakeYlength[a],21,21);
g.drawRect(5,10,snakeXlength[a],snakeYlength[a]);
// rightmouth = new ImageIcon("rightmouth.png");
//rightmouth.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
if (a == 0 && left) {
leftmouth = new ImageIcon("leftmouth.png");
leftmouth.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
if (a == 0 && down) {
downmouth = new ImageIcon("downmouth.png");
downmouth.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
if (a == 0 && up) {
upmouth = new ImageIcon("uptmouth.png");
upmouth.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
if (a != 0) {
g.setColor(Color.GREEN);
g.fillOval(snakeXlength[a],snakeYlength[a],17,17);
//snakeimage = new ImageIcon("snakeimage.png");
//snakeimage.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
}
g.dispose();
}
public void keyPressed(KeyEvent e) {
timer.start();
if(right) {
for (int r = lengtOfSnake-1; r >= 0;r--) {
snakeYlength[r+1] = snakeYlength[r];
}
for(int r = lengtOfSnake;r >=0;r--) {
if(r==0) {
snakeXlength[r] = snakeXlength[r] +25;
}
else {
snakeXlength[r] = snakeXlength[r-1];
}
if(snakeXlength[r] > 850){
snakeXlength[r] = 25;
}
}
repaint();
}
if(left) {
}
if(up) {
}
if(down) {
}
}
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
moves++;
right = true;
if(left != true) {
right = true;
}
else
{
right = false;
left = true;
}
down = false;
up = false;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
moves++;
left = true;
if(right != true) {
left = true;
}
else
{
left = false;
right = true;
}
down = false;
up = false;
} if(e.getKeyCode() == KeyEvent.VK_UP) {
moves++;
up = true;
if(down != true) {
up = true;
}
else
{
up = false;
down = true;
}
left = false;
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
moves++;
down = true;
if(up != true) {
down = true;
}
else
{
up = true;
down = false;
}
left = false;
right = false;
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
it just seems to copy itself to the right
public void paint(Graphics g)
{
g.setColor(Color.WHITE);
Custom painting should be done by overriding paintComponent(...) and then you need to invoke super.paintComponent(...):
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.WHITE);
This will make sure the background of the panel is cleared before doing the custom painting.
it's not going to the right automatically you have to keep pressing the key.
Well, that is usually the way a game is designed. You only have motion when the key is pressed as this will keep generating events. Then if you don't want motion you just don't press any keys.
If you want animation then you use a Swing Timer. Each time the Timer fires you invoke a move(...) method. This method would need to look at your "direction" variable to determine whether to move the snake left, right, up or down.
Check out:
Motion Using the Keyboard for animation when a key is pressed and held and
get width and height of JPanel outside of the class for continuous animation
I have been working on a snake game, but an improvement I wanted to make was adding text to the game, giving instructions and keeping track of points. I messed around with JPanel and a few other things that all open a new, mini window that displays the text rather than printing it on the primary window
EDIT:
Thanks to several helpful people, I understand the correct use, but when I use it while attempting to change the color, it changes the color of the background as well. I was under the assumption this is because it's in the same class as the background, so when I put g.setColor under the background's color, it changed it.
I tried making a new object using paintComponent() while the background was in paint(), and the text didn't show up.
Any advice?
Here is the main java file:
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
public class Gamepanel extends JPanel implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500, HEIGHT = 500; //window size
private Thread thread;
private boolean running; //allows the game to be started/stopped
private boolean right = true, left = false, up = false, down = false; //setting default movement
private BodyPart b;
private ArrayList<BodyPart> snake;
private Food food;
private ArrayList<Food> foods;
private Random r; //creating random integer for food spawn
private int xCoor = 10, yCoor = 10, size = 5; //setting location and coordinate size, along with snake length
private int ticks = 0;
private int points = 0;
public Gamepanel() {
setFocusable(true);
setPreferredSize(new Dimension(WIDTH, HEIGHT)); //window size
addKeyListener(this); //allows key input from user
snake = new ArrayList <BodyPart>();
foods = new ArrayList <Food>();
r = new Random(); //random integer
}
public void start() {
running = true; //allows the game to start
thread = new Thread(this);
thread.start();
}
public void stop() {
running = false; //stops the game from running
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void tick() {
if(snake.size() == 0) { //sets location
b = new BodyPart(xCoor, yCoor, 10);
snake.add(b);
}
ticks++; //constant tick increase
if(ticks > 750000) { //sets speed (higher = slower)
if(right) xCoor ++;
if(left) xCoor --;
if(up) yCoor --;
if(down) yCoor ++;
ticks = 0;
b = new BodyPart(xCoor, yCoor, 10);
snake.add(b);
if(snake.size() > size) {
snake.remove(0); //removes earliest value in snake size
}
}
if(foods.size() == 0) { //sets food in window range(multiplies by 10)
int xCoor = r.nextInt(48);
int yCoor = r.nextInt(48);
points++;
food = new Food(xCoor, yCoor, 10);
foods.add(food);
}
for (int i = 0 ; i < foods.size(); i++) { //spawns new food when old food is eaten
if(xCoor == foods.get(i).getxCoor() && yCoor == foods.get(i).getyCoor()) {
size ++;
foods.remove(i);
i++;
}
}
//player body collision
for(int i = 0 ; i < snake.size(); i++) {
if(xCoor == snake.get(i).getxCoor() && yCoor == snake.get(i).getyCoor()) {
if(i != snake.size() - 1) {
System.out.print("Game Over! " + "Points: " + points);
stop();
}
}
}
//border collision
if(xCoor < 0 || xCoor > 49 || yCoor < 0 || yCoor > 49) {
System.out.println("Game Over! " + "Points: " + points);
stop();
}
}
public void paint(Graphics g) { //background color/size setter
g.clearRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK); //background color
g.fillRect(0, 0, WIDTH, HEIGHT);
for(int i = 0; i < WIDTH/10 ; i++) {
g.drawLine(i * 10, 0, i * 10, HEIGHT);
}
for(int i = 0; i < HEIGHT/10 ; i++) {
g.drawLine(0, i * 10, HEIGHT, i * 10);
}
for(int i = 0 ; i < snake.size(); i++) {
snake.get(i).draw(g);
}
for(int i = 0 ; i < foods.size(); i++) {
foods.get(i).draw(g);
}
}
#Override
public void run() {
while(running) {
tick(); //runs ticks while running is true
repaint();
}
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT && !left) { //right key = right movement
right = true;
up = false;
down = false;
}
if(key == KeyEvent.VK_LEFT && !right) { //left key = left movement
left = true;
up = false;
down = false;
}
if(key == KeyEvent.VK_UP && !down) { //up key = up movement
up = true;
right = false;
left = false;
}
if(key == KeyEvent.VK_DOWN && !up) { //down key = down movement
down = true;
right = false;
left = false;
}
if(key == KeyEvent.VK_SPACE) {
snake.clear();
start();
size = 5;
points = 0;
xCoor = 10;
yCoor = 10;
}
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
Did you try this ?
public void paintComponent(Graphics g) {
super.paintComponent(g);
Font font = new Font("Verdana", Font.BOLD, 14);
g.setFont(font);
g.setColor(Color.black);
g.drawString("instructions", 75, 75);
}
as noted by #Hovercraft maybe you should be overriding the paintComponent() method instead of paint()
Hi I made a pause menu for my game, and you navigate through it with the arrow keys on the keyboard. My question is how do I make it so I can navigate with my mouse, and click the buttons rather then having to use the arrow keys?
here is the code:
public class InGameMenu implements KeyListener {
private String[] string = { "Resume Game", "Options", "Save Game", "Load Game", "Exit Game" };
private String[] optionStrings = { "Help", "Back" };
public static int selected = 0;
private int space = 25;
public int width = 800;
public int height = 600;
public static boolean isInMenu = true;
public static boolean isInOptions = false;
public static boolean saving = false;
public static boolean loading = false;
public InGameMenu() {
}
public void tick() {
}
public void render(Graphics g) {
g.setColor(new Color(0, 0, 0, 90));
g.fillRect(0, 0, Component.width, Component.height);
if (isInMenu) {
g.setColor(Color.LIGHT_GRAY);
if (saving) {
g.drawString("Saving", Component.width / 2 / Component.pixelSize - (int) (Component.width / 25), 35);
}
if (loading) {
g.drawString("Loading", Component.width / 2 / Component.pixelSize - (int) (Component.width / 25), 35);
}
for (int i = 0; i < string.length; i++) {
if (selected == i) {
g.setColor(Color.RED);
} else {
g.setColor(Color.WHITE);
}
g.drawString(string[i], Component.width / 2 / Component.pixelSize - (int) (Component.width / 17.5), Component.height / 8 + (i * space));
}
} else if (isInOptions) {
for (int i = 0; i < optionStrings.length; i++) {
if (selected == i) {
g.setColor(Color.RED);
} else {
g.setColor(Color.WHITE);
}
g.drawString(optionStrings[i], Component.width / 2 / Component.pixelSize - (int) (Component.width / 17.5), Component.height / 8 + (i * space));
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (isInMenu) {
if (key == KeyEvent.VK_UP) {
selected--;
if (selected < 0) {
selected = string.length - 1;
}
}
if (key == KeyEvent.VK_DOWN) {
selected++;
if (selected > string.length - 1) {
selected = 0;
}
}
if (key == KeyEvent.VK_ENTER) {
if (selected == 0) {
Component.isInMenu = false;
} else if (selected == 1) {
isInMenu = false;
isInOptions = true;
selected = 0;
} else if (selected == 2) {
saving = true;
SaveLoad.save();
saving = false;
} else if (selected == 3) {
loading = true;
SaveLoad.load();
loading = false;
} else if (selected == 4) {
System.exit(0);
}
}
} else if (isInOptions) {
if (key == KeyEvent.VK_UP) {
selected--;
if (selected < 0) {
selected = optionStrings.length - 1;
}
}
if (key == KeyEvent.VK_DOWN) {
selected++;
if (selected > optionStrings.length - 1) {
selected = 0;
}
}
if (key == KeyEvent.VK_ENTER) {
if (selected == 0) {
System.out.println("HELP");
} else if (selected == 1) {
isInOptions = false;
isInMenu = true;
}
}
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
You can implement MouseListener too.
You can add these methods from MouseListener:
public void mousePressed(MouseEvent e) {
if(e.getSource() == button1)
{
isInMenu = false;
isInOptions = true;
selected = 0;
}
if(e.getSource() == button2)
{
saving = true;
SaveLoad.save();
saving = false;
}
if(e.getSource() == button3)
{
loading = true;
SaveLoad.load();
loading = false;
}
if(e.getSource() == button4)
{
System.exit(0);
}
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
First, you must get the bounds (x, y, width and height) of the text.
You already have the x and y:
g.drawString(string[i], Component.width / 2 / Component.pixelSize - (int) (Component.width / 17.5), Component.height / 8 + (i * space));
// x = Component.width / 2 / Component.pixelSize - (int) (Component.width / 17.5)
// y = Component.height / 8 + (i * space)
You can determine the width and height via Font#getStringBounds(String, FontRenderContext):
FontRenderContext renderContext = new FontRenderContext(null, true, true);
Font font = new Font("Arial", Font.PLAIN, 14);
String labelText = "Start";
Rectangle2D labelBounds = font.getStringBounds(labelText, renderContext);
int labelWidth = (int) labelBounds.getWidth();
int labelHeight = (int) labelBounds.getHeight();
The bounds is needed to determine if the mouse is hovering over the text when the click occurs.
Next, you must maintain the bounds for each menu item.
Right now, you're only maintaining the names in string and optionStrings. You'll need to maintain the x, y, width and height for every menu item.
Since every menu item each has their own name, size and position, it would be easier to create a new type composed of these properties:
public class Label {
private String name;
private Font font;
private int x, y;
private int width, height;
public Label(String name, Font font, int x, int y, int width, int height) {
this.name = name;
this.font = font;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
Instead of a String[], you could have a Label[]. Although it's preferrable to use List for it's higher-level functionality:
public class InGameMenu implements MouseListener {
private List<Label> labels;
public void mousePressed(MouseEvent event) {
int x = event.getX();
int y = event.getY();
labels.forEach(label -> {
// if (mouse hovering over label)
// ...
});
}
}
Then, you must determine if the mouse position is within the label's position.
The formula is pretty simple:
// checks if mouse intersects with label on X axis
intersectsHorizontally := mouseX > labelX && mouseX < labelX + labelWidth;
// checks if mouse intersects with label on Y axis
intersectsVertically := mouseY > labelY && mouseY < labelY + labelHeight;
// if both conditions above are true, mouse is hovering over label
The easiest way to implement this would be to give your Label objects a containsPoint(int x, int y) behavior:
public class Label {
private int x, y;
private int width, height;
//...
public boolean containsPoint(int pointX, int pointY) {
boolean containsHorizontally = pointX > x && pointX < x + width;
boolean containsVertically = pointY > y && pointY < y + height;
return containsHorizontally && containsVertically;
}
}
Now you can easily determine whether the mouse is hovering over a specific label:
public void mousePressed(MouseEvent event) {
int x = event.getX();
int y = event.getY();
labels.forEach(label -> {
if(label.containsPoint(x, y)) {
//...
}
});
}
Finally, you must determine which label was clicked
There are many ways to go about this. Instead of a List, you could maintain the labels independently and check each one:
public class InGameMenu implements MouseListener {
private Label startLabel;
private Label loadLabel;
public InGameMenu(Label startLabel, Label loadLabel) {
this.startLabel = startLabel;
this.loadLabel = loadLabel;
}
public void mousePressed(MouseEvent event) {
int x = event.getX();
int y = event.getY();
if(startLabel.containsPoint(x, y)) {
//start game
} else if(loadLabel.containsPoint(x, y)) {
//load game
}
}
}
But this isn't dynamic, as InGameMenu is forced to know about every label it has, and adding labels would be a pain.
A better approach is to create all the Label objects outside of InGameMenu, as the examples above have been doing:
FontRenderContext renderContext = ...;
Font font = ...;
// start label
String labelText = "Start";
Rectangle2D labelBounds = font.getStringBounds(labelText, renderContext);
int x = ...;
int y = ...;
int width = (int) labelBounds.getWidth();
int height = (int) labelBounds.getHeight();
Label label = new Label(labelText, font, labelX, labelY, labelWidth, labelHeight);
// list of all labels for menu
List<Label> labels = new ArrayList<>();
labels.add(label);
InGameMenu menu = new InGameMenu(labels);
Then have the label object tell us when it has been clicked. We can do this by giving Label a click() method for InGameMenu to trigger when the label has been clicked:
public class InGameMenu implements MouseListener {
private List<Label> labels;
public InGameMenu(List<Label> labels) {
this.labels = labels;
}
public void mousePressed(MouseEvent event) {
int x = event.getX();
int y = event.getY();
labels.forEach(label -> {
if(label.containsPoint(x, y))
label.click();
});
}
}
Then allowing Label to accept a callback function:
public class Label {
private String name;
private Font font;
private int x, y;
private int width, height;
private Runnable onClick;
public Label(String name, Font font, int x, int y, int width, int height, Runnable onClick) {
this.name = name;
this.font = font;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.onClick = onClick;
}
public void click() {
onClick.run();
}
//...
}
So when you create Label objects, you can give them actions that make use of outside data (maybe a GameStateManager or something):
Runnable onClick = () -> System.out.println("Start button was clicked!");
Label label = new Label("Start", ..., onClick);
This is my ScreenManager class which is used for getting the perfect DisplayMode & setting the screen to fullscreen
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
public class ScreenManager
{
private GraphicsDevice vc;
//give vc access to monitor screen
public ScreenManager()
{
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = e.getDefaultScreenDevice();
}
//get all compatible DM
public DisplayMode[] getCompatibleDisplayModes()
{
return vc.getDisplayModes();
}
//compares DM passed into vc DM & see if they match
public DisplayMode findFirstCompatibleMode(DisplayMode modes[])
{
DisplayMode goodModes[] = vc.getDisplayModes();
for ( int x = 0; x < modes.length; x++)
{
for( int y = 0; y < goodModes.length; y++)
{
if(displayModesMatch(modes[x], goodModes[y]))
{
return modes[x];
}
}
}
return null;
}
//get current DM
public DisplayMode getCurrentDisplayMode()
{
return vc.getDisplayMode();
}
//checks if two modes match each other
public boolean displayModesMatch(DisplayMode m1, DisplayMode m2)
{
if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight())
{
return false;
}
if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth())
{
return false;
}
if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate())
{
return false;
}
return true;
}
//make frame full screen
public void setFullScreen(DisplayMode dm)
{
JFrame f = new JFrame();
f.setUndecorated(true);
f.setIgnoreRepaint(true);
f.setResizable(true);
vc.setFullScreenWindow(f);
if( dm != null & vc.isDisplayChangeSupported())
{
try
{
vc.setDisplayMode(dm);
}
catch(Exception ex) { }
}
f.createBufferStrategy(2);
}
//we will set graphics object to this
public Graphics2D getGraphics()
{
Window w = vc.getFullScreenWindow();
if(w != null)
{
BufferStrategy s = w.getBufferStrategy();
return (Graphics2D)s.getDrawGraphics();
}
else
{
return null;
}
}
//update displaye
public void update()
{
Window w = vc.getFullScreenWindow();
if( w != null )
{
BufferStrategy s = w.getBufferStrategy();
if(!s.contentsLost())
{
s.show();
}
}
}
//return full screen window
public Window getFullScreenWindow()
{
return vc.getFullScreenWindow();
}
//get width of window
public int getWidth()
{
Window w = vc.getFullScreenWindow();
if( w != null)
{
return w.getWidth();
}
else
{
return 0;
}
}
//get height of window
public int getHeight()
{
Window w = vc.getFullScreenWindow();
if( w != null)
{
return w.getHeight();
}
else
{
return 0;
}
}
//get out of full screen
public void restoreScreen()
{
Window w =vc.getFullScreenWindow();
if( w != null)
{
w.dispose();
}
vc.setFullScreenWindow(null);
}
//create image compatible with your moitor
public BufferedImage createCompatibleImage(int w, int h, int t)
{
Window win = vc.getFullScreenWindow();
if( win != null)
{
GraphicsConfiguration gc = win.getGraphicsConfiguration();
return gc.createCompatibleImage(w, h, t);
}
else
{
return null;
}
}
}
This is the Core class which I used for initializing the screen, looping mechanism, etc.
import java.awt.*;
import javax.swing.*;
public abstract class Core
{
private static DisplayMode modes[] = {
new DisplayMode(800, 600, 32, 0),
new DisplayMode(800, 600, 24, 0),
new DisplayMode(800, 600, 16, 0),
new DisplayMode(640, 480, 32, 0),
new DisplayMode(640, 480, 24, 0),
new DisplayMode(640, 480, 16, 0),
};
private boolean running;
protected ScreenManager s;
//stop method
public void stop()
{
running = false;
}
//call inint & gameloop
public void run()
{
try
{
init();
gameloop();
}
finally
{
s.restoreScreen();
}
}
//set to full screen
public void init()
{
s = new ScreenManager();
DisplayMode dm = s.findFirstCompatibleMode(modes);
s.setFullScreen(dm);
Window w = s.getFullScreenWindow();
w.setFont(new Font("Arial", Font.PLAIN, 20));
w.setBackground(Color.GREEN);
w.setForeground(Color.WHITE);
running = true;
}
//main gameloop
public void gameloop()
{
long startTime = System.currentTimeMillis();
long cumTime = startTime;
while(running)
{
long timePassed = System.currentTimeMillis() - cumTime;
cumTime += timePassed;
update(timePassed);
Graphics2D g = s.getGraphics();
draw(g);
g.dispose();
s.update();
try
{
Thread.sleep(20);
}
catch(Exception ex) { }
}
}
//update animation
public void update(long timePassed) { }
//draws to the screen
public abstract void draw(Graphics2D g);
}
This is the actual Game class which I used for designing starting screen on window
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Game extends Core implements KeyListener, MouseListener
{
public static void main(String []args)
{
new Game().run();
}
private String mess = "";
private Image VRacer;
private String start = "Start", controls = "Controls", credits = "Credits", exit = "Exit";
private void loadPics()
{
VRacer = new ImageIcon("VRacers.png").getImage();
}
public void init()
{
super.init();
loadPics();
Window w = s.getFullScreenWindow();
w.setFocusTraversalKeysEnabled(false);
w.addKeyListener(this);
w.addMouseListener(this);
mess = "Press Esc to Close Application";
}
//draw
public synchronized void draw(Graphics2D g)
{
Window w = s.getFullScreenWindow();
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(Color.BLACK);
g.fillRect(0, 0, s.getWidth(), s.getHeight());
g.setColor(Color.YELLOW);
g2.drawString(mess, 30, 30);
g.drawImage(VRacer, 160, 50, null);
g2.drawString(start, 355, 200);
g2.drawString(controls, 340, 270);
g2.drawString(credits, 345, 340);
g2.drawString(exit, 360, 410);
}
//key pressed
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_ESCAPE)
{
stop();
}
else
{
mess = "Pressed : " + KeyEvent.getKeyText(keyCode);
e.consume();
}
}
//key pressed
public void keyTyped(KeyEvent e)
{
e.consume();
}
//key released
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
mess = "Released : " + KeyEvent.getKeyText(keyCode);
e.consume();
}
//Mouse pressed
public void mousePressed(MouseEvent e)
{
if( (e.getX() >= 355 && e.getX() <= 396) && (e.getY() >= 174 && e.getY() <= 200) )
{
mess = "Pressed : " + start + " & location : (" + e.getX() + ", " + e.getY() + ")";
}
if( (e.getX() >= 340 && e.getX() <= 410) && (e.getY() >= 244 && e.getY() <= 270) )
{
mess = "Pressed : " + controls + " & location : (" + e.getX() + ", " + e.getY() + ")";
}
if( (e.getX() >= 345 && e.getX() <= 407) && (e.getY() >= 314 && e.getY() <= 340) )
{
mess = "Pressed : " + credits + " & location : (" + e.getX() + ", " + e.getY() + ")";
}
if( (e.getX() >= 360 && e.getX() <= 390) && (e.getY() >= 384 && e.getY() <= 410) )
{
stop();
mess = "Pressed : " + exit + " & location : (" + e.getX() + ", " + e.getY() + ")";
}
}
//Mouse released
public void mouseReleased(MouseEvent e) { }
//Mouse clicked
public void mouseClicked(MouseEvent e) { }
//Mouse entered
public void mouseEntered(MouseEvent e) { }
//Mouse exited
public void mouseExited(MouseEvent e) { }
//
}
I have added some text on the screen & when mouse clicked in the region bounded by the text it gives the output.
But how can I clear the screen if I want to draw something new on the screen when I click Start, Controls, or Credits???
Such as remove everything like Start, Credits, Controls, Exit & the Image
So I can draw something new on that blank screen.
thnx for help in advance...
Despite I import the applet library, NetBeans cannot recognize and use getDocumentBase() in my code, I have my html file within my project and all other required files as well, here is a part of my code :
import java.awt.*;
import java.applet.*;
public class AirportCanvas extends Canvas
{
SingleLaneAirport controller;
Image redPlane;
Image bluePlane;
Image airport;
//AudioClip crashSound;
int[] redX,redY,blueX,blueY;
int maxCar = 2;
final static int initredX = 5;
final static int initredY = 55;
final static int initblueX = 410;
final static int initblueY = 130;
final static int bridgeY = 90;
boolean frozen = false;
int cycleTime = 20;
AirportCanvas(SingleLaneAirport controller)
{
super();
this.controller = controller;
// crashSound=controller.getAudioClip(controller.getDocumentBase(),"crash.au");
MediaTracker mt;
mt = new MediaTracker(this);
redPlane = controller.getImage(controller.getDocumentBase(), "redplane.png");
mt.addImage(redPlane, 0);
bluePlane = controller.getImage(controller.getDocumentBase(), "blueplane.png");
mt.addImage(bluePlane, 1);
airport = controller.getImage(controller.getDocumentBase(), "airport.png");
mt.addImage(airport, 2);
try
{
mt.waitForID(0);
mt.waitForID(1);
mt.waitForID(2);
}
catch (java.lang.InterruptedException e)
{
System.out.println("Couldn't load one of the images");
}
setSize(airport.getWidth(null),airport.getHeight(null));
init(1);
}
public final void init(int ncars)
{ //set number of cars
maxCar = ncars;
frozen = false;
redX = new int[maxCar];
redY = new int[maxCar];
blueX = new int[maxCar];
blueY = new int[maxCar];
for (int i = 0; i<maxCar ; i++)
{
redX[i] = initredX - i*85;
redY[i] = initredY;
blueX[i] =initblueX + i*85;
blueY[i] =initblueY;
}
repaint();
}
Image offscreen;
Dimension offscreensize;
Graphics offgraphics;
public void backdrop()
{
Dimension d = getSize();
if ((offscreen == null) || (d.width != offscreensize.width)
|| (d.height != offscreensize.height))
{
offscreen = createImage(d.width, d.height);
offscreensize = d;
offgraphics = offscreen.getGraphics();
offgraphics.setFont(new Font("Helvetica",Font.BOLD,36));
}
offgraphics.setColor(Color.lightGray);
offgraphics.drawImage(airport,0,0,this);
}
#Override
public void paint(Graphics g)
{
update(g);
}
#Override
public void update(Graphics g)
{
backdrop();
for (int i=0; i<maxCar; i++)
{
offgraphics.drawImage(redPlane,redX[i],redY[i],this);
offgraphics.drawImage(bluePlane,blueX[i],blueY[i],this);
}
if (blueY[0]==redY[0] && Math.abs(redX[0]+80 - blueX[0])<5)
{
offgraphics.setColor(Color.red);
offgraphics.drawString("Crunch!",200,100);
frozen=true;
// crashSound.play();
}
g.drawImage(offscreen, 0, 0, null);
}
//returns true for the period from just before until just after car on bridge
public boolean moveRed(int i) throws InterruptedException
{
int X = redX[i];
int Y = redY[i];
synchronized (this)
{
while (frozen )
wait();
if (i==0 || Math.abs(redX[i-1] - X) > 120)
{
X += 2;
if (X >=500)
{
X = -80; Y = initredY;
}
if (X >=60 && X < 290 && Y<bridgeY)
++Y;
if (X >=290 && Y>initredY)
--Y;
}
redX[i]=X;
redY[i]=Y;
repaint();
}
Thread.sleep(cycleTime);
return (X>25 && X<400);
}
//returns true for the period from just before until just after car on bridge
public boolean moveBlue(int i) throws InterruptedException
{
int X = blueX[i];
int Y = blueY[i];
synchronized (this)
{
while (frozen )
wait();
if (i==0 || Math.abs(blueX[i-1] - X) > 120)
{
X -= 2;
if (X <=-80)
{
X = 500; Y = initblueY;
}
if (X <=370 && X > 130 && Y>bridgeY)
--Y;
if (X <=130 && Y<initblueY)
++Y;
blueX[i]=X;
}
blueY[i]=Y;
repaint();
}
Thread.sleep(cycleTime);
repaint();
return (X>25 && X<400);
}
public synchronized void freeze()
{
frozen = true;
}
public synchronized void thaw()
{
frozen = false;
notifyAll();
}
}
Single Lane Airport Class :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class SingleLaneAirport {
AirportCanvas display;
Button restart;
Button freeze;
Button onecar;
Button twocar;
Button threecar;
Checkbox fair;
Checkbox safe;
boolean fixed = false;
int maxCar = 1;
Thread red[];
Thread blue[];
#Override
public void init()
{
setLayout(new BorderLayout());
display = new AirportCanvas(this);
add("Center",display);
restart = new Button("Restart");
restart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.thaw();
}
});
freeze = new Button("Freeze");
freeze.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.freeze();
}
});
onecar = new Button("One Car");
onecar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stop();
maxCar = 1;
start();
}
});
twocar = new Button("Two Cars");
twocar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stop();
maxCar = 2;
start();
}
});
threecar = new Button("Three Cars");
threecar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stop();
maxCar = 3;
start();
}
});
safe = new Checkbox("Safe",null,true);
safe.setBackground(Color.lightGray);
safe.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
stop();
start();
}
});
fair = new Checkbox("Fair",null,false);
fair.setBackground(Color.lightGray);
fair.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
stop();
start();
}
});
Panel p1 = new Panel();
p1.setLayout(new FlowLayout());
p1.add(freeze);
p1.add(restart);
p1.add(onecar);
p1.add(twocar);
p1.add(threecar);
p1.add(safe);
p1.add(fair);
add("South",p1);
setBackground(Color.lightGray);
}
#Override
public void start()
{
red = new Thread[maxCar];
blue = new Thread[maxCar];
display.init(maxCar);
Airport b;
if (fair.getState() && safe.getState())
b = new FairAirport();
else if ( safe.getState())
b = new SafeAirport();
else
b = new Airport();
for (int i = 0; i<maxCar; i++)
{
red[i] = new Thread(new RedPlane(b,display,i));
blue[i] = new Thread(new BluePlane(b,display,i));
}
for (int i = 0; i<maxCar; i++)
{
red[i].start();
blue[i].start();
}
}
#Override
public void stop()
{
for (int i = 0; i<maxCar; i++)
{
red[i].interrupt();
blue[i].interrupt();
}
}
}
Your class SingleLaneAirport should extend Applet class in order to use getDocumentBase() function.
Because getDocumentBase() is the function of Applet class and not the Object class