The application is a text based Starbucks simulator.
Image
The problem I am facing is how do I change reference to a screen base on a (x, y) values.
I am looking for a solution where I give the screen the responsibility of changing to the next screen base on x and y values.
Here is the third layer of the application which initial's screen is MyCards:
public class Frame implements IFrame {
private IScreen current = new MyCards();
/* Most code are taken out because not relevant */
public void touch(int x, int y){
if(current!= null){ current.touch(x, y)}
}
}
If I call frame.touch(3,3) it should change the reference to a new screen which I call MyCardsPay.
Here is my interface I call IScreen:
public interface IScreen
{
void touch(int x, int y) ; // send touch events to screen
String display() ; // displays screen components
String name() ; // returns name of screen
void next() ; // navigate to next screen
void prev() ; // navigate to previous screen
void setNext(IScreen s, String n ) ; // set next screen with action name
void setPrev(IScreen s, String n ) ; // set previous screen with action name
}
Here is my base class I call Screen:
public class Screen implements IScreen {
public Screen(){
}
#Override
public void touch(int x, int y) {
}
#Override
public void next() {
// add code here
}
#Override
public void prev() {
// add code here
}
#Override
public void setNext(IScreen s, String n ) {
// add code here
}
#Override
public void setPrev(IScreen s, String n ) {
// add code here
}
#Override
public String display() {
return "";
}
#Override
public String name() {
return (this.getClass().getName()).split("\\.")[1] ;
}
}
Here is my MyCard class:
public class MyCards extends Screen {
private Double price;
public MyCards() {
}
public void setPrice(Double p){
price = p;
}
#Override
public String display(){
return getPriceDescription() + super.display();
}
public String getPriceDescription(){
NumberFormat formatter = NumberFormat.getCurrencyInstance();
return formatter.format(price);
}
}
Here is my MyCardsPay class:
public class MyCardsPay extends Screen
{
String cardID;
public MyCardsPay()
{
}
public void setCardID(String c){
cardID = c;
}
#Override
public String display(){
if(cardID == null){
return super.display();
}
return "[" + cardID + "]" + "\n\n\n" + "Scan Now";
}
}
If i'm not getting wrong, you are storing the current screen by the current filed of Frame class, and you want to change the screen reference by Frame.touch() method?
In this case I would suggest making touch(in IScreen, and in MyCards and MyCardsPay) returning not void, but the "result screen" of touch(). And store the result by Frame.current.
That is to say, Frame like:
public class Frame implements IFrame {
private IScreen current = new MyCards();
/* Most code are taken out because not relevant */
public void touch(int x, int y){
if(current!= null){ current = current.touch(x, y)}
}
}
And the Screens like:
public class MyCards extends Screen {
#Override
public IScreen touch(int x, int y) {
if(isOnThePayButton(x, y)){
return new MyCardsPay();
}
}
}
A good way is to use the Observer pattern. Have Screen tell Frame which screen to update on touch method.
Use an interface to communicate.
public interface IScreenFlowObserver {
void switched(String screen, String n);
}
Have Frame implement it.
public class Frame implements IFrame, IScreenFlowObserver{
/* More code*/
public void switched(String screen, String n){ /* */
}
}
Then change the base class to:
public class Screen implements IScreen{
IScreenFlowObserver observer;
public void setObserver(IScreenFlowObserver o){
observer = o;
}
}
Last, have a ScreenFactory to create Screens.
With that simple design pattern, Screen classes can tell Frame who to switch to. This allows let if statments.
Related
I am making an apllication in java swing for practice by using drag and drop components , i am facing a problem, i put inside the JPanel, an JInternal Frame
, it is moveable,
i want to make it un-moveable
,which event is used for it? How can i do it ? i search on the internet but unfortunately unable to find the solution for this.
I have found this on internet but i want to do it with the help of event option in swing.
// Make first internal frame unmovable
JInternalFrame[] frames = frame.desktop.getAllFrames();
JInternalFrame f = frames[0];
BasicInternalFrameUI ui = (BasicInternalFrameUI)f.getUI();
Component north = ui.getNorthPane();
MouseMotionListener[] actions = // there is no option for MouseMotionListener in the event option
(MouseMotionListener[])north.getListeners(MouseMotionListener.class);
for (int i = 0; i < actions.length; i++)
north.removeMouseMotionListener( actions[i] );
DesktopManager is resposible for all operation with internal frames. So you can redefine it using the proxy pattern to make some of your frames non-movable. Here is non-complete example for you (sorry I havn't tested this code, so I'm not sure whether it works).
private static class ProxyDesktopManager implements DesktopManager {
private final DesktopManager delegate;
public ProxyDesktopManager(DesktopManager delegate) {
this.delegate = Objects.requireNonNull(delegate);
}
// Check whether frame is moveable
private boolean checkFrameMovable(JComponent frame) {
if (frame instanceof JInternalFrame) {
// TODO check whether the frame if movable
}
return false;
}
#Override
public void beginDraggingFrame(JComponent f) {
if (checkFrameMovable(f)) {
delegate.beginDraggingFrame(f);
}
}
#Override
public void dragFrame(JComponent f, int newX, int newY) {
if (checkFrameMovable(f)) {
delegate.dragFrame(f, newX, newY);
}
}
#Override
public void endDraggingFrame(JComponent f) {
if (checkFrameMovable(f)) {
delegate.endDraggingFrame(f);
}
}
#Override
public void openFrame(JInternalFrame f) {
delegate.openFrame(f);
}
#Override
public void closeFrame(JInternalFrame f) {
delegate.closeFrame(f);
}
#Override
public void maximizeFrame(JInternalFrame f) {
delegate.maximizeFrame(f);
}
#Override
public void resizeFrame(JComponent f, int newX, int newY, int newWidth, int newHeight) {
delegate.resizeFrame(f, newX, newY, newWidth, newHeight);
}
// IMPORTANT: simply delegate all another methods like openFrame or
// resizeFrame
}
Now you can use this proxy class for your JDesktopPane
JDesktopPane desktop = new JDesktopPane();
desktop.setDesktopManager(new ProxyDesktopManager(desktop.getDesktopManager()));
I want to develop a simple interactive game (like arcanoid). I already have implemented a menu and different views, and now I need to develop the actually game (draw flying ball, some movable platform) and I don't know how to do this. I need something like canvas where I can draw my graphic each frame.
I have tryed to implement this with Canvas and Timer. But it doesn't want update graphic itself, but only when user clicks on screen or similar. Also I saw com.google.gwt.canvas.client.Canvas, but I cannot understand how to use it in Vaadin application.
So my question is next: is it possible to draw some graphic each frame with high framerate in any way? If possible, how can I do this?
P.S. I use the Vaadin 7.3.3.
ADDED LATER:
Here is a link to my educational project with implementation below.
I'll be glad if it helps someone.
ORIGINAL ANSWER:
Well... I found the solution myself. First of all, I have created my own widget - "client side" component (according to this article).
Client side part:
public class GWTMyCanvasWidget extends Composite {
public static final String CLASSNAME = "mycomponent";
private static final int FRAMERATE = 30;
public GWTMyCanvasWidget() {
canvas = Canvas.createIfSupported();
initWidget(canvas);
setStyleName(CLASSNAME);
}
Connector:
#Connect(MyCanvas.class)
public class MyCanvasConnector extends AbstractComponentConnector {
#Override
public Widget getWidget() {
return (GWTMyCanvasWidget) super.getWidget();
}
#Override
protected Widget createWidget() {
return GWT.create(GWTMyCanvasWidget.class);
}
}
Server side part:
public class MyCanvas extends AbstractComponent {
#Override
public MyCanvasState getState() {
return (MyCanvasState) super.getState();
}
}
Then I just add MyCanvas component on my View:
private void createCanvas() {
MyCanvas canvas = new MyCanvas();
addComponent(canvas);
canvas.setSizeFull();
}
And now I can draw anything on Canvas (on client side in GWTMyCanvasWidget) with great performance =). Example:
public class GWTMyCanvasWidget extends Composite {
public static final String CLASSNAME = "mycomponent";
private static final int FRAMERATE = 30;
private Canvas canvas;
private Platform platform;
private int textX;
public GWTMyCanvasWidget() {
canvas = Canvas.createIfSupported();
canvas.addMouseMoveHandler(new MouseMoveHandler() {
#Override
public void onMouseMove(MouseMoveEvent event) {
if (platform != null) {
platform.setCenterX(event.getX());
}
}
});
initWidget(canvas);
Window.addResizeHandler(new ResizeHandler() {
#Override
public void onResize(ResizeEvent resizeEvent) {
resizeCanvas(resizeEvent.getWidth(), resizeEvent.getHeight());
}
});
initGameTimer();
resizeCanvas(Window.getClientWidth(), Window.getClientHeight());
setStyleName(CLASSNAME);
platform = createPlatform();
}
private void resizeCanvas(int width, int height) {
canvas.setWidth(width + "px");
canvas.setCoordinateSpaceWidth(width);
canvas.setHeight(height + "px");
canvas.setCoordinateSpaceHeight(height);
}
private void initGameTimer() {
Timer timer = new Timer() {
#Override
public void run() {
drawCanvas();
}
};
timer.scheduleRepeating(1000 / FRAMERATE);
}
private void drawCanvas() {
canvas.getContext2d().clearRect(0, 0, canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight());
drawPlatform();
}
private Platform createPlatform() {
Platform platform = new Platform();
platform.setY(Window.getClientHeight());
return platform;
}
private void drawPlatform() {
canvas.getContext2d().fillRect(platform.getCenterX() - platform.getWidth() / 2, platform.getY() - 100, platform.getWidth(), platform.getHeight());
}
}
I have the following problem:
I am trying to implement a menu with submenus in libgdx, using the table layout. When a submenu is clicked, a listener is fired, which should setVisible(false) the previous menu, and setVisible(true) the new one. But, although I successfully display the new one, the previous one is still here! Could someone help me?
Here is my code:
The Menu.java:
public class Menu extends Table {
private Stage stage;
public void attachToStage(Stage s) {
if (s != null) {
stage = s;
s.addActor(this);
}
}
public Menu() {
this(null);
}
public Menu(final Stage s) {
attachToStage(s);
setFillParent(true);
top();
left();
}
private void addButtonWithListener(String label, ClickListener listener) {
add().width(10);
Label l = new Label(label, SkinManager.get());
add(l).width(100);
row();
if (listener != null)
l.addListener(listener);
}
/**
* #param label
* #return The menu, for chaining
*/
public Menu addButton(String label) {
addButtonWithListener(label, null);
return this;
}
/**
*
* #param label
* #param m
* the menu to add
* #return The main menu, for chaining
*/
public Menu addMenu(String label, final Menu m) {
addButtonWithListener(label, new ClickListener() {
#Override public void clicked(InputEvent e, float x, float y) {
System.out.println(getChildren());
setVisible(false);
m.setVisible(true);
}
});
m.attachToStage(stage);
m.setVisible(false);
return this;
}
}
My Application:
public class TestApplication implements ApplicationListener {
private Stage stage;
#Override public void create() {
stage = new Stage();
Menu m = new Menu(stage).addButton("Move").addButton("Stay");
m.addMenu("Attack", new Menu().addButton("Sword").addButton("Bow"));
Gdx.input.setInputProcessor(stage);
}
#Override public void render() {
stage.draw();
}
// Other empty methods
}
Thanks a lot!
EDIT: Problem was unrelated, see my answer
Ok, found the problem: not related at all to the Table, just forgott to clear the screen in the Application.
I just added
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
in the render function.
I am working on a game using JME3 and Nifty GUI. I have an outer class that has a Nifty member variable. And the inner class should be able to access that variable regardless of access modifier. In the constructor I assign a new Nifty object to it. However when I access that variable in the inner class I run into problems. I did a little debugging and found out it's because the inner class thinks the Nifty member variable is null and I cant figure out why. Its not null in the outer class. Since this is a JME3 game I tried to have the inner class implement the AppState interface but it still shows the Nifty member variable as null. Here is the code:
public class MenuScreen extends SimpleApplication {
/** Used to configure Nifty GUI. */
private Nifty mNifty;
private NiftyJmeDisplay mNiftyDisplay;
private Element popup;
//*******************
// Overridden medhods
//*******************
/** This method is used to initialize everything needed to display the game screen. */
#Override
public void simpleInitApp() {
guiNode.detachAllChildren();
initNifty();
flyCam.setDragToRotate(true);
}
/**
* The game's main update loop.
*
* #param tpf Time Per Fram, the time it takes each loop to run.
*/
#Override
public void simpleUpdate(float tpf) {
// not used
}
#Override
public void simpleRender(RenderManager rm) {
// not used
}
public static void main(String[] args) {
MenuScreen app = new MenuScreen();
app.start();
}
/**
* Helper method to initialize and configure Nifty GUI.
*/
private void initNifty() {
mNiftyDisplay = new NiftyJmeDisplay(assetManager, inputManager, audioRenderer, guiViewPort);
mNifty = mNiftyDisplay.getNifty();
guiViewPort.addProcessor(mNiftyDisplay);
// If this is being run on a desktop then load the desktop main menu.
if (Strings.OS_NAME.contains("windows") || Strings.OS_NAME.contains("mac") || Strings.OS_NAME.contains("linux")) {
mNifty.fromXml("Interface/XML/DesktopMenuScreenGui.xml", "start", new MenuScreen().new MenuScreenGui());
}
// If its an Android device load the mobile main menu.
else if (Strings.OS_NAME.contains("android")) {
mNifty.fromXml("Interface/XML/MobileMenuScreenGui.xml", "mobile", new MenuScreen().new MenuScreenGui());
}
}
//**************
// Inner Classes
//**************
/**
* © Jason Crosby 2012 <p>
*
* This class handles all the GUI interactions like button clicks.
*
* #author Jason Crosby
*/
public class MenuScreenGui implements ScreenController, EventTopicSubscriber<MenuItemActivatedEvent>,
AppState {
#Override
public void initialize(AppStateManager stateManager, Application app) {
}
#Override
public void cleanup() {
}
#Override
public boolean isEnabled() {
return false;
}
#Override
public boolean isInitialized() {
return false;
}
#Override
public void postRender() {
}
#Override
public void setEnabled(boolean active) {
}
#Override
public void stateAttached(AppStateManager stateManager) {
}
#Override
public void stateDetached(AppStateManager stateManager) {
}
#Override
public void render(RenderManager rm) {
}
#Override
public void update(float tpf) {
}
#Override
public void bind(Nifty nifty, Screen screen) {
// not used
}
#Override
public void onEndScreen() {
// not used
}
#Override
public void onStartScreen() {
// not used
}
#Override
public void onEvent(String string, MenuItemActivatedEvent t) {
}
//**************
// Class methods
//**************
/**
* Called when the play button is clicked.
*/
public void playButton() {
}
/**
* Called when the high scores button is clicked.
*/
public void highScoresButton() {
}
/**
* Called when the settings button is clicked.
*/
public void settingsButton() {
}
public void quitButton() {
showDialog();
}
/**
* Called when the rate button is clicked. Only Available on mobile.
*/
public void rateButton() {
}
/**
* Called when the feedback button is clicked. Only on mobile devices.
*/
public void feedbackButton() {
}
/**
* Called when the help button is clicked.
*/
public void helpButton() {
}
/**
* Called when the dialog needs to be shown.
*/
public void showDialog() {
System.out.println("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW");
popup = new Nifty().createPopup("popup");
System.out.println("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
//Menu myMenu = popup.findNiftyControl("#menu", Menu.class);
//myMenu.setWidth(new SizeValue("100px")); // must be set
//myMenu.addMenuItem("Click me!", new menuItem("menuItemid", "blah blah")); // menuItem is a custom class
//mNifty.subscribe(mNifty.getCurrentScreen(), myMenu.getId(), MenuItemActivatedEvent.class, this);
mNifty.showPopup(mNifty.getCurrentScreen(), popup.getId(), null);
}
public void clsoseDialog() {
}
/**
* Used to return a String to the Nifty xml file.
*
* #param name The name key associated with the String.
* #return The String associated with the key.
*/
public String getString(String name) {
if (name.equals("play")) {
return Strings.PLAY_BUTTON;
}
else if (name.equals("high_score")) {
return Strings.HIGH_SCORES_BUTTON;
}
else if (name.equals("settings")) {
return Strings.SETTINGS_BUTTON;
}
else if (name.equals("quit")) {
return Strings.QUIT_BUTTON;
}
else if (name.equals("rate")) {
return Strings.RATE_BUTTON;
}
else if (name.equals("feedback")) {
return Strings.FEEDBACK_BUTTON;
}
else if (name.equals("rules")) {
return Strings.RULES_BUTTON;
}
return null;
}
}
}
What happens is I click on the quit button which calls the quitButton() method. That works fine. That in turn invokes showDialog() which is where the problem is. In the showDialog() method is this line popup = new Nifty().createPopup("popup"); and it is at that line which mNifty is null when it shouldn't be. Any assistance is appreciated.
The line
popup = new Nifty().createPopup("popup");
does not use mNifty. It creates a new instance of Nifty and then calls creatPopup() on this new instance. Since earlier you initialized mNifty by calling what looks like a factory method
mNifty = mNiftyDisplay.getNifty();
it is quite possible that obtaining a Nifty via new does not return a completely initialized instance. Since you haven't posted the code for Nifty it is unclear what is happening.
I would double-check to make sure that creating a Nifty via new will return a fully initialized instance, and that you really wanted a new instance here.
I need a listener that will constantly check if a static boolean value has been changed so that I can repaint a component on a frame. Can someone please help me I really don't know much about listeners and haven't worked with them much? Help will be greatly appreciated.
edit(more clarity): I have two separate classes in which on class is the "main frame" the second class is an extension of JLabel and implements MouseListner for a "clickable photo". The "main frame" creates instances of the photo and when the photo is clicked the "main frame" is supposed to paint on the panel a description of the photo. This is "main frame"
MenuBar menuBar;
static AnnotationVisual a;
Picture pic;
Picture pic2;
GalleryScreen(int rows, int columns){
this.setBorder(BorderFactory.createEmptyBorder(500,500,0,0));
pic = new Picture("pic1", "Z:/My Documents/Downloads/Ball.jpg", new Coordinate(0,0));
pic2 = new Picture("pic2", "Z:/My Documents/Downloads/hoop.jpg" , new Coordinate(1,0));
this.add(pic);
this.add(pic2);
a = new AnnotationVisual();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(a.shouldAnnotate()){
FontMetrics size= g.getFontMetrics();
if(getWidth()>=(a.dispX()+size.stringWidth(a.annotationText()))){
g.setColor(Color.white);
g.fillRect(a.dispX()-3,a.dispY()-12,size.stringWidth(a.annotationText())+5,15);
g.setColor(Color.black);
g.drawRect(a.dispX()-3,a.dispY()-12,size.stringWidth(a.annotationText())+5,15);
g.drawString(a.annotationText(), a.dispX(), a.dispY());
}else{
String sub="";
int letters=0;
g.setColor(Color.white);
g.fillRect(a.dispX()-3,a.dispY()-12,getWidth(),15);
g.setColor(Color.black);
for(int i=0;i<a.annotationText().length();i++){
if(a.dispX()+letters+16<=getWidth()){
sub+=a.annotationText().substring(i,i+1);
letters=size.stringWidth(sub);
}else{
sub=sub+"...";
i=a.annotationText().length();
}
}
g.drawRect(a.dispX()-3,a.dispY()-12,size.stringWidth(sub)+3,15);
g.drawString(sub,a.dispX(),a.dispY());
}
}
}
public static AnnotationVisual getA()
{
return a;
}
This is "clickable photo"
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.*;
import javax.swing.*;
public class Picture extends JLabel implements MouseListener
{
String myAnnotation;
String filePath;
Coordinate imageCoord;
private boolean wasDoubleClick;
private Timer timer;
EditAnnotation newEdit;
AnnotationVisual newVisual;
public Picture(String annotation, String filePath, Coordinate coord)
{
super(new ImageIcon(filePath));
this.addMouseListener(this);
myAnnotation=annotation;
this.filePath = filePath;
imageCoord = coord;
newEdit = new EditAnnotation(annotation);
newVisual = new AnnotationVisual();
}
public Picture(String filePath)
{
super(new ImageIcon(filePath));
this.addMouseListener(this);
this.filePath = filePath;
newEdit = new EditAnnotation();
newVisual = new AnnotationVisual();
}
public String getAnnotation()
{
return myAnnotation;
}
public AnnotationVisual getAnnotationVisual()
{
return newVisual;
}
public void setAnnotation(String annotation)
{
myAnnotation=annotation;
}
public Coordinate getCoordinate()
{
return imageCoord;
}
public void setCoordinate(Coordinate coord)
{
imageCoord = coord;
}
public Dimension getSize()
{
return new Dimension(super.getIcon().getIconWidth(), super.getIcon().getIconHeight());
}
public void mouseClicked(MouseEvent e)
{
final int scrLocX = (int)e.getLocationOnScreen().getX();
final int scrLocY = (int)e.getLocationOnScreen().getY();
if (e.getClickCount() == 2)
{
wasDoubleClick = true;
}
else if(e.getClickCount() == 1)
{
Integer timerinterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
timer = new Timer(timerinterval.intValue(), new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if (wasDoubleClick)
{
GalleryScreen.getA().deleteAnnotation();
myAnnotation = newEdit.getAnnotation();
newEdit.show(myAnnotation);
wasDoubleClick = false;
}
else
{
GalleryScreen.getA().deleteAnnotation();
GalleryScreen.getA().showAnnotation(scrLocX, scrLocY , myAnnotation);
}
}
});
timer.setRepeats(false);
timer.start();
}
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
}
AnnotationVisual is the thing that supposed to pop up when single clicked
You're probably better off making the boolean private, and only allowing it to be changed through a setter method. The setter method, when called, should then repaint the component.
The point of listeners is to invert the logic. You don't constantly check if a value is changed. You notify the listener when you change the value.
So, instead of Foo.bar = 5, you invoke Foo.setBar(5), where in addition to the assignment, you call barListener.valueChanged(value)
As a sidenote - avoid storing state in static variables.
You don't set a listener on a field in Java, you set it on a property. While properties (according to the JavaBeans spec) can be fields, they're usually done as pairs of methods (one getter, one setter; the latter being not needed for read-only fields) as that lets you hook extra logic in to be called when the property is accessed. Such as firing a listener callback to say that the value has changed. (You could use a thread to monitor for that sort of thing, but that's really nasty and error-prone. Wasteful too.)
One thing to be aware of though: you don't know what thread the value will have been modified from. Take care when invoking back into Swing…