Модераторы: javastic, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Выполнение действий при нажатии на клавишу 
:(
    Опции темы
Zamuta
Дата 6.3.2006, 01:41 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 389
Регистрация: 18.1.2006

Репутация: нет
Всего: 6



всего три класса.

Класс мидлета:

Код


package Test;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Timer;
import java.util.TimerTask;


public class MainGame extends MIDlet implements CommandListener{

    private Command exitMidlet = new Command ("Выход", Command.EXIT, 0);
    private MyGameCanvas mr;
    public void startApp() {
        try{
        mr = new MyGameCanvas();
        mr.start();
        mr.addCommand(exitMidlet);
        mr.setCommandListener(this);
        Display.getDisplay(this).setCurrent(mr);
        } catch(java.io.IOException zxz) {};
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
        if(mr != null) mr.stop();
    }
    public void commandAction(Command c, Displayable d)
    {
        if (c == exitMidlet)
        {
            destroyApp(false);
            notifyDestroyed();
        }
    }
}




При запуске приложения просто рисуется картинка в классе MyGameCanvas, а затем при нажатии на RIGHT_PRESSED либо скажем через 2 секнды экран должен очиститься и зпустить код класса MenuScreen, как это сделать?

код класса MyGameCanvas:

Код


package Test;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;

public class MyGameCanvas extends GameCanvas implements Runnable {
    
    private TiledLayer fonPole;
    private LayerManager lm;
    boolean z;
    
    public MyGameCanvas() throws IOException {
        super(true);
        setFullScreenMode(true);
        fonPole = Fon();
        lm = new LayerManager();
        lm.append(fonPole);
    }
    public void start(){
    z = true;
    Thread t = new Thread(this);
    t.start();
    }
    
    public TiledLayer Fon() throws IOException {
    Image im = Image.createImage("/128x160.png");
    fonPole = new TiledLayer(1, 1, im, 128, 160);
    int[] pole =
    {
    1,
    };
    for(int i=0; i<pole.length; i++){
    fonPole.setCell(i % 1, i / 1, pole[i]);
    }
    return fonPole;
    }
    public void stop(){
        z = false;
    }
    
    public void run(){
    Graphics g = getGraphics();
    while(z){
        inputKey();
        init(g);
        try {Thread.sleep(20);
        }
        catch  (java.lang.InterruptedException zxz) {};
    }
    }


    private void inputKey(){
        
        // определяем нажатую клавишу
        int keyStates = getKeyStates();
        if ((keyStates& RIGHT_PRESSED) !=0) ; 




{             как запустить?             }




        
        
    }
    
    private void init(Graphics g)
    {
        g.setColor(0xffffff);
        g.fillRect(0, 0, getWidth(), getHeight());
        lm.paint(g, 0, 0);
        flushGraphics();
    }
    }






код класса MenuScreen:

Код


package Test;

import javax.microedition.lcdui.*;

public class MenuScreen extends Canvas implements Runnable {
    // Set Fonts
    static final Font lowFont = Font.getFont (Font.FACE_MONOSPACE, Font.STYLE_PLAIN, Font.SIZE_SMALL);
    static final Font highFont = Font.getFont (Font.FACE_MONOSPACE, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
    // Set Color
    static final int lowColor = 0x00FFFFFF; // Not Highlighted
    static final int highColor = 0x00FF0000; // Highlighted
    static final int highBGColor = 0x00AACCEE; // Highlighted Background
    static int width; // screen width
    static int height; // screen height
    static int startHeight; // height where the menu starts
    static final int spacing = highFont.getHeight()/2; // spacing between menu items
    // Menu Item Labels
    static final String[] mainMenu = {"Новая игра","Статистика","Настройки","Помощь","Об игре"};   
    // To hold the current highlighted menu option
    static int menuIdx;
    // Menu Thread
    Thread menuThread;
    // Constructor
    public MenuScreen() {
        // Get Width and Height of Canvas
        setFullScreenMode(true);
        width = getWidth();
        height = getHeight();
        // Calculate Start Height of Menu
        startHeight = (highFont.getHeight() * mainMenu.length) + ((mainMenu.length-1) * spacing);
        startHeight = (height - startHeight) / 2;
        // Set Selected Menu Item to the first menu item
        menuIdx = 0;
        // Create Thread and Start
        menuThread = new Thread(this);
        menuThread.start();
        }
    // Simple Run -- Should be modified for better performance/efficiency
    public void run() {
        while(true) {
            repaint();
            }
        }
    // Paint Main Menu
    public void paint(Graphics g) {
        g.setColor(0x00ccdaee);
        g.fillRect(0,0,width,height);
        for (int i=0; i<mainMenu.length; i++) {
            if (i==menuIdx) {
                g.setColor(highBGColor);
                g.fillRect(0,startHeight + (i*highFont.getHeight()) + spacing,width,highFont.getHeight());
                g.setFont(highFont);
                g.setColor(highColor);
                g.drawString(mainMenu[i], (width - highFont.stringWidth(mainMenu[i])) / 2, startHeight + (i*highFont.getHeight()) + spacing, 20 );
                }
            else {
                g.setFont(lowFont);
                g.setColor(lowColor);
                g.drawString(mainMenu[i], (width - lowFont.stringWidth(mainMenu[i]) ) / 2, startHeight + (i*highFont.getHeight()) + spacing, 20);
                }
        }
    }
    // Capture Keypresses for Menu Selection
    protected void keyPressed (int code) {
        if (getGameAction(code) == Canvas.UP && menuIdx - 1 >= 0) {
            menuIdx--;
        } else if (getGameAction(code) == Canvas.DOWN && menuIdx + 1 <mainMenu.length) {
            menuIdx++;
        }
    }
}





--------------------
Thank you opensource.
PM MAIL ICQ   Вверх
redrick
Дата 6.3.2006, 11:23 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 547
Регистрация: 7.1.2004
Где: Москва

Репутация: 1
Всего: 5



дык надо думать точно также :
Код

try{
        MenuScreen mr = new MenuScreen();
        mr.start();
        mr.addCommand(exitMidlet);
        mr.setCommandListener(this);
        Display.getDisplay(this).setCurrent(mr);
        } catch(java.io.IOException zxz) {};



--------------------
Имею Мнение Хрен Оспоришь   
PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса

  • Прежде чем задать вопрос прочтите это!
  • Литература по Java находится здесь.
  • Литературу по Java обсуждаем здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит" (возле кнопок кодов) если у Вас нет русских шрифтов.
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда

  • FAQ раздела лежит здесь!
 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java ME (J2ME) | Следующая тема »


 




[ Время генерации скрипта: 0.0576 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.