I am trying to create a walking animation. It should alternate between playerLeft and playerLeftWalk. The code is shown below:
public class MyClass extends JPanel implements ActionListener, KeyListener{
protected Timer tm = new Timer(10, this);
protected Clip clip;
protected Image background, playerSprite, playerLeft, playerLeftWalk;
protected int mapdx = 0;
protected int mapdy = 0;
protected int mapX = 0;
protected int mapY = 0;
protected int playerX = 1060;
protected int playerY = 2800;
protected volatile boolean activeThread;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.background, this.mapX + this.mapdx, this.mapY - this.mapdy, this);
g.drawImage(this.playerSprite, this.playerX, this.playerY, this);
}
#Override
public void actionPerformed(ActionEvent e) {
mapX += mapdx;
mapY += mapdy;
this.repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
Thread playerControl=null;
if (!activeThread) {
this.activeThread=true;
playerControl = new Thread(new Runnable() {
#Override
public void run() {
switch (k) {
case KeyEvent.VK_LEFT:
mapdx = 1;
mapdy = 0;
System.out.println("Map X: " + mapX + " Map Y: " + mapY);
try {
playerSprite = playerLeftWalk;
Thread.sleep(250);
playerSprite = playerLeft;
} catch (InterruptedException e) {
}
break;
default:
break;
}
}
});
activeThread=false;
}
if(playerControl!=null)
playerControl.start();
}
#Override
public void keyReleased(KeyEvent e) {
int k = e.getKeyCode();
if(k == KeyEvent.VK_LEFT) {
mapdx = 0;
mapdy = 0;
playerSprite = playerLeft;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
What the code above does is work for the first "cycle" and then stutter thereafter. I assume that what is happening is that multiple threads are being created, making the image stutter.
I have this code from java2s.com and I just modified it. I don't know if I need to use the runnable or the documentlistener so that the application will automatically highlight the word that was defined in the code. I don't have much knowledge about the two, I tried the runnable but I encountered errors. Can someone help me? Here's the code.
public class Sample {
public static void main(String[] args) {
JFrame f = new JFrame();
JTextPane textPane = new JTextPane();
String word = "";
Highlighter highlighter = new UnderlineHighlighter(null);
textPane.setHighlighter(highlighter);
textPane.setText("This is a test");
final WordSearcher searcher = new WordSearcher(textPane);
final UnderlineHighlighter uhp = new UnderlineHighlighter(Color.red);
String w = "i";
int offset = searcher.search(w);
if (offset == -1) {
return;
}
try {
textPane.scrollRectToVisible(textPane.modelToView(offset));
} catch (BadLocationException ex) {
}
textPane.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void removeUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void changedUpdate(DocumentEvent evt) {
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.add(panel, "South");
f.add(new JScrollPane(textPane), "Center");
f.setSize(400, 400);
f.setVisible(true);
}
public static String word;
public static Highlighter highlighter = new UnderlineHighlighter(null);
}
class WordSearcher {
public WordSearcher(JTextComponent comp) {
this.comp = comp;
this.painter = new UnderlineHighlighter.UnderlineHighlightPainter(
Color.red);
}
public int search(String word) {
int firstOffset = -1;
Highlighter highlighter = comp.getHighlighter();
Highlighter.Highlight[] highlights = highlighter.getHighlights();
for (int i = 0; i < highlights.length; i++) {
Highlighter.Highlight h = highlights[i];
if (h.getPainter() instanceof
UnderlineHighlighter.UnderlineHighlightPainter) {
highlighter.removeHighlight(h);
}
}
if (word == null || word.equals("")) {
return -1;
}
String content = null;
try {
Document d = comp.getDocument();
content = d.getText(0, d.getLength()).toLowerCase();
} catch (BadLocationException e) {
// Cannot happen
return -1;
}
word = word.toLowerCase();
int lastIndex = 0;
int wordSize = word.length();
while ((lastIndex = content.indexOf(word, lastIndex)) != -1) {
int endIndex = lastIndex + wordSize;
try {
highlighter.addHighlight(lastIndex, endIndex, painter);
} catch (BadLocationException e) {
// Nothing to do
}
if (firstOffset == -1) {
firstOffset = lastIndex;
}
lastIndex = endIndex;
}
return firstOffset;
}
protected JTextComponent comp;
protected Highlighter.HighlightPainter painter;
}
class UnderlineHighlighter extends DefaultHighlighter {
public UnderlineHighlighter(Color c) {
painter = (c == null ? sharedPainter : new UnderlineHighlightPainter(c));
}
public Object addHighlight(int p0, int p1) throws BadLocationException {
return addHighlight(p0, p1, painter);
}
public void setDrawsLayeredHighlights(boolean newValue) {
// Illegal if false - we only support layered highlights
if (newValue == false) {
throw new IllegalArgumentException(
"UnderlineHighlighter only draws layered highlights");
}
super.setDrawsLayeredHighlights(true);
}
public static class UnderlineHighlightPainter extends
LayeredHighlighter.LayerPainter {
public UnderlineHighlightPainter(Color c) {
color = c;
}
public void paint(Graphics g, int offs0, int offs1, Shape bounds,
JTextComponent c) {
// Do nothing: this method will never be called
}
public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds,
JTextComponent c, View view) {
g.setColor(color == null ? c.getSelectionColor() : color);
Rectangle alloc = null;
if (offs0 == view.getStartOffset() && offs1 == view.getEndOffset()) {
if (bounds instanceof Rectangle) {
alloc = (Rectangle) bounds;
} else {
alloc = bounds.getBounds();
}
} else {
try {
Shape shape = view.modelToView(offs0,
Position.Bias.Forward, offs1,
Position.Bias.Backward, bounds);
alloc = (shape instanceof Rectangle) ? (Rectangle) shape
: shape.getBounds();
} catch (BadLocationException e) {
return null;
}
}
FontMetrics fm = c.getFontMetrics(c.getFont());
int baseline = alloc.y + alloc.height - fm.getDescent() + 1;
g.drawLine(alloc.x, baseline, alloc.x + alloc.width, baseline);
g.drawLine(alloc.x, baseline + 1, alloc.x + alloc.width,
baseline + 1);
return alloc;
}
protected Color color; // The color for the underline
}
protected static final Highlighter.HighlightPainter sharedPainter = new
UnderlineHighlightPainter(
null);
protected Highlighter.HighlightPainter painter;
}
Maybe your code has some import errors? It runs fine with Java 1.8. In this situation it is Ok to use DocumentListener. Made some modifications in main class for finding text "test":
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.*;
public class Sample {
public static void main(String[] args) {
JFrame f = new JFrame();
JTextPane textPane = new JTextPane();
String word = "test";
Highlighter highlighter = new UnderlineHighlighter(null);
textPane.setHighlighter(highlighter);
textPane.setText("This is a test");
final WordSearcher searcher = new WordSearcher(textPane);
final UnderlineHighlighter uhp = new UnderlineHighlighter(Color.red);
String w = "i";
int offset = searcher.search(w);
if (offset == -1) {
return;
}
try {
textPane.scrollRectToVisible(textPane.modelToView(offset));
} catch (BadLocationException ex) {
}
textPane.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void removeUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void changedUpdate(DocumentEvent evt) {
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(textPane), "Center");
f.setSize(400, 400);
f.setVisible(true);
searcher.search(word);
}
public static String word;
public static Highlighter highlighter = new UnderlineHighlighter(null);
}
}
In the showDebugWindow() method inside a class I called, [TinyDebug], the JOptionPane.showInputDialog() is called twice even after I input the correct password, why is that?
Additionally, this code is being executed from an update() method in my Game class, which is called once every second.
Take a look below at the following sets of code for the problem.
Game:
public class Game extends TinyPixel {
private static Game game;
private static KeyManager keyManager;
private static MouseManager mouseManager;
private static GameStateManager sManager;
private boolean isRunning;
private int targetTime;
private final int frameCap = 60;
public Game(String gameTitle, String gameVersion, int gameWidth, int gameRatio, int gameScale) {
super(gameTitle, gameVersion, gameWidth, gameRatio, gameScale);
init();
}
public void init() {
Utilities.printMessage("\t\t-[" + Library.gameTitle + "]-" +
"\n[Game Version]: " + gameVersion +
"\n[Unique Build Number]: " + Utilities.generateCode(16));
ResourceLoader.loadImages();
ResourceLoader.loadMusic();
ResourceLoader.loadSound();
ResourceLoader.loadFonts();
keyManager = new KeyManager(this);
mouseManager = new MouseManager(this);
sManager = new GameStateManager(this);
}
#Override public void update() {
sManager.update();
mouseManager.update();
}
#Override public void render() {
BufferStrategy bs = tinyWindow.getCanvas().getBufferStrategy();
if (bs == null) {
tinyWindow.getCanvas().createBufferStrategy(3);
tinyWindow.getCanvas().requestFocus();
return;
}
Graphics g = bs.getDrawGraphics();
g.clearRect(0, 0, gameWidth, gameHeight);
sManager.render(g);
g.dispose();
bs.show();
}
public void start() {
if(isRunning) return;
isRunning = true;
new Thread(this, gameTitle + " " + gameVersion).start();
}
public void stop() {
if(!isRunning) return;
isRunning = false;
}
#Override public void run() {
isRunning = true;
targetTime = 1000 / frameCap;
long start = 0;
long elapsed = 0;
long wait = 0;
while (isRunning) {
start = System.nanoTime();
update();
render();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if (wait < 0) wait = 5;
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
Utilities.printErrorMessage("Failed to Load " + gameTitle + " " + gameVersion);
}
}
stop();
}
public static KeyManager getKeyManager() {
return keyManager;
}
public static GameStateManager getsManager() {
return sManager;
}
public static Game getGame() {
return game;
}
}
GameLauncher:
public class GameLauncher {
public static void main(String[] args) {
new Game(Library.gameTitle, Library.gameVersion, 640, TinyPixel.Square, 1).start();
}
}
GameStateManager:
public class GameStateManager {
private int numStates = 3;
public static final int MenuState = 0;
public static final int LoadingState = 1;
public static final int GameState = 2;
public static GameState[] gStates;
private static int currentState;
private static String currentMusic;
protected Game game;
public GameStateManager(Game game) {
this.game = game;
init();
}
private void init() {
gStates = new GameState[numStates];
currentState = MenuState;
//currentMusic = Library.backgroundMusic;
//TinyPlayer.playMusic(currentMusic);
loadState(currentState);
}
private void loadState(int gState) {
if (gState == MenuState) gStates[gState] = new MenuState(game, this);
if (gState == LoadingState) gStates[gState] = new LoadingState(game, this);
if (gState == GameState) gStates[gState] = new PlayState(game, this);
}
private void unloadState(int gState) {
gStates[gState] = null;
}
public void setState(int gState) {
unloadState(gState);
currentState = gState;
loadState(gState);
}
private void changeMusic(String key) {
if (currentMusic.equals(key)) return;
TinyPlayer.stopMusic(currentMusic);
currentMusic = key;
TinyPlayer.loop(currentMusic);
}
public void update() {
try {
gStates[currentState].update();
} catch (Exception e) {}
}
public void render(Graphics g) {
try {
gStates[currentState].render(g);
} catch (Exception e) {}
}
public static int getCurrentState() {
return currentState;
}
}
GameState:
public abstract class GameState {
protected Game game;
protected GameStateManager sManager;
public GameState(Game game, GameStateManager sManager) {
this.game = game;
this.sManager = sManager;
init();
}
public abstract void init();
public abstract void update();
public abstract void render(Graphics g);
}
MenuState:
public class MenuState extends GameState {
private Rectangle playBtn, exitBtn;
private TinyDebug tinyDebug;
public static final Color DEFAULT_COLOR = new Color(143, 48, 223);
public MenuState(Game game, GameStateManager sManager) {
super(game, sManager);
init();
}
public void init() {
tinyDebug = new TinyDebug();
int xOffset = 90, yOffset = 70;
playBtn = new Rectangle(Game.getWidth() / 2 - xOffset, Game.getHeight() / 2, 180, 40);
exitBtn = new Rectangle(Game.getWidth() / 2 - xOffset, Game.getHeight() / 2 + yOffset, 180, 40);
}
public void update() {
if (Game.getKeyManager().debug.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_Q, true);
tinyDebug.showDebugWindow();
}
if (Game.getKeyManager().space.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_SPACE, true);
sManager.setState(GameStateManager.LoadingState);
}
if (Game.getKeyManager().exit.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_ESCAPE, true);
System.exit(0);
}
}
public void render(Graphics g) {
//Render the Background
g.drawImage(Library.menuBackground, 0, 0, Game.getWidth(), Game.getHeight(), null);
//Render the Game Version
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Version: " + Library.gameVersion, Game.getWidth() / 2 + 245, Game.getHeight() - 30);
//Render the Social Section
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#nickadamou", 20, Game.getHeight() - 60);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#nicholasadamou", 20, Game.getHeight() - 45);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Ever Tried? Ever Failed? No Matter. Try Again. Fail Again. Fail Better.", 20, Game.getHeight() - 30);
//Render the Debug Section
tinyDebug.renderDebug(g);
g.setColor(Color.white);
g.drawRect(playBtn.x, playBtn.y, playBtn.width, playBtn.height);
g.drawRect(exitBtn.x, exitBtn.y, exitBtn.width, exitBtn.height);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 14), Color.white, "Play Game [space]", playBtn.x + 10, playBtn.y + 25);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 14), Color.white, "Exit Game [esc]", exitBtn.x + 20, exitBtn.y + 25);
}
}
keyManager:
public class KeyManager implements KeyListener {
private Game game;
public KeyManager(Game game) {
this.game = game;
game.getTinyWindow().getCanvas().addKeyListener(this);
}
public class Key {
private int amtPressed = 0;
private boolean isPressed = false;
public int getAmtPressed() {
return amtPressed;
}
public boolean isPressed() {
return isPressed;
}
public void toggle(boolean isPressed) {
this.isPressed = isPressed;
if (isPressed) amtPressed++;
}
}
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public Key space = new Key();
public Key debug = new Key();
public Key exit = new Key();
public void keyPressed(KeyEvent key) {
toggleKey(key.getKeyCode(), true);
}
public void keyReleased(KeyEvent key) {
toggleKey(key.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {}
public void toggleKey(int keyCode, boolean isPressed) {
game.getTinyWindow().getFrame().requestFocus();
game.getTinyWindow().getCanvas().requestFocus();
if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) {
up.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) {
down.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) {
left.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) {
right.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_SPACE) {
space.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_Q) {
debug.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_ESCAPE) {
exit.toggle(isPressed);
}
}
#SuppressWarnings("unused")
private void debug(KeyEvent key) {
System.out.println("[keyCode]: " + key.getKeyCode());
}
}
TinyDebug:
public class TinyDebug {
private final String appTitle = Library.gameTitle;
private String tinyPassword, tinyBuildCode;
private boolean isAllowedDebugging = false;
private boolean isShowingTinyText = false;
public TinyDebug() {
tinyPassword = "test123"; // - Standard Password (Non-Renewable)
//tinyPassword = Utilities.generateCode(16); // - Stronger Password (Renewable)
writePasswordToFile(tinyPassword);
tinyBuildCode = Utilities.generateCode(16);
}
//TODO: This method invokes JOptionPane.showInputDialog() twice even after I input the correct password, why?
public void showDebugWindow() {
boolean hasRun = true;
if (hasRun) {
Clipboard cBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
cBoard.setContents(new StringSelection(tinyPassword), null);
if (isAllowedDebugging() && isShowingTinyText()) return;
String userPassword = JOptionPane.showInputDialog("Input Password to Enter [TinyDebug].");
do {
if (userPassword.equals(tinyPassword)) {
JOptionPane.showMessageDialog(null, "[" + appTitle + "]: The Password Entered is Correct.", appTitle + " Message", JOptionPane.PLAIN_MESSAGE);
isAllowedDebugging(true);
isShowingTinyText(true);
break;
} else {
JOptionPane.showMessageDialog(null, "[Error Code]: " + Utilities.generateCode(16) + "\n[Error]: Password is Incorrect.", appTitle + " Error Message", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} while (userPassword != null || userPassword.trim().isEmpty() != true);
}
hasRun = false;
}
#SuppressWarnings("unused")
public void renderDebug(Graphics g) {
if (isAllowedDebugging()) {
//TODO: Render Debug Information.
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Tiny Pixel [Debug]", 5, 10);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#. [Options are Shown Here]", 10, 25);
if (isShowingTinyText()) {
String debugHeader = appTitle + " Information";
String debugPasswordField = appTitle + " Information:";
String debugBuildNumber = appTitle + " Unique Build #: " + getTinyBuildCode();
}
}
}
//TODO: This method prints the [Utilities.printMessage(appTitle + ": [tinyPassword] Generated and Stored # FilePath: \n" + logFile.getAbsolutePath());] twice, why?
private void writePasswordToFile(String tinyPassword) {
BufferedWriter bWriter = null;
try {
File logFile = new File("tinyPassword.txt");
Utilities.printMessage(appTitle + ": [tinyPassword] Generated and Stored # FilePath: \n" + logFile.getAbsolutePath());
bWriter = new BufferedWriter(new FileWriter(logFile));
bWriter.write(appTitle + " debug Password: " + tinyPassword);
} catch (Exception e) {
Utilities.printErrorMessage("Failed to Write [tinyPassword] to File.");
} finally {
try {
bWriter.close();
} catch (Exception e) {
Utilities.printErrorMessage("Failed to Close [bWriter] Object.");
}
}
}
public String getTinyPassword() {
return tinyPassword;
}
public String getTinyBuildCode() {
return tinyBuildCode;
}
public void isShowingTinyText(boolean isShowingTinyText) {
this.isShowingTinyText = isShowingTinyText;
}
public boolean isShowingTinyText() {
return isShowingTinyText;
}
public void isAllowedDebugging(boolean isAllowedDebugging) {
this.isAllowedDebugging = isAllowedDebugging;
if (isAllowedDebugging) showDebugWindow();
}
public boolean isAllowedDebugging() {
return isAllowedDebugging;
}
}
In showDebugWindow() method, you have this statement:
if (userPassword.equals(tinyPassword)) {
...
isAllowedDebugging(true); // Problematic statement
...
}
Which calls this method:
public void isAllowedDebugging(boolean isAllowedDebugging) {
this.isAllowedDebugging = isAllowedDebugging;
if (isAllowedDebugging) showDebugWindow(); // Second call?
}
As you see, when you set isAllowedDebugging switch, you also call the method, so when you enter password correct, this second call happens.
i made a canvas J2ME program and i used key press and key code to complete the program! now i have a big problem with two screen commands!
I need to use the command labels "Ersal" and "Virayesh" as below code but the command code doesn't work! i could use the key Codes(-6) but then i don't have command labels in the screen.
So whats your solution?
can i just add two labels in the screen not command?!
or how can i active these command void!
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.*;
import com.sun.midp.io.j2me.comm.WAP;
import com.sun.midp.io.j2me.comm.SDA;
public class Demo extends MIDlet
{
Command ersal = new Command("Ersal", Command.STOP, 1);
Command virayesh = new Command("Virayesh", Command.SCREEN, 1);
private Canvas m_canvas = new DemoCanvas();
private Display m_disp;
int v = 0;
public static final int IME_NOTIFY = -6;
public static final int KEY_ASTERISK = 42;
public static final int KEY_HASH = 35;
String a;
int step = -1;
public Demo() {
// TODO Auto-generated constructor stub
m_disp = Display.getDisplay(this);
m_disp.setCurrent(m_canvas);
}
private class DemoCanvas extends Canvas implements CommandListener
{
private String info = "Barname Estelam\n*:Meno Aval\n\nYek dokme ` `ra\nfeshar dahid";
public DemoCanvas(){}
public void paint(Graphics g)
{
g.setColor(0xFFFFFF);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(0);
g.drawString(info, 0, 5, Graphics.LEFT|Graphics.TOP);
/*
if(step==-1){
step=0;
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
info = "1:moshakhasat\nkhodro \n2:estelam taghib \n3:etelaat malek \n4:estelam khalafi";
repaint();
}
*
*/
}
protected void keyPressed(int keyCode)
{
/*
if(IME_NOTIFY == keyCode){
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
}
*
*/
if(keyCode==42 || step==-1){
info="1:moshakhasat\nkhodro \n2:estelam taghib \n3:etelaat malek \n4:estelam khalafi";
step=0;
a="";
m_canvas.removeCommand(ersal);
m_canvas.removeCommand(virayesh);
//m_disp.setCurrent(m_canvas);
WAP.WAP_InputMethodContents("");
}
String content = WAP.GetT9String();
if(step==2){
step=3;
//tayid T9
m_canvas.addCommand(ersal);
m_canvas.addCommand(virayesh);
String n = WAP.GetT9String();
if(a.equals("11") && n.length()>7)
info = "moshakhasat\nkhodro\n\npelak:\n" + pelakSp(content);
if(a.equals("12") && n.length()>7)
info = "moshakhasat\nkhodro\n\nshomare shasi:\n" + content;
if(a.equals("13") && n.length()>7)
info = "moshakhasat\nkhodro\n\nshomare motor:\n" + content;
if(a.equals("21") && n.length()>7)
info = "estelam taghib\n\npelak:\n" + pelakSp(content);
if(a.equals("31") && n.length()>7)
info = "etelaat malek\n\npelak:\n" + pelakSp(content);
if(a.equals("41") && n.length()>7)
info = "estelam khalafi\n\npelak:\n" + pelakSp(content);
repaint();
}
if(step==1){
if(keyCode==49){
step=2;
a+="1";
//pelak
String c = info;
WAP.WAP_InputMethodContentsLength(8);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = WAP.GetT9String();
repaint();
}
if(keyCode==50 && a.equals("1")){
step=2;
a+="2";
//shomare shasi0-9
String c = info;
WAP.WAP_InputMethodContentsLength(14);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = com.sun.midp.io.j2me.comm.WAP.GetT9String();
}
repaint();
if(keyCode==51 && a.equals("1")){
step=2;
a+="3";
//shomare motor
String c = info;
WAP.WAP_InputMethodContentsLength(10);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = com.sun.midp.io.j2me.comm.WAP.GetT9String();
repaint();
}
}
if(step==0){
if(keyCode==49){
a="1";
info="*Moshakhasat\nkhodro*\n1:Pelak\n2:Shomare Shasi\n3:Shomare Motor";
step=1;
}
if(keyCode==50){
a="2";
info="*Estelam Taghib*\n1:Pelak";
step=1;
}
if(keyCode==51){
a="3";
info="*Moshakhast Malek*\n1:Pelak";
step=1;
}
if(keyCode==52){
a="4";
info="*Estelam Khalafi*\n1:Pelak";
step=1;
}
}
repaint();
}
public void commandAction(Command c, Displayable d) {
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
// throw new UnsupportedOperationException("Not supported yet.");
}
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
// TODO Auto-generated method stub
notifyDestroyed();
}
protected void pauseApp() {}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
public String pelakSp(String a){
//tafkike pelak
String m = a.substring(0, 2) + " " + a.substring(2, 3) + " " + a.substring(3, 6) + "-" + a.substring(6, 8);
return m;
}
}
Try
this.addCommand(...)
in your constructor
i got the problem!
i didn't used command listener for my canvas!
i add this and it solved:
m_canvas.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
}
});
I just now trying to make a game where there are few borders on the map, which is being generated from a text document. The text document has 1s and 0s where ther is 1 it shows a wall. So how do I make it so the character stops infront of the wall
My Code:
MAIN CLASS:
public class JavaGame {
public static void main(String[] args) {
final Platno p = new Platno();
final JFrame okno = new JFrame("Test");
Mapa map = new Mapa();
okno.setResizable(false);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
okno.setSize(800, 600);
okno.setVisible(true);
map.nacti();
okno.add(p);
p.mapa = map;
okno.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int kod = e.getKeyCode();
if(kod == KeyEvent.VK_LEFT)
{
Platno.x -= 3;
p.repaint();
}
else if(kod == KeyEvent.VK_RIGHT)
{
Platno.x +=3;
p.repaint();
}
else if(kod == KeyEvent.VK_UP)
{
Platno.y -=3;
p.repaint();
}
else if(kod == KeyEvent.VK_DOWN)
{
Platno.y +=3;
p.repaint();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
/* Timer = new Timer(1, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
Platno.y -=3;
p.repaint();
}
}); */
}`
Map loader class:
public void nacti()
{
try (BufferedReader br = new BufferedReader(new FileReader("map1-1.txt")))
{
String radek;
int cisloRadku = 0;
while((radek = br.readLine()) != null)
{
for(int i = 0; i < radek.length(); i++)
{
char znak = radek.charAt(i);
int hodnota = Integer.parseInt(String.valueOf(znak));
pole[i][cisloRadku] = hodnota;
}
cisloRadku++;
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
public void vykresli(Graphics g)
{
try {
wall = ImageIO.read(ClassLoader.getSystemResource("Images/wall.gif"));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
for(int i = 0; i < pole[0].length; i++)
{
for(int j = 0; j < pole.length; j++)
{
if(pole[j][i] == 1)
{
g.setColor(Color.RED);
// g.fillRect(j*40, i*40, 40, 40);
g.drawImage(wall, j*40, i*40, null);
}
}
}
}`
and the Hero class:
public class Hero {
public int poziceX;
public int poziceY;
public static boolean upB = false;
public static boolean downB = false;
public static boolean rightB = false;
public static boolean leftB = false;
BufferedImage up;
BufferedImage down;
BufferedImage right;
BufferedImage left;
public Hero()
{
try {
up = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Up.png"));
down = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Down.png"));
right = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Right.png"));
left = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Left.png"));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
public void vykreslit(Graphics g)
{
if(upB == true)
{
g.drawImage(up, poziceX, poziceX, null);
}
else if(downB == true)
{
g.drawImage(down, poziceX, poziceX, null);
}
else if(leftB == true)
{
g.drawImage(left, poziceX, poziceX, null);
}
else if(rightB == true)
{
g.drawImage(right, poziceX, poziceX, null);
}
}`
Thanks for your help :)
You could calculate the 'future position' for a move, and test for collisions.
If a collision occur, dont'move, otherwise you're ok to move.
See if this logic can help you:
public boolean willCollide(int row, int col, Board map)
{
return map[row][col] == 1;
}
public void moveLeft(Hero hero, Board map)
{
//watch for index out of bounds!
int futureCol = hero.y - 1;
if (! willCollide(hero.row, futureCol)
hero.y = futureCol;
}