I am trying to push a new screen when a bitmap is "clicked" on the screen. For this I have created a Class from this post: Blackberry Clickable BitmapField whose partial code I've posted below:
public class CustomMenuButtonField extends Field{
Bitmap normal,focused;
...
protected boolean navigationClick(int status, int time)
{
// push new screen
fieldChangeNotify(0);
return true;
}
...
I want to push a new screen when the user clicks the bitmap. I have consulted this thread:
Communicating between classes, but I still can't figure out the commands to call the new screen command. The UserInterface I have so far is:
public class UserInterface extends UiApplication {
public static void main(String[] args){
UserInterface theApp = new UserInterface();
theApp.enterEventDispatcher();
}
public UserInterface() {
pushScreen(new UserInterfaceScreen());
}
}
final class UserInterfaceScreen extends MainScreen {
public UserInterfaceScreen() {
...
What would be the command to pop up the new screen, and more importantly where would I be able to work on it? I know it should probably use pushScreen() but that is not recognized in that class. Would I create a new final class NewScreenFromClick extends MainScreen? and if so how would I call it and put it in the eventDispatcher. I've been going through the blackberry site but they don't have much sample code on this issue and I am very new to Java so this is fairly confusing to me.
imageField imageField = new imageField ("",Field.FOCUSABLE,"image.png","image.png", 0x102839);
add(imageField );
FieldChangeListener listener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (field == imageField ) {
home home = new home();//your screen
UiApplication.getUiApplication().pushScreen(home);
}
}
};
imageField .setChangeListener(listener);
//imagefield class is given below
package com.pl.button;
import net.rim.device.api.ui.*;
import net.rim.device.api.system.*;
public class imagefield extends Field {
private String _label;
private int _labelHeight;
private int _labelWidth;
private Font _font;
private Bitmap _currentPicture;
private Bitmap _onPicture;
private Bitmap _offPicture;
int color;
public imagefield (String text, long style ,String img, String img_hvr, int color){
super(style);
_offPicture = Bitmap.getBitmapResource(img);
_onPicture = Bitmap.getBitmapResource(img_hvr);
_font = getFont();
_label = text;
_labelHeight = _onPicture.getHeight();
_labelWidth = _onPicture.getWidth();
this.color = color;
_currentPicture = _offPicture;
}
/**
* #return The text on the button
*/
String getText(){
return _label;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredHeight()
*/
public int getPreferredHeight(){
return _labelHeight;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredWidth()
*/
public int getPreferredWidth(){
return _labelWidth;
}
/**
* Field implementation. Changes the picture when focus is gained.
* #see net.rim.device.api.ui.Field#onFocus(int)
*/
protected void onFocus(int direction) {
_currentPicture = _onPicture;
invalidate();
}
/**
* Field implementation. Changes picture back when focus is lost.
* #see net.rim.device.api.ui.Field#onUnfocus()
*/
protected void onUnfocus() {
_currentPicture = _offPicture;
invalidate();
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#drawFocus(Graphics, boolean)
*/
protected void drawFocus(Graphics graphics, boolean on) {
// Do nothing
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#layout(int, int)
*/
protected void layout(int width, int height) {
setExtent(Math.min( width, getPreferredWidth()),
Math.min( height, getPreferredHeight()));
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#paint(Graphics)
*/
protected void paint(Graphics graphics){
// First draw the background colour and picture
graphics.setColor(this.color);
graphics.fillRect(0, 0, getWidth(), getHeight());
graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0, 0);
// Then draw the text
graphics.setColor(Color.BLACK);
graphics.setFont(_font);
graphics.drawText(_label, 4, 2,
(int)( getStyle() & DrawStyle.ELLIPSIS | DrawStyle.HALIGN_MASK ),
getWidth() - 6 );
}
/**
* Overridden so that the Event Dispatch thread can catch this event
* instead of having it be caught here..
* #see net.rim.device.api.ui.Field#navigationClick(int, int)
*/
protected boolean navigationClick(int status, int time){
fieldChangeNotify(1);
return true;
}
}
You can use:
UiApplication.getUiApplication().pushScreen(new HomeScreen());
If your application is not doing anything strange UiApplication.getUiApplication() will always return the UiApplication object for your program. This is a singleton object created for each UiApplication context.
You could also use:
UserInterface.getUiApplication().pushScreen(new HomeScreen());
If the UserInterface class is visible to the class you are working on, but this would make your code less re-usable.
I've collected some basic samples on my blog. Have a look at this page. Start at the bottom and work your way up.
Try the following code I have added UserInterfaceScreen. When UserInterfaceScreen is constructed, it adds a CustomMenuButtonField and sets a field change listener. When the button is clicked it pushes the new screen to the stack
package mypackage;
import net.rim.device.api.ui.UiApplication;
public class UserInterface extends UiApplication {
public static void main(String[] args){
UserInterface theApp = new UserInterface();
theApp.enterEventDispatcher();
}
public UserInterface() {
pushScreen(new UserInterfaceScreen());
}
}
This is the UserInterfaceScreen
package mypackage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;
public class UserInterfaceScreen extends MainScreen {
public UserInterfaceScreen() {
super();
//replace null with the image string
CustomMenuButtonField button = new CustomMenuButtonField(null, null);
button.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
UiApplication.getUiApplication().pushScreen(new MyHomeScreen());
}
});
}
}
Look the answer in the below link which I posted by me(alishaik786) :
Clickable Bitmap;
Related
Good Afternoon, I'm back with another new-bee question. I am trying to create an program with a Star Trek inspired interface. I do not want to use dialog boxes with the program.
My interface is drawn on the screen in the fraMain class that my program calls first. It is shown below:
/**
* Troy Marker Enterprises
* TMEA-002-J: PHMS Database - Java
* Main Activity Code File
* Copyright (c) 2020 By Troy Marker Enterprises
* All Rights Under Copyright Reserved
*
* The code in this file was created for use with Troy Marker Enterprises Software.
* Use of this code by the public is strictly prohibited.
*/
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Main program frame class
*/
public class fraMain extends JFrame implements ActionListener{
/**
* Program variable definitions
*/
private JPanel panMainMenu;
public static JPanel panSubMenu;
public static JPanel panTop;
private JPanel panBottom;
private int screenWidth;
private int screenHeight;
/**
* Method to start the program
* #param args - Method arguments
*/
public static void main(String[] args) {
new fraMain();
}
/**
* Method to draw the main window
*/
public fraMain() {
EventQueue.invokeLater(this::run);
}
/**
* Draw the main window
*/
private void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
GraphicsEnvironment graphics = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = graphics.getDefaultScreenDevice();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setBackground(Color.BLACK);
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
screenWidth = gd.getDisplayMode().getWidth();
screenHeight = gd.getDisplayMode().getHeight();
this.panMainMenu = new ClassMainMenu(screenWidth, screenHeight);
panSubMenu = new ClassSubMenu(screenWidth, screenHeight);
panSubMenu.setVisible(false);
panTop = new ClassTopFrame(screenWidth,screenHeight);
this.panBottom = new ClassBottomFrame(screenWidth, screenHeight);
this.add(this.panMainMenu);
this.add(panSubMenu);
this.add(panTop);
this.add(panBottom);
this.pack();
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
device.setFullScreenWindow(this);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
The screen is divided into four panels: panMainMenu, panSubMenu, panTop, and panBotom.
Each panel has its own class that draw its contents.
The panSubMenu is hidden until a button in the Main Menu is pressed, which show the sub menu. That part is working fine.
However, when I click the Exit Button on the main menu the only t hing that happens is the top frame turns white.
Here is my code for the Main Menu:
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ClassMainMenu extends JPanel implements ActionListener {
final TMButton department;
final TMButton grade;
final TMButton user;
final TMButton exit;
private String MainMenuOption;
private final int screenHeight;
private final int screenWidth;
public ClassMainMenu(int screenWidth, int screenHeight) {
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.setBackground(Color.BLACK);
this.setBounds(0, 0, 160, screenHeight);
department = new TMButton("DEPARTMENT", "green");
grade = new TMButton("GRADES", "green");
user = new TMButton("USERS", "green");
exit = new TMButton("EXIT","blue");
department.addActionListener(this);
grade.addActionListener(this);
user.addActionListener(this);
exit.addActionListener(this);
this.add(department);
this.add(grade);
this.add(user);
this.add(exit);
}
public void deselectAll() {
for (Component c : this.getComponents()) {
if (c instanceof TMButton) {
((TMButton)c).setSelected(false);
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
ClassTopFrame topFrame = new ClassTopFrame();
if(e.getSource()==department) {
this.deselectAll();
fraMain.panSubMenu.setVisible(true);
department.setSelected(true);
MainMenuOption = "Department";
}
if(e.getSource()==grade) {
this.deselectAll();
fraMain.panSubMenu.setVisible(true);
grade.setSelected(true);
MainMenuOption = "Grade";
}
if(e.getSource()==user) {
this.deselectAll();
fraMain.panSubMenu.setVisible(true);
user.setSelected(true);
MainMenuOption = "User";
}
if(e.getSource()==exit) {
this.deselectAll();
exit.setSelected(true);
fraMain.panTop = topFrame.exitProgram(fraMain.panTop);
//System.exit(0);
}
}
}
And the code for the top panel:
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
public class ClassTopFrame extends JPanel{
private int screenWidth;
private int screenHeight;
public ClassTopFrame(int Width, int Height) {
screenWidth = Width;
screenHeight = Height;
this.setBackground(Color.BLACK);
this.setBounds(160, 0, screenWidth-160, screenHeight/2);
JLabel jl=new JLabel();
jl.setIcon(new javax.swing.ImageIcon(Objects.requireNonNull(getClass().getResource("/i_TMEA-0002-J_Logo.png"))));
this.add(jl);
}
public ClassTopFrame() {
}
public JPanel exitProgram(JPanel returnPanel) {
returnPanel.setBackground(Color.BLACK);
returnPanel.setBounds(160, 0, screenWidth-160, screenHeight/2);
JLabel jl=new JLabel();
jl.setIcon(new javax.swing.ImageIcon(Objects.requireNonNull(getClass().getResource("/i_TMEA-0002-J_Logo.png"))));
returnPanel.add(jl);
return returnPanel;
}
}
My plan is the have a new panel replace the top panel when the Exit button is pressed. I know the current code will only display the same contents of the panel when the button is clicked, it just wanted to put something the int exitProgram method for it to display.
As I said, I am a Java new-bee. I am not even sure if what I want to do is possible, I want to think so. Can anyone help me figure this out?
Thanks, Troy
Here is a picture of what I am looking to do:
The right side of the screen will show the sub menu when one of the buttons is clicked.
ADDITION:
In response to some help I have been getting, I am trying to switch to a card layout, but am having problem. I tried posting here, but it looks like adding the required information will make this post to long. So I uploaded everything to my GitHub account. The main changes I made are in this fine: https://github.com/troy-marker/TMEA-0002-J/blob/main/src/com/troymarkerenterprises/ClassBottomFrame.java
I use this class for my school app projects. It is how I set the application up and it extends JFrame and implements Runnable. Now whenever I use this in school on a Windows computer and everything works and the screen updates, but at home on a Mac it doesn't. I use Eclipse neon with JDK 1.8.0_101
Please help me out, I can't test any projects at home cause of this.
import java.awt.Graphics;
import javax.swing.JFrame;
public abstract class GUIApplication extends JFrame implements Runnable{
private Screen currentScreen;
//no main, cant instentiate an abstract class
public GUIApplication(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int x=40;
int y=40;
int width=1000;
int height=640;
setBounds(x,y,width,height);
initScreen();
setVisible(true);
}
//this is a method for creating the starting screen
protected abstract void initScreen();
public void setScreen(Screen screen){
//stop controls from previous screen
removeListeners();
setCurrentScreen(screen);
//add new controls
addListeners();
}
private void removeListeners(){
if(getCurrentScreen() != null){
if(getCurrentScreen().getMouseListener() != null) removeMouseListener(getCurrentScreen().getMouseListener());
if(getCurrentScreen().getMouseMotionListener() != null) removeMouseMotionListener(getCurrentScreen().getMouseMotionListener());
if(getCurrentScreen().getKeyListener() != null) removeKeyListener(getCurrentScreen().getKeyListener());
// if(currentScreen.getMouseWheelListener() != null) removeMouseWheelListener(currentScreen.getMouseWheelListener());
}
}
private void addListeners(){
if(getCurrentScreen() != null){
if(getCurrentScreen().getMouseListener() != null)addMouseListener(getCurrentScreen().getMouseListener());
if(getCurrentScreen().getMouseMotionListener() != null) addMouseMotionListener(getCurrentScreen().getMouseMotionListener());
if(getCurrentScreen().getKeyListener() != null){
addKeyListener(getCurrentScreen().getKeyListener());
}
// if(currentScreen.getMouseWheelListener() != null) addMouseWheelListener(currentScreen.getMouseWheelListener());
}
}
public void paint(Graphics g){
g.drawImage(getCurrentScreen().getImage(), 0, 0, null);
}
public void run(){
while(true){
getCurrentScreen().update();
repaint();
try {
Thread.sleep(30);
repaint();
revalidate();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Screen getCurrentScreen() {
return currentScreen;
}
public void setCurrentScreen(Screen currentScreen) {
this.currentScreen = currentScreen;
}
}
This is how a game would start:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.ArrayList;
import javax.swing.JFrame;
import game.mainScreenTeam.Dragon;
import game.mainScreenTeam.HomeScreen;
import game.miniGameTeam.GameInstructions;
import game.miniGameTeam.GameScreen;
import game.miniGameTeam.HighScoreScreen;
import game.shopScreen.BuyScreenWendy;
import game.shopScreen.HomeShopScreen;
import game.shopScreen.SellShopZheng;
import guiPractice.GUIApplication;
import guiPractice.Screen;
import guiPractice.components.AnimatedComponent;
/**
* #author Kat
*
*/
public class DragonLand extends GUIApplication {
public static DragonLand game;
public static int coins = 1500;
public static HomeScreen homeScreen;
public static Screen shopMain; // shop 1
public static Screen sellScreen; // shop 2
public static Screen buyScreen; // shop 3
public static Screen highscoreScreen; // high score
public static GameScreen miniGameScreen; // minigame
public static Screen gameInstructionsScreen;
public static Screen HelpScreen;
public static Color NAVY;
public static Color BRIGHT_PINK;
public static Color LIGHT_PINK;
public static Color LIGHT_NUDE;
public static Color DARKER_NUDE;
/**
*
*/
// public static void addDragon(AnimatedComponent a){
// dragonList.add(a);
// }
public DragonLand() {
}
/* (non-Javadoc)
* #see guiPractice.GUIApplication#initScreen()
*/
#Override
protected void initScreen() {
initColors();
miniGameScreen = new GameScreen(getWidth(),getHeight());
shopMain = new HomeShopScreen(getWidth(),getHeight());
sellScreen = new SellShopZheng(getWidth(),getHeight());
homeScreen = new HomeScreen(getWidth(),getHeight());
buyScreen = new BuyScreenWendy(getWidth(),getHeight());
highscoreScreen = new HighScoreScreen(getWidth(),getHeight());
HomeScreen.jenCode = new game.mainScreenTeam.HomeJenniber();
gameInstructionsScreen = new GameInstructions(getWidth(), getHeight());
setScreen(homeScreen);
}
private void initColors() {
NAVY = new Color(62,74,99);
BRIGHT_PINK = new Color(224,102,102);
LIGHT_PINK = new Color(248,186,182);
LIGHT_NUDE = new Color(244,215,183);
DARKER_NUDE = new Color(230,195,147);
}
/**
* #param args
*/
public static void main(String[] args) {
game = new DragonLand();
Thread go = new Thread(game);
go.start();
}
//public coin getter + setter
public void setCoins(int x){
coins = x;
}
public int getCoins(){
return coins;
}
}
This is the home screen
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import game.DragonLand;
import guiPractice.ClickableScreen;
import guiPractice.components.Action;
import guiPractice.components.AnimatedComponent;
import guiPractice.components.Button;
import guiPractice.components.Graphic;
import guiPractice.components.TextLabel;
import guiPractice.components.Visible;
import guiPractice.sampleGames.MouseFollower;
/**
* #author Kat
* #author Jenniber
*
*/
public class HomeScreen extends ClickableScreen implements Runnable{
private Graphic background;
public static HomeJenniber jenCode;
public HomeScreen(int width, int height) {
super(width, height);
Thread play = new Thread(this);
play.start();
}
#Override
public void initAllObjects(ArrayList<Visible> viewObjects) {
background=new Graphic(0,0,getWidth(),getHeight(),"img/Grassland.png");
viewObjects.add(background);
HomeKat katCode=new HomeKat(viewObjects, getWidth(), getHeight());
}
#Override
public void run() {
}
}
katCode adds buttons to the screen and image annimations
public void paint(Graphics g){
g.drawImage(getCurrentScreen().getImage(), 0, 0, null);
}
Don't override paint() on a JFrame.
The proper way to do custom painting is to override paintComponent(...) on a JPanel (or JComponent) and then you can set the content pane of the frame to this panel. And don't forget to invoke super.paintComponent(...) as the first statement in the method. Read the section from the Swing tutorial on Custom Painting for more information and working examples.
However if you do get lazy, then at minimum you need to invoke super.paint(...) as the first statement in the paint(...) method.
Also, I doubt you need the revalidate(), since you don't appear to be adding/removing components from the frame.
But in general the order should be:
revalidate(); // to invoke the layout manager
repaint(); // paint components in new location.
I also don't know why you are invoking the update() method. That seems like old AWT code which you don't use in Swing. I suggest you take a look at the tutorial link I gave you and look at the table of contents for other Swing basics.
I have these 3 classes which is supposed to work together to create a game. But I'm getting an error in one of them where it wants me to add unimplemented methods. The class which is creating the error is called Game and looks like this.
package org.game.main;
import java.awt.Graphics2D;
public class Game extends Window {
public static void main(String[] args) {
Window window = new Game();
window.run(1.0 / 60.0);
System.exit(0);
}
public Game() {
// call game constructor
super("Test Game", 640, 480);
}
public void gameStartup() {
}
public void gameUpdate(double delta) {
}
public void gameDraw(Graphics2D g) {
}
public void gameShutdown() {
}
}
It wants me to implement the method called Update() from the Window class. The Window class looks like this.
package org.game.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import org.game.input.*;
/**
* Game that creates a window and handles input.
* #author Eric
*/
public abstract class Window extends GameLoop {
private Frame frame;
private Canvas canvas;
private BufferStrategy buffer;
private Keyboard keyboard;
private Mouse mouse;
private MouseWheel mouseWheel;
/**
* Creates a new game window.
*
* #param title title of the window.
* #param width width of the window.
* #param height height of the window.
*/
public Window(String title, int width, int height) {
/*Log.debug("Game", "Creating game " +
title + " (" + width + ", " + height + ")");*/
// create frame and canvas
frame = new Frame(title);
frame.setResizable(false);
canvas = new Canvas();
canvas.setIgnoreRepaint(true);
frame.add(canvas);
// resize canvas and make the window visible
canvas.setSize(width, height);
frame.pack();
frame.setVisible(true);
// create buffer strategy
canvas.createBufferStrategy(2);
buffer = canvas.getBufferStrategy();
// create our input classess and add them to the canvas
keyboard = new Keyboard();
mouse = new Mouse();
mouseWheel = new MouseWheel();
canvas.addKeyListener(keyboard);
canvas.addMouseListener(mouse);
canvas.addMouseMotionListener(mouse);
canvas.addMouseWheelListener(mouseWheel);
canvas.requestFocus();
}
/**
* Get the width of the window.
*
* #return the width of the window.
*/
public int getWidth()
{
return canvas.getWidth();
}
/**
* Get the height of the window.
*
* #return the height of the window.
*/
public int getHeight()
{
return canvas.getHeight();
}
/**
* Returns the title of the window.
*
* #return the title of the window.
*/
public String getTitle()
{
return frame.getTitle();
}
/**
* Returns the keyboard input manager.
* #return the keyboard.
*/
public Keyboard getKeyboard()
{
return keyboard;
}
/**
* Returns the mouse input manager.
* #return the mouse.
*/
public Mouse getMouse()
{
return mouse;
}
/**
* Returns the mouse wheel input manager.
* #return the mouse wheel.
*/
public MouseWheel getMouseWheel() {
return mouseWheel;
}
/**
* Calls gameStartup()
*/
public void startup() {
gameStartup();
}
/**
* Updates the input classes then calls gameUpdate(double).
* #param delta time difference between the last two updates.
*/
public void update(double delta) {
// call the input updates first
keyboard.update();
mouse.update();
mouseWheel.update();
// call the abstract update
gameUpdate(delta);
}
/**
* Calls gameDraw(Graphics2D) using the current Graphics2D.
*/
public void draw() {
// get the current graphics object
Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
// clear the window
g.setColor(Color.BLACK);
g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
// send the graphics object to gameDraw() for our main drawing
gameDraw(g);
// show our changes on the canvas
buffer.show();
// release the graphics resources
g.dispose();
}
/**
* Calls gameShutdown()
*/
public void shutdown() {
gameShutdown();
}
public abstract void gameStartup();
public abstract void gameUpdate(double delta);
public abstract void gameDraw(Graphics2D g);
public abstract void gameShutdown();
}
The last class is called Gameloop and looks like this.
package org.game.main;
public abstract class GameLoop {
private boolean runFlag = false;
/**
* Begin the game loop
* #param delta time between logic updates (in seconds)
*/
public void run (double delta) {
runFlag = true;
startup();
// convert the time to seconds
double nextTime = (double) System.nanoTime() / 1000000000.0;
double maxTimeDiff = 0.5;
int skippedFrames = 1;
int maxSkippedFrames = 5;
while (runFlag) {
// convert the time to seconds
double currTime = (double) System.nanoTime() / 1000000000.0;
if ((currTime - nextTime) > maxTimeDiff) nextTime = currTime;
if (currTime >= nextTime) {
// assign the time for the next update
nextTime += delta;
update();
if ((currTime < nextTime) || (skippedFrames > maxSkippedFrames)) {
draw();
skippedFrames = 1;
}
else {
skippedFrames++;
}
} else {
// calculate the time to sleep
int sleepTime = (int)(1000.0 * (nextTime - currTime));
// sanity check
if (sleepTime > 0) {
// sleep until the next update
try {
Thread.sleep(sleepTime);
}
catch(InterruptedException e) {
// do nothing
}
}
}
}
shutdown();
}
public void stop() {
runFlag = false;
}
public abstract void startup();
public abstract void shutdown();
public abstract void update();
public abstract void draw();
}
The error I'm getting in console when I run the main class looks like this.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The type Game must implement the inherited abstract method GameLoop.update()
at org.game.main.Game.update(Game.java:5)
at org.game.main.GameLoop.run(GameLoop.java:26)
at org.game.main.Game.main(Game.java:8)
I hope you can help me. I'm quite new to java.
The signature of the update method is not overriding the interface, if that's what you intended.
public void update(double delta)
You need it to match the interface
public abstract void update();
So it sounds like this simple change should help:
public abstract void update(double delta);
In GameLoop you have defined
public abstract void update();
This method must be implemented in one of the sub classes Window or Game with the same signature.
You have implement unimplemented methods of Game Window and GameLoop class
Implement abstract methods. Window class' abstract methods are following:
public abstract void gameStartup();
public abstract void gameUpdate(double delta);
public abstract void gameDraw(Graphics2D g);
public abstract void gameShutdown();
Also implement following methods of GameLoop class
public abstract void startup();
public abstract void shutdown();
public abstract void update();
public abstract void draw();
Okay i found it out with some of the help that you suggested. It was because I hadn't defined Update() in GameLoop as.
public abstract void update(double delta);
Insted of
public abstract void update();
So the method didn't get called in Window. So then it had to be called in Game. Thanks for the help, everything works as should now.
I'm developing a Image Editor in java, i inserted a JPanel inside a JTabbedPane, to create a JTabbedPane with tabs that rapresent the Image Filter i want to apply to the image,
i don't know how to obtain a The inner JPanel of a TabbedPane to decide witch filter is selected,
because when i do " jTabbedPane1.getSelectedComponent(); " i can obtain only a component not a JComponent..
anyone knows something, sorry for my english thank's a lot..
This is a part of my code:
package javaapplication22;
import javax.swing.JPanel;
/**
*
* #author iDoc
*/
public abstract class FilterTab extends JPanel {
public FilterTab() {
}
protected void ApplyFilter() {
}
protected void ResetFilter() {
}
}
public class InvertFilterTab extends FilterTab {
private InvertFilter filter;
public InvertFilterTab ()
{
filter = new InvertFilter();
}
/**
*
* #param originalImage
* #param modifiedImage
*/
public void ApplyFilter(BufferedImage originalImage, BufferedImage modifiedImage) {
modifiedImage = filter.filter(originalImage, modifiedImage);
}
#Override
public void ResetFilter() {
}
}
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedImage originalImage = jOriginalPanel.getImage();
// BufferedImage modifiedImage = new BufferedImage(
// originalImage.getWidth(), originalImage.getHeight(),
// BufferedImage.TYPE_INT_ARGB);
//modifiedImage =
FilterTab ft = jTabbedPane1.getSelectedComponent(); <--- the problem is here
filter.filter(originalImage, modifiedImage);
jModifiedPanel.changeImage(modifiedImage);
jModifiedPanel.repaint();
Simply cast the result ...
FilterTab tab = (FilterTab)jTabbedPane1.getSelectedComponent();
Remember, JPanel extends from JComponent, which extends from Container, which extends from Component
I am trying to make an original game in Eclipse and I am having some trouble writing code that will remove GObjects and change the properties of others, using the mouseClicked method.
The problem seems to be that the private instant variables are not being recognised in the mousePressed method.
Can someone please advise on what I'm getting wrong here? I have spent a whole day on this and some help will be greatly appreciated.
Kind regards,
Mehul
*/*
* File: Linesv1.java
* 07/08/2012
*
*/
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.MenuEvent;
public class Linesv1 extends GraphicsProgram {
/** Width and height of application window in pixels */
public static final int BACKGROUND_WIDTH = 400;
public static final int BACKGROUND_HEIGHT = 600;
/** Dimensions of game board (usually the same) */
private static final int WIDTH = BACKGROUND_WIDTH;
private static final int HEIGHT = BACKGROUND_HEIGHT;
/** Dimensions of triangle*/
private static final int LENGTH_OF_TRIANGLE_SIDE = 100;
/** Dimensions of arc height*/
private static final int ARC_HEIGHT = 100;
/** Dimensions of radius of switches*/
private static final int SWITCH_RADII = 5;
// private instant variables
private GObject switchA;
private GOval switchB;
private GObject triangle;
private GObject bottomArc;
public void run() {
addMouseListeners();
setUpGame();
}
public void setUpGame(){
//add central triangle
GPolygon triangle = new GPolygon (WIDTH/2,HEIGHT/2);
triangle.addVertex(0,-LENGTH_OF_TRIANGLE_SIDE*2/3);
triangle.addVertex(LENGTH_OF_TRIANGLE_SIDE/2,+LENGTH_OF_TRIANGLE_SIDE*1/3);
triangle.addVertex(-LENGTH_OF_TRIANGLE_SIDE/2,+LENGTH_OF_TRIANGLE_SIDE*1/3);
triangle.setFilled(true);
triangle.setFillColor(Color.green);
add(triangle);
//add topArc
GArc bottomArc = new GArc (WIDTH/2-LENGTH_OF_TRIANGLE_SIDE/2, HEIGHT/2+LENGTH_OF_TRIANGLE_SIDE*1/3-ARC_HEIGHT/2, ARC_HEIGHT,ARC_HEIGHT,0,-180);
bottomArc.setFilled(true);
bottomArc.setFillColor(Color.green);
add(bottomArc);
//add switches to the bottom of the triangle
GOval switchA = new GOval (WIDTH/2-LENGTH_OF_TRIANGLE_SIDE/2-SWITCH_RADII, HEIGHT/2+LENGTH_OF_TRIANGLE_SIDE*1/3-SWITCH_RADII,SWITCH_RADII*2,SWITCH_RADII*2);
switchA.setFilled(true);
switchA.setFillColor(Color.black);
add(switchA);
//add switches to the bottom of the triangle
GOval switchB = new GOval (WIDTH/2+LENGTH_OF_TRIANGLE_SIDE/2-SWITCH_RADII, HEIGHT/2+LENGTH_OF_TRIANGLE_SIDE*1/3-SWITCH_RADII,SWITCH_RADII*2,SWITCH_RADII*2);
switchB.setFilled(true);
switchB.setFillColor(Color.black);
add(switchB);
}
public void mousePressed(MouseEvent e) {
findObject(e.getX(),e.getY());
GObject check = findObject(e.getX(),e.getY());
if (check!=null){
remove(triangle);
switchA.setColor(Color.cyan);
}
}
private GObject findObject(int a, int b){
if(getElementAt(a,b) != null) {
return getElementAt(a,b);
} else {
return null;
}
}
}*
The triangle you are trying to remove is not the one you added. You created a local GPolygon called triangle in setupGame() and added that, not the private member.
private GObject triangle; // this is uninitialized
public void setUpGame(){
GPolygon triangle = new GPolygon (WIDTH/2,HEIGHT/2); // this is hiding your member variable
// THIS IS LOCAL COPY, NOT MEMBER VARIABLE
add(triangle);
And then later you try to remove the uninitialized member variable, so nothing happens. You probably don't want a separate local copy of triangle. You probably want
public void setUpGame() {
triangle = new GPolygon (WIDTH/2, HEIGHT/2);
// ...
add(triangle); // Now, you are adding the member
}