Search Results

Search found 128 results on 6 pages for 'keyevent'.

Page 2/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • Unexpected StackOverflowError in KeyListener

    - by BillThePlatypus
    I am writing a program that can write sets of questions for review to a file for another program to read. The possible answers are typed into JTextFields at the bottom. It has code to ensure that there won't bew more than one blank JTextField at the end. When I type in answers, at varying points it will throw a StackOverflowError. The stack trace: Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) and the code: package writer; import java.awt.BorderLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import main.QuestionSet; public class SetPanel extends JPanel implements KeyListener { private QuestionSet set; private WriterPanel writer; private JPanel top=new JPanel(new BorderLayout()),controls=new JPanel(new GridLayout(1,0)),answerPanel=new JPanel(new GridLayout(0,1)); private JSplitPane split; private JTextField title=new JTextField(); private JTextArea question=new JTextArea(); private ArrayList<JTextField> answers=new ArrayList<JTextField>(); public SetPanel(QuestionSet s,WriterPanel writer) { super(new BorderLayout()); top.add(controls,BorderLayout.PAGE_START); title.setFont(title.getFont().deriveFont(40f)); title.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } @Override public void keyPressed(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } @Override public void keyReleased(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } }); title.getDocument().addDocumentListener(new DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } @Override public void removeUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } @Override public void changedUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } }); top.add(title,BorderLayout.PAGE_END); this.add(top,BorderLayout.PAGE_START); question.setLineWrap(true); question.setWrapStyleWord(true); question.setFont(question.getFont().deriveFont(20f)); question.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); }}); split=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,new JScrollPane(question),new JScrollPane(answerPanel)); split.setDividerLocation(150); this.add(split,BorderLayout.CENTER); answers.add(new JTextField()); answerPanel.add(answers.get(0)); answers.get(0).addKeyListener(this); } private void fitTitle() { if(title==null||title.getText().equals("")) return; //title.setText(WriterPanel.convertString(title.getText())); String text=title.getText(); Insets insets=title.getInsets(); int width=title.getWidth()-insets.left-insets.right; int height=title.getHeight()-insets.top-insets.bottom; Font root=title.getFont().deriveFont((float)height); FontMetrics m=title.getFontMetrics(root); if(m.stringWidth(text)<width) { title.setFont(title.getFont().deriveFont((float)height)); return; } float delta=-100; while(Math.abs(delta)>.1f) { m=title.getFontMetrics(root); int w=m.stringWidth(text); if(w==width) break; if(Math.signum(w-width)==Math.signum(delta)||root.getSize2D()+delta<0) { delta/=-10; continue; } root=root.deriveFont(root.getSize2D()+delta); } title.setFont(root); } private void fixAnswers() { //System.out.println(answers); while(answers.get(answers.size()-1).getText().equals("")&&answers.size()>1&&answers.get(answers.size()-2).getText().equals("")) removeAnswer(answers.size()-1); if(!answers.get(answers.size()-1).getText().equals("")) { answers.add(new JTextField()); answerPanel.add(answers.get(answers.size()-1)); answers.get(answers.size()-2).removeKeyListener(this); answerPanel.revalidate(); } answers.get(answers.size()-1).addKeyListener(this); } private void removeAnswer(int i) { answers.remove(i); answerPanel.remove(i); answerPanel.revalidate(); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub fixAnswers(); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } } Thank you in advance for any help.

    Read the article

  • How to send KeyEvents trough an input method service to a Dialog, or a Spinner menu?

    - by shutdown11
    I'm trying to implement an input method service that receives intents sent by a remote client, and in response to those sends an appropriate KeyEvent. I'm using in the input method service this method private void keyDownUp(int keyEventCode) { getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode)); getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_UP, keyEventCode)); } to send KeyEvents as in the Simple Sofykeyboard Sample, and it works in the home, in Activities... but it doesn't works when a Dialog or the menu of a Spinner is in foreground. The events is sent to the parent activity behind the Dialog. Is there any way to send keys and control the device like using the hardware keys from an input method?

    Read the article

  • overriding the Home Key Long press in a category.HOME activity.

    - by Profete162
    Hello all, I just created my own "Home" to replace the stock android one or Sense. All is working fine and I get all I want. My only problem is to replace to long press on home key ( that usually show the last 6 activities you launched) by my own launcher. I successfully replace the long press on MENU button with this code: @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //Log.i(TAG,"Keycode: "+keyCode); if (keyCode == KeyEvent.KEYCODE_MENU) { // this tells the framework to start tracking for // a long press and eventual key up. it will only // do so if this is the first down (not a repeat). event.startTracking(); return true; } (...) and this part part for the long press: @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { //Log.i(TAG,"LONG"+keyCode); Toast.makeText(Launcher.this,"LONG "+keyCode, Toast.LENGTH_SHORT).show(); if (keyCode == KeyEvent.KEYCODE_MENU) { (...) But the problem is that I wasn't able to replace the KeyEvent.KEYCODE_MENU with KeyEvent.KEYCODE_HOME is that something locked in the code that avoid user to use a Home long press? Thank a lot for all the information you woulg give me.

    Read the article

  • trouble running smooth animation in thread only when using key listener

    - by heysuse renard
    first time using a forum for coding help so sorry if i post this all wrong. i have more than a few classes i don't think screenManger or core holds the problem but i included them just incase. i got most of this code working through a set of tutorials. but a certain point started trying to do more on my own. i want to play the animation only when i'm moving my sprite. in my KeyTest class i am using threads to run the animation it used to work (poorly) but now not at all pluss it really gunks up my computer. i think it's because of the thread. im new to threads so i'm not to sure if i should even be using one in this situation or if its dangerous for my computer. the animation worked smoothly when i had the sprite bouce around the screen forever. the animation loop played with out stopping. i think the main problem is between the animationThread, Sprite, and keyTest classes, but itcould be more indepth. if someone could point me in the right direction for making the animation run smoothly when i push down a key and stop runing when i let off it would be greatly apriciated. i already looked at this Java a moving animation (sprite) obviously we were doing the same tutorial. but i feel my problem is slightly different. p.s. sorry for the typos. import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFrame; public class KeyTest extends Core implements KeyListener { public static void main(String[] args) { new KeyTest().run(); } Sprite player1; Image hobo; Image background; animation hoboRun; animationThread t1; //init also calls init form superclass public void init() { super.init(); loadImages(); Window w = s.getFullScreenWindow(); w.setFocusTraversalKeysEnabled(false); w.addKeyListener(this); } //load method will go here. //load all pics need for animation and sprite public void loadImages() { background = new ImageIcon("\\\\STUART-PC\\Users\\Stuart\\workspace\\Gaming\\yellow square.jpg").getImage(); Image face1 = new ImageIcon("\\\\STUART-PC\\Users\\Stuart\\workspace\\Gaming\\circle.png").getImage(); Image face2 = new ImageIcon("\\\\STUART-PC\\Users\\Stuart\\workspace\\Gaming\\one eye.png").getImage(); hoboRun = new animation(); hoboRun.addScene(face1, 250); hoboRun.addScene(face2, 250); player1 = new Sprite(hoboRun); this.t1 = new animationThread(); this.t1.setAnimation(player1); } //key pressed public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_ESCAPE) { stop(); } if (keyCode == KeyEvent.VK_RIGHT) { player1.setVelocityX(0.3f); try { this.t1.setRunning(true); Thread th1 = new Thread(this.t1); th1.start(); } catch (Exception ex) { System.out.println("noooo"); } } if (keyCode == KeyEvent.VK_LEFT) { player1.setVelocityX(-0.3f); try { this.t1.setRunning(true); Thread th1 = new Thread(this.t1); th1.start(); } catch (Exception ex) { System.out.println("noooo"); } } if (keyCode == KeyEvent.VK_DOWN) { player1.setVelocityY(0.3f); try { this.t1.setRunning(true); Thread th1 = new Thread(this.t1); th1.start(); } catch (Exception ex) { System.out.println("noooo"); } } if (keyCode == KeyEvent.VK_UP) { player1.setVelocityY(-0.3f); try { this.t1.setRunning(true); Thread th1 = new Thread(this.t1);; th1.start(); } catch (Exception ex) { System.out.println("noooo"); } } else { e.consume(); } } //keyReleased @SuppressWarnings("static-access") public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_LEFT) { player1.setVelocityX(0); try { this.t1.setRunning(false); } catch (Exception ex) { } } if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN) { player1.setVelocityY(0); try { this.t1.setRunning(false); } catch (Exception ex) { } } else { e.consume(); } } //last method from interface public void keyTyped(KeyEvent e) { e.consume(); } //draw public void draw(Graphics2D g) { Window w = s.getFullScreenWindow(); g.setColor(w.getBackground()); g.fillRect(0, 0, s.getWidth(), s.getHieght()); g.setColor(w.getForeground()); g.drawImage(player1.getImage(), Math.round(player1.getX()), Math.round(player1.getY()), null); } public void update(long timePassed) { player1.update(timePassed); } } abstract class Core { private static DisplayMode modes[] = { new DisplayMode(1600, 900, 64, 0), new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(800, 480, 32, 0), new DisplayMode(800, 480, 24, 0), new DisplayMode(800, 480, 16, 0),}; private boolean running; protected ScreenManager s; //stop method public void stop() { running = false; } public void run() { try { init(); gameLoop(); } finally { s.restoreScreen(); } } //set to full screen //set current background here public void init() { s = new ScreenManager(); DisplayMode dm = s.findFirstCompatibleMode(modes); s.setFullScreen(dm); Window w = s.getFullScreenWindow(); w.setFont(new Font("Arial", Font.PLAIN, 20)); w.setBackground(Color.GREEN); w.setForeground(Color.WHITE); running = true; } //main gameLoop public void gameLoop() { long startTime = System.currentTimeMillis(); long cumTime = startTime; while (running) { long timePassed = System.currentTimeMillis() - cumTime; cumTime += timePassed; update(timePassed); Graphics2D g = s.getGraphics(); draw(g); g.dispose(); s.update(); try { Thread.sleep(20); } catch (Exception ex) { } } } //update animation public void update(long timePassed) { } //draws to screen abstract void draw(Graphics2D g); } class animationThread implements Runnable { String name; boolean playing; Sprite a; //constructor takes input from keyboard public animationThread() { } //The run method for animation public void run() { long startTime = System.currentTimeMillis(); long cumTime = startTime; boolean test = getRunning(); while (test) { long timePassed = System.currentTimeMillis() - cumTime; cumTime += timePassed; test = getRunning(); } } public String getName() { return name; } public void setAnimation(Sprite a) { this.a = a; } public void setName(String name) { this.name = name; } public void setRunning(boolean running) { this.playing = running; } public boolean getRunning() { return playing; } } class animation { private ArrayList scenes; private int sceneIndex; private long movieTime; private long totalTime; //constructor public animation() { scenes = new ArrayList(); totalTime = 0; start(); } //add scene to ArrayLisy and set time for each scene public synchronized void addScene(Image i, long t) { totalTime += t; scenes.add(new OneScene(i, totalTime)); } public synchronized void start() { movieTime = 0; sceneIndex = 0; } //change scenes public synchronized void update(long timePassed) { if (scenes.size() > 1) { movieTime += timePassed; if (movieTime >= totalTime) { movieTime = 0; sceneIndex = 0; } while (movieTime > getScene(sceneIndex).endTime) { sceneIndex++; } } } //get animations current scene(aka image) public synchronized Image getImage() { if (scenes.size() == 0) { return null; } else { return getScene(sceneIndex).pic; } } //get scene private OneScene getScene(int x) { return (OneScene) scenes.get(x); } //Private Inner CLASS////////////// private class OneScene { Image pic; long endTime; public OneScene(Image pic, long endTime) { this.pic = pic; this.endTime = endTime; } } } class Sprite { private animation a; private float x; private float y; private float vx; private float vy; //Constructor public Sprite(animation a) { this.a = a; } //change position public void update(long timePassed) { x += vx * timePassed; y += vy * timePassed; } public void startAnimation(long timePassed) { a.update(timePassed); } //get x position public float getX() { return x; } //get y position public float getY() { return y; } //set x public void setX(float x) { this.x = x; } //set y public void setY(float y) { this.y = y; } //get sprite width public int getWidth() { return a.getImage().getWidth(null); } //get sprite height public int getHeight() { return a.getImage().getHeight(null); } //get horizontal velocity public float getVelocityX() { return vx; } //get vertical velocity public float getVelocityY() { return vx; } //set horizontal velocity public void setVelocityX(float vx) { this.vx = vx; } //set vertical velocity public void setVelocityY(float vy) { this.vy = vy; } //get sprite / image public Image getImage() { return a.getImage(); } } class ScreenManager { private GraphicsDevice vc; public ScreenManager() { GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); vc = e.getDefaultScreenDevice(); } //get all compatible DM public DisplayMode[] getCompatibleDisplayModes() { return vc.getDisplayModes(); } //compares DM passed into vc DM and see if they match public DisplayMode findFirstCompatibleMode(DisplayMode modes[]) { DisplayMode goodModes[] = vc.getDisplayModes(); for (int x = 0; x < modes.length; x++) { for (int y = 0; y < goodModes.length; y++) { if (displayModesMatch(modes[x], goodModes[y])) { return modes[x]; } } } return null; } //get current DM public DisplayMode getCurrentDisplayMode() { return vc.getDisplayMode(); } //checks if two modes match each other public boolean displayModesMatch(DisplayMode m1, DisplayMode m2) { if (m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()) { return false; } if (m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()) { return false; } if (m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()) { return false; } return true; } //make frame full screen public void setFullScreen(DisplayMode dm) { JFrame f = new JFrame(); f.setUndecorated(true); f.setIgnoreRepaint(true); f.setResizable(false); vc.setFullScreenWindow(f); if (dm != null && vc.isDisplayChangeSupported()) { try { vc.setDisplayMode(dm); } catch (Exception ex) { } } f.createBufferStrategy(2); } //sets graphics object = this return public Graphics2D getGraphics() { Window w = vc.getFullScreenWindow(); if (w != null) { BufferStrategy s = w.getBufferStrategy(); return (Graphics2D) s.getDrawGraphics(); } else { return null; } } //updates display public void update() { Window w = vc.getFullScreenWindow(); if (w != null) { BufferStrategy s = w.getBufferStrategy(); if (!s.contentsLost()) { s.show(); } } } //returns full screen window public Window getFullScreenWindow() { return vc.getFullScreenWindow(); } //get width of window public int getWidth() { Window w = vc.getFullScreenWindow(); if (w != null) { return w.getWidth(); } else { return 0; } } //get height of window public int getHieght() { Window w = vc.getFullScreenWindow(); if (w != null) { return w.getHeight(); } else { return 0; } } //get out of full screen public void restoreScreen() { Window w = vc.getFullScreenWindow(); if (w != null) { w.dispose(); } vc.setFullScreenWindow(null); } //create image compatible with monitor public BufferedImage createCopatibleImage(int w, int h, int t) { Window win = vc.getFullScreenWindow(); if (win != null) { GraphicsConfiguration gc = win.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, t); } return null; } }

    Read the article

  • Android - Key Dispatching Timed Out

    - by Donal Rafferty
    In my Android application I am getting a very strange crash, when I press a button (Image) on my UI the entire application freezes and after a couple of seconds I getthe dreaded force close dialog appearing. Here is what gets printed in the log: WARN/WindowManager(88): Key dispatching timed out sending to package name/Activity WARN/WindowManager(88): Dispatch state: {{KeyEvent{action=1 code=5 repeat=0 meta=0 scancode=231 mFlags=8} to Window{432bafa0 com.android.launcher/com.android.launcher.Launcher paused=false} @ 1281611789339 lw=Window{432bafa0 com.android.launcher/com.android.launcher.Launcher paused=false} lb=android.os.BinderProxy@431ee8e8 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window{4335fc58 package name/Activity paused=false}}} WARN/WindowManager(88): Current state: {{null to Window{4335fc58 package name/Activity paused=false} @ 1281611821193 lw=Window{4335fc58 package name/Activity paused=false} lb=android.os.BinderProxy@434c9bd0 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window{4335fc58 package name/Activity paused=false}}} INFO/ActivityManager(88): ANR in process: package name (last in package name) INFO/ActivityManager(88): Annotation: keyDispatchingTimedOut INFO/ActivityManager(88): CPU usage: INFO/ActivityManager(88): Load: 5.18 / 5.1 / 4.75 INFO/ActivityManager(88): CPU usage from 7373ms to 1195ms ago: INFO/ActivityManager(88): package name: 6% = 1% user + 5% kernel / faults: 7 minor INFO/ActivityManager(88): system_server: 5% = 4% user + 1% kernel / faults: 27 minor INFO/ActivityManager(88): tiwlan_wifi_wq: 3% = 0% user + 3% kernel INFO/ActivityManager(88): mediaserver: 0% = 0% user + 0% kernel INFO/ActivityManager(88): logcat: 0% = 0% user + 0% kernel INFO/ActivityManager(88): TOTAL: 12% = 5% user + 6% kernel + 0% softirq INFO/ActivityManager(88): Removing old ANR trace file from /data/anr/traces.txt INFO/Process(88): Sending signal. PID: 1812 SIG: 3 INFO/dalvikvm(1812): threadid=7: reacting to signal 3 INFO/dalvikvm(1812): Wrote stack trace to '/data/anr/traces.txt' This is the code for the Button (Image): findViewById(R.id.endcallimage).setOnClickListener(new OnClickListener() { public void onClick(View v) { mNotificationManager.cancel(2); Log.d("Handler", "Endcallimage pressed"); if(callConnected) elapsedTimeBeforePause = SystemClock.elapsedRealtime() - stopWatch.getBase(); try { serviceBinder.endCall(lineId); } catch (RemoteException e) { e.printStackTrace(); } dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.FLAG_SOFT_KEYBOARD)); dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)); } }); If I comment the following out the pressing of the button (image) doesn't cause the crash: try { serviceBinder.endCall(lineId); } catch (RemoteException e) { e.printStackTrace(); } The above code calls down through several levels of the app and into the native layer (NDK), could the call passing through several objects be leading to the force close? It seems unlikely as several other buttons do the same without issue. How about the native layer? Could some code I've built with the NDK be causing the issue? Any other ideas as to what the cause of the issue might be?

    Read the article

  • using Unity Android In a sub view and add actionbar and style

    - by aeroxr1
    I exported a simple animation from Unity3D (version 4.5) in android project. With eclipse I modified the manifest and added another activity. In this activity I put a button that it makes start the animation,and this is the result. The action bar appear in the main activity but it doesn't in the unity's activity :( How can I add the action bar and the style of the first activity to unity's animation activity ? This is the unity's activity's code : package com.rabidgremlin.tut.redcube; import android.app.NativeActivity; import android.content.res.Configuration; import android.graphics.PixelFormat; import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import com.unity3d.player.UnityPlayer; public class UnityPlayerNativeActivity extends NativeActivity { protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code // Setup activity layout @Override protected void onCreate (Bundle savedInstanceState) { //requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); getWindow().takeSurface(null); //setTheme(android.R.style.Theme_NoTitleBar_Fullscreen); getWindow().setFormat(PixelFormat.RGB_565); mUnityPlayer = new UnityPlayer(this); /*if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true)) getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); */ setContentView(mUnityPlayer); mUnityPlayer.requestFocus(); } // Quit Unity @Override protected void onDestroy () { mUnityPlayer.quit(); super.onDestroy(); } // Pause Unity @Override protected void onPause() { super.onPause(); mUnityPlayer.pause(); } // eliminiamo questa onResume() e proviamo a modificare la onResume() // Resume Unity @Override protected void onResume() { super.onResume(); mUnityPlayer.resume(); } // inseriamo qualche modifica qui // This ensures the layout will be correct. @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mUnityPlayer.configurationChanged(newConfig); } // Notify Unity of the focus change. @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mUnityPlayer.windowFocusChanged(hasFocus); } // For some reason the multiple keyevent type is not supported by the ndk. // Force event injection by overriding dispatchKeyEvent(). @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_MULTIPLE) return mUnityPlayer.injectEvent(event); return super.dispatchKeyEvent(event); } // Pass any events not handled by (unfocused) views straight to UnityPlayer @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); } /*API12*/ public boolean onGenericMotionEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); } } And this is the AndroidManifest.xml android:versionCode="1" android:versionName="1.0" > <!-- android:theme="@android:style/Theme.NoTitleBar"--> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:xlargeScreens="true" /> <application android:icon="@drawable/app_icon" android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light" > <activity android:name="com.rabidgremlin.tut.redcube.UnityPlayerNativeActivity" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale" android:label="@string/app_name" android:screenOrientation="portrait" > <!--android:launchMode="singleTask"--> <meta-data android:name="unityplayer.UnityActivity" android:value="true" /> <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" /> </activity> <activity android:name="com.rabidgremlin.tut.redcube.MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="19" /> <uses-feature android:glEsVersion="0x00020000" /> </manifest>

    Read the article

  • simulate backspace key with java.awt.Robot

    - by Tyler
    There seems to be an issue simulating the backspace key with java.awt.Robot. This thread seems to confirm this but it does not propose a solution. This works: Robot rob = new Robot(); rob.keyPress(KeyEvent.VK_A); rob.keyRelease(KeyEvent.VK_A); This doesn't: Robot rob = new Robot(); rob.keyPress(KeyEvent.VK_BACK_SPACE); rob.keyRelease(KeyEvent.VK_BACK_SPACE); Any ideas? Thanks!

    Read the article

  • android keylistener losing key taps

    - by miannelle
    I am using a keylistener to get key taps. The problem is that once you tap the delete key, the next key tap is not registering. The key tap after that keeps working. If I tap 2 deletes in a row, they work, just no other keys. They just disappear. I put in a log test before the "if (keycode" section and it shows nothing after the first delete is pressed, unless it is another delete. I am using the following code (Thanks Shawn).: itemPrice.setKeyListener(new CalculatorKeyListener()); itemPrice.setRawInputType(Configuration.KEYBOARD_12KEY); class CalculatorKeyListener extends NumberKeyListener { public int getInputType() { return InputType.TYPE_CLASS_NUMBER; } @Override public boolean onKeyDown(View view, Editable content, int keyCode, KeyEvent event) { if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) { digitPressed(keyCode - KeyEvent.KEYCODE_0); } else if (keyCode == KeyEvent.KEYCODE_DEL) { deletePressed(); } return true; } @Override protected char[] getAcceptedChars() { return new char[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; } } With this problem the keylistener provides no value to me. There must be something that I am missing. Thanks,

    Read the article

  • Base class -> Derived class and vice-versa conversions in C++

    - by Ivan Nikolaev
    Hi! I have the following example code: #include <iostream> #include <string> using namespace std; class Event { public: string type; string source; }; class KeyEvent : public Event { public: string key; string modifier; }; class MouseEvent : public Event { public: string button; int x; int y; }; void handleEvent(KeyEvent e) { if(e.key == "ENTER") cout << "Hello world! The Enter key was pressed ;)" << endl; } Event generateEvent() { KeyEvent e; e.type = "KEYBOARD_EVENT"; e.source = "Keyboard0"; e.key = "SPACEBAR"; e.modifier = "none"; return e; } int main() { KeyEvent e = generateEvent(); return 0; } I can't compile it, G++ throws an error of kind: main.cpp: In function 'int main()': main.cpp:47:29: error: conversion from 'Event' to non-scalar type 'KeyEvent' requested I know that the error is obvious for C++ guru's, but I can't understand why I can't do the conversion from base class object to derived one. Can someone suggest me the solution of the problem that I have? Thx in advice

    Read the article

  • Android: Unregister camera button

    - by niko
    Hi, I tried to bind some actions to a camera button: videoPreview.setOnKeyListener(new OnKeyListener(){ public boolean onKey(View v, int keyCode, KeyEvent event){ if(event.getAction() == KeyEvent.ACTION_DOWN) { switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: //videoPreview.onCapture(settings); onCaptureButton(); ... } } return false; } }); Pressing the button however the application crashes because the original Camera application starts. Does anyone know how to prevent Camera application start when the camera button is pressed?

    Read the article

  • Thread not behaving correctly

    - by ivor
    Hello, I wonder if anyone can help me to understand where I could be going wrong with this code; Basically I'm working on a turorial and calling the class below from another class - and it is getting the following error; Exception in thread "Thread-1" java.lang.NullPointerException at org.newdawn.spaceinvaders.TCPChat.run(TCPChat.java:322) at java.lang.Thread.run(Unknown Source) I realise the error is beibg flagged in another class- but I have tested the other class with a small class which sets up a separate thread - and it works fine, but as soon as I try and implement a new thread in this class - it causes all sorts of problems. Am I setting up the thread correctly in this class? Basically I can set up a thread in this class, with a test loop and it's fine, but when I bring in the functionality of the rest of the game it sometimes hangs, or does not display at all. Any suggestions on where I could be going wrong would be greatly appreciated. Thanks for looking. package org.newdawn.spaceinvaders; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Scanner; import java.awt.*;//maybe not needed import javax.swing.*;//maybenot needed import java.util.Random; //import java.io.*; /** * The main hook of our game. This class with both act as a manager * for the display and central mediator for the game logic. * * Display management will consist of a loop that cycles round all * entities in the game asking them to move and then drawing them * in the appropriate place. With the help of an inner class it * will also allow the player to control the main ship. * * As a mediator it will be informed when entities within our game * detect events (e.g. alient killed, played died) and will take * appropriate game actions. * * @author Kevin Glass */ public class Game extends Canvas implements Runnable{ /** The stragey that allows us to use accelerate page flipping */ private BufferStrategy strategy; /** True if the game is currently "running", i.e. the game loop is looping */ private boolean gameRunning = true; /** The list of all the entities that exist in our game */ private ArrayList entities = new ArrayList(); /** The list of entities that need to be removed from the game this loop */ private ArrayList removeList = new ArrayList(); /** The entity representing the player */ private Entity ship; /** The speed at which the player's ship should move (pixels/sec) */ private double moveSpeed = 300; /** The time at which last fired a shot */ private long lastFire = 0; /** The interval between our players shot (ms) */ private long firingInterval = 500; /** The number of aliens left on the screen */ private int alienCount; /** The number of levels progressed */ private double levelCount; /** high score for the user */ private int highScore; /** high score for the user */ private String player = "bob"; //private GetUserInput getPlayer; /** The list of entities that need to be removed from the game this loop */ /** The message to display which waiting for a key press */ private String message = ""; /** True if we're holding up game play until a key has been pressed */ private boolean waitingForKeyPress = true; /** True if the left cursor key is currently pressed */ private boolean leftPressed = false; /** True if the right cursor key is currently pressed */ private boolean rightPressed = false; /** True if we are firing */ private boolean firePressed = false; /** True if game logic needs to be applied this loop, normally as a result of a game event */ private boolean logicRequiredThisLoop = false; //private Thread cThread = new Thread(this); //public Thread t = new Thread(this); //private Thread g = new Thread(this); void setHighscore(int setHS) { highScore = setHS; } public int getHighscore() { return highScore; } public void setPlayer(String setPlayer) { player = setPlayer; } public String getPlayer() { return player; } public void run() { //setup(); System.out.println("hello im running bob"); /*int count = 1; do { System.out.println("Count is: " + count); count++; try{Thread.sleep(1);} catch(InterruptedException e){} } while (count <= 2000000);*/ //Game g =new Game(); //Game g = this; // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //setup(); //this.gameLoop(); //try{thread.sleep(1);} //catch{InterruptedException e} } /** * Construct our game and set it running. */ public Game () { //Thread t = new Thread(this);//set up new thread for invaders game //t.run();//run the run method of the game //Game g =new Game(); //setup(); //Thread t = new Thread(this); //thread.start(); //SwingUtilities.invokeLater(this); Thread er = new Thread(this); er.start(); } public void setup(){ //initialise highscore setHighscore(0); // create a frame to contain our game JFrame container = new JFrame("Space Invaders 101"); // get hold the content of the frame and set up the resolution of the game JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(800,600)); //panel.setLayout(null); // setup our canvas size and put it into the content of the frame setBounds(0,0,800,600); panel.add(this); // Tell AWT not to bother repainting our canvas since we're // going to do that our self in accelerated mode setIgnoreRepaint(true); // finally make the window visible container.pack(); container.setResizable(false); container.setVisible(true); // add a listener to respond to the user closing the window. If they // do we'd like to exit the game container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //cThread.interrupt(); System.exit(0); } }); // add a key input system (defined below) to our canvas // so we can respond to key pressed addKeyListener(new KeyInputHandler()); // request the focus so key events come to us requestFocus(); // create the buffering strategy which will allow AWT // to manage our accelerated graphics createBufferStrategy(2); strategy = getBufferStrategy(); // initialise the entities in our game so there's something // to see at startup initEntities(); } /** * Start a fresh game, this should clear out any old data and * create a new set. */ private void startGame() { // clear out any existing entities and intialise a new set entities.clear(); initEntities(); //initialise highscore setHighscore(0); // blank out any keyboard settings we might currently have leftPressed = false; rightPressed = false; firePressed = false; } /** * Initialise the starting state of the entities (ship and aliens). Each * entitiy will be added to the overall list of entities in the game. */ //private void initEntities() { public void initEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = 1.02; for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){ //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",100+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } } //private void initEntities() { public void initAlienEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal //ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side //entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = levelCount + 0.10;//this increases the speed on every level for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){//randome check to show alien //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",-250+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } advanceAlienSpeed(levelCount); } /** * Notification from a game entity that the logic of the game * should be run at the next opportunity (normally as a result of some * game event) */ public void updateLogic() { logicRequiredThisLoop = true; } /** * Remove an entity from the game. The entity removed will * no longer move or be drawn. * * @param entity The entity that should be removed */ public void removeEntity(Entity entity) { removeList.add(entity); } /** * Notification that the player has died. */ public void notifyDeath() { message = "Oh no! They got you, try again?"; waitingForKeyPress = true; } /** * Notification that the player has won since all the aliens * are dead. */ public void notifyWin() { message = "Well done! You Win!"; waitingForKeyPress = true; } /** * Notification that an alien has been killed */ public void notifyAlienKilled() { // reduce the alient count, if there are none left, the player has won! alienCount--; if (alienCount == 0) { //notifyWin();win not relevant here... this.initAlienEntities();//call fresh batch of aliens } // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens advanceAlienSpeed(1.30); } public void advanceAlienSpeed(double speed) { // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); if (entity instanceof AlienEntity) { // speed up by 2% entity.setHorizontalMovement(entity.getHorizontalMovement() * speed); //entity.setVerticalMovement(entity.getVerticalMovement() * 1.02); } } } /** * Attempt to fire a shot from the player. Its called "try" * since we must first check that the player can fire at this * point, i.e. has he/she waited long enough between shots */ public void tryToFire() { // check that we have waiting long enough to fire if (System.currentTimeMillis() - lastFire < firingInterval) { return; } // if we waited long enough, create the shot entity, and record the time. lastFire = System.currentTimeMillis(); ShotEntity shot = new ShotEntity(this,"sprites/shot.gif",ship.getX()+10,ship.getY()-30); entities.add(shot); } /** * The main game loop. This loop is running during all game * play as is responsible for the following activities: * <p> * - Working out the speed of the game loop to update moves * - Moving the game entities * - Drawing the screen contents (entities, text) * - Updating game events * - Checking Input * <p> */ public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); // keep looping round til the game ends while (gameRunning) { // work out how long its been since the last update, this // will be used to calculate how far the entities should // move this loop long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); // Get hold of a graphics context for the accelerated // surface and blank it out Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,800,600); // cycle round asking each entity to move itself if (!waitingForKeyPress) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } } // cycle round drawing all the entities we have in the game for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } // brute force collisions, compare every entity against // every other entity. If any of them collide notify // both entities that the collision has occured for (int p=0;p<entities.size();p++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); } } } // remove any entity that has been marked for clear up entities.removeAll(removeList); removeList.clear(); // if a game event has indicated that game logic should // be resolved, cycle round every entity requesting that // their personal logic should be considered. if (logicRequiredThisLoop) { //g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } // if we're waiting for an "any key" press then draw the // current message //show highscore at top of screen //show name at top of screen g.setColor(Color.white); g.drawString("Player : "+getPlayer()+" : Score : "+getHighscore(),20,20); if (waitingForKeyPress) { g.setColor(Color.white); g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250); g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); } // finally, we've completed drawing so clear up the graphics // and flip the buffer over g.dispose(); strategy.show(); // resolve the movement of the ship. First assume the ship // isn't moving. If either cursor key is pressed then // update the movement appropraitely ship.setVerticalMovement(0);//set to vertical movement if ((leftPressed) && (!rightPressed)) { ship.setVerticalMovement(-moveSpeed);//**took out setHorizaontalMOvement } else if ((rightPressed) && (!leftPressed)) { ship.setVerticalMovement(moveSpeed);//**took out setHorizaontalMOvement } // if we're pressing fire, attempt to fire if (firePressed) { tryToFire(); } // finally pause for a bit. Note: this should run us at about // 100 fps but on windows this might vary each loop due to // a bad implementation of timer try { Thread.sleep(10); } catch (Exception e) {} } } /** * A class to handle keyboard input from the user. The class * handles both dynamic input during game play, i.e. left/right * and shoot, and more static type input (i.e. press any key to * continue) * * This has been implemented as an inner class more through * habbit then anything else. Its perfectly normal to implement * this as seperate class if slight less convienient. * * @author Kevin Glass */ private class KeyInputHandler extends KeyAdapter { /** The number of key presses we've had while waiting for an "any key" press */ private int pressCount = 1; /** * Notification from AWT that a key has been pressed. Note that * a key being pressed is equal to being pushed down but *NOT* * released. Thats where keyTyped() comes in. * * @param e The details of the key that was pressed */ public void keyPressed(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "press" if (waitingForKeyPress) { return; } // if (e.getKeyCode() == KeyEvent.VK_LEFT) { ////leftPressed = true; ///} //// if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //rightPressed = true; if (e.getKeyCode() == KeyEvent.VK_UP) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = true; } } /** * Notification from AWT that a key has been released. * * @param e The details of the key that was released */ public void keyReleased(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "released" if (waitingForKeyPress) { return; } if (e.getKeyCode() == KeyEvent.VK_UP) {//changed from VK_LEFT leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_DOWN) {//changed from VK_RIGHT rightPressed = false; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = false; } } /** * Notification from AWT that a key has been typed. Note that * typing a key means to both press and then release it. * * @param e The details of the key that was typed. */ public void keyTyped(KeyEvent e) { // if we're waiting for a "any key" type then // check if we've recieved any recently. We may // have had a keyType() event from the user releasing // the shoot or move keys, hence the use of the "pressCount" // counter. if (waitingForKeyPress) { if (pressCount == 1) { // since we've now recieved our key typed // event we can mark it as such and start // our new game waitingForKeyPress = false; startGame(); pressCount = 0; } else { pressCount++; } } // if we hit escape, then quit the game if (e.getKeyChar() == 27) { //cThread.interrupt(); System.exit(0); } } } /** * The entry point into the game. We'll simply create an * instance of class which will start the display and game * loop. * * @param argv The arguments that are passed into our game */ //public static void main(String argv[]) { //Game g =new Game(); // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //g.gameLoop(); //} }

    Read the article

  • Android: Enable selection in webkit

    - by tacone
    Hello, I'am looking for a way to have a webview content selectable in the very same way as the stock browser does. user long presses the text the whole word is selected two pins appear at the word's boundary allowing the user to stretch/shrink the selection. I should note that Dolphin HD shows exactly the same text select functionality as the default browser (same icons, animation, etc), so it really should be possible. But I can't figure out how. Until now, all i found was this function, which kind of work, but doesn't allow the user to expand/shrink the selection. public void selectAndCopyText() { try { KeyEvent shiftPressEvent = new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0); shiftPressEvent.dispatch(mWebView); } catch (Exception e) { throw new AssertionError(e); } }

    Read the article

  • What am I doing wrong with this use of StructLayout( LayoutKind.Explicit ) when calling a PInvoke st

    - by csharptest.net
    The following is a complete program. It works fine as long as you don't uncomment the '#define BROKEN' at the top. The break is due to a PInvoke failing to marshal a union correctly. The INPUT_RECORD structure in question has a number of substructures that might be used depending on the value in EventType. What I don't understand is that when I define only the single child structure of KEY_EVENT_RECORD it works with the explicit declaration at offset 4. But when I add the other structures at the same offset the structure's content get's totally hosed. //UNCOMMENT THIS LINE TO BREAK IT: //#define BROKEN using System; using System.Runtime.InteropServices; class ConIOBroken { static void Main() { int nRead = 0; IntPtr handle = GetStdHandle(-10 /*STD_INPUT_HANDLE*/); Console.Write("Press the letter: 'a': "); INPUT_RECORD record = new INPUT_RECORD(); do { ReadConsoleInputW(handle, ref record, 1, ref nRead); } while (record.EventType != 0x0001/*KEY_EVENT*/); Assert.AreEqual((short)0x0001, record.EventType); Assert.AreEqual(true, record.KeyEvent.bKeyDown); Assert.AreEqual(0x00000000, record.KeyEvent.dwControlKeyState & ~0x00000020);//strip num-lock and test Assert.AreEqual('a', record.KeyEvent.UnicodeChar); Assert.AreEqual((short)0x0001, record.KeyEvent.wRepeatCount); Assert.AreEqual((short)0x0041, record.KeyEvent.wVirtualKeyCode); Assert.AreEqual((short)0x001e, record.KeyEvent.wVirtualScanCode); } static class Assert { public static void AreEqual(object x, object y) { if (!x.Equals(y)) throw new ApplicationException(); } } [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool ReadConsoleInputW(IntPtr hConsoleInput, ref INPUT_RECORD lpBuffer, int nLength, ref int lpNumberOfEventsRead); [StructLayout(LayoutKind.Explicit)] public struct INPUT_RECORD { [FieldOffset(0)] public short EventType; //union { [FieldOffset(4)] public KEY_EVENT_RECORD KeyEvent; #if BROKEN [FieldOffset(4)] public MOUSE_EVENT_RECORD MouseEvent; [FieldOffset(4)] public WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent; [FieldOffset(4)] public MENU_EVENT_RECORD MenuEvent; [FieldOffset(4)] public FOCUS_EVENT_RECORD FocusEvent; //} #endif } [StructLayout(LayoutKind.Sequential)] public struct KEY_EVENT_RECORD { public bool bKeyDown; public short wRepeatCount; public short wVirtualKeyCode; public short wVirtualScanCode; public char UnicodeChar; public int dwControlKeyState; } [StructLayout(LayoutKind.Sequential)] public struct MOUSE_EVENT_RECORD { public COORD dwMousePosition; public int dwButtonState; public int dwControlKeyState; public int dwEventFlags; }; [StructLayout(LayoutKind.Sequential)] public struct WINDOW_BUFFER_SIZE_RECORD { public COORD dwSize; } [StructLayout(LayoutKind.Sequential)] public struct MENU_EVENT_RECORD { public int dwCommandId; } [StructLayout(LayoutKind.Sequential)] public struct FOCUS_EVENT_RECORD { public bool bSetFocus; } [StructLayout(LayoutKind.Sequential)] public struct COORD { public short X; public short Y; } } UPDATE: For those worried about the struct declarations themselves: bool is treated as a 32-bit value the reason for offset(4) on the data is to allow for the 32-bit structure alignment which prevents the union from beginning at offset 2. Again, my problem isn't making PInvoke work at all, it's trying to figure out why these additional structures (supposedly at the same offset) are fowling up the data by simply adding them.

    Read the article

  • android set hidden the keybord on press enter (in a EditText)

    - by user119333
    Hi, When my user press "ENTER" on the virtual android "user validate entry!" keybord my keybord stay visible ! (Why?) Here my Java code... private void initTextField() { entryUser = (EditText) findViewById(R.id.studentEntrySalary); entryUser.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: userValidateEntry(); return true; } } return true; } }); } private void userValidateEntry() { System.out.println("user validate entry!"); } ... here my View <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <EditText android:id="@+id/studentEntrySalary" android:text="Foo" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> Maybe something wrong on my virtual device ?

    Read the article

  • ANDROID. Emulate Hardware Keys with an IME. Doesn't work with Dialog and Spinner

    - by shutdown11
    I have understand that the only way to inject KeyEvents in the Android System is to implement an Input Method. I have created my IME with the purpose to control from remote the device. I emulate the hardware keys using the method private void keyDownUp(int keyEventCode) { getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode)); getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_UP, keyEventCode)); } in my class that extends InputMethodService. It works fine until an AlertDialog, or the menu of a Spinner comes in foreground. Also the windows that appears when the Menu key is problematic. My IME can't get focus on them, and the keyevents are sent to the activity behind them. Using hardware keys, the Dialog get the focus and you can select the botton on the Dialog. How can i emulate that, using the IME(or anything else)?

    Read the article

  • How to send KeyEvents through an input method service to a Dialog, or a Spinner menu?

    - by shutdown11
    I'm trying to implement an input method service that receives intents sent by a remote client, and in response to those sends an appropriate KeyEvent. I'm using in the input method service this method private void keyDownUp(int keyEventCode) { getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode)); getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_UP, keyEventCode)); } to send KeyEvents as in the Simple Sofykeyboard Sample, and it works in the home, in Activities... but it doesn't works when a Dialog or the menu of a Spinner is in foreground. The events is sent to the parent activity behind the Dialog. Is there any way to send keys and control the device like using the hardware keys from an input method? Better explanation on what I'm trying to do: I am kind of writng an Input Method that allows to control the device from remote. I write in a client (a java application on my desktop pc) a command (for example "UP"), a server on the device with sendBroadcast() sends the intent with the information, and a receiver in the input method gets it and call keyDownUp with the keycode of the DPAD_UP key. It generally works, but when I go to an app that shows a dialog, the keyDownUp method don't sends the key event to the dialog, for example for select the yes or not buttons, but it keeps to control the activty behind the Dialog.

    Read the article

  • Is it possible to create a Service that listens for hardware key presses?

    - by VoteBrian
    I'd like to run an Android background service that will act as a keylistener from the home screen or when the phone is asleep. Is this possible? From semi-related examples online, I put together the following service, but get the error, "onKeyDown is undefined for the type Service" public class ServiceName extends Service { @Override public void onCreate() { //Stuff } public IBinder onBind(Intent intent) { //Stuff return null; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { switch(keyCode) { case KeyEvent.KEYCODE_A: //Stuff return true; case KeyEvent.KEYCODE_B: //Stuff return true; //etc. } } return super.onKeyDown(keyCode, event); } } I realize Android defaults to the search bar when you type from the home screen, but this really is just for a very particular use. I don't really expect to distribute this. Also, it'd be nice to use the camera button to wake the phone.

    Read the article

  • How to move image in Applet?

    - by user1609804
    I want to move the character left, right up, and down in applet, but it is not moving at all. here is my code, help please import javax.swing.JPanel; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import java.applet.*; import java.awt.event.*; import java.awt.*; public class drawCenter extends Applet { private int x,y;// the x and y of the position of the player private BufferedImage image, pos; public void init( ) { try { image = ImageIO.read(new File("pokemonCenter.png")); pos = ImageIO.read(new File("player/maleInGame.png")); } catch (IOException ex) { } x = 150; y = 171; } public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); switch( keyCode ) { case KeyEvent.VK_UP: if( y>0 ) { y=y-19; repaint(); } break; case KeyEvent.VK_DOWN: if( y<171 ) { y=y+19; repaint(); } break; case KeyEvent.VK_LEFT:if( x>0 ) { x=x-15; repaint(); } break; case KeyEvent.VK_RIGHT:if( x<285 ) { x=x+15; repaint(); } break; } e.consume(); } public void keyReleased(){ } public void paint( Graphics g ) { g.drawImage(image, 0, 0, null); g.drawImage(pos, x, y, null); } }

    Read the article

  • 2D game - Missile shooting problem on Android

    - by Niksa
    Hello, I have to make a tank that sits still but moves his turret and shoots missiles. As this is my first Android application ever and I haven't done any game development either, I've come across a few problems... Now, I did the tank and the moving turret once I read the Android tutorial for the LunarLander sample code. So this code is based on the LunarLander code. But I'm having trouble doing the missile firing then SPACE button is being pressed. private void doDraw(Canvas canvas) { canvas.drawBitmap(backgroundImage, 0, 0, null); // draws the tank canvas.drawBitmap(tank, x_tank, y_tank, new Paint()); // draws and rotates the tank turret canvas.rotate((float) mHeading, (float) x_turret + mTurretWidth, y_turret); canvas.drawBitmap(turret, x_turret, y_turret, new Paint()); // draws the grenade that is a regular circle from ShapeDrawable class bullet.setBounds(x_bullet, y_bullet, x_bullet + width, y_bullet + height); bullet.draw(canvas); } UPDATE GAME method private void updateGame() throws InterruptedException { long now = System.currentTimeMillis(); if (mLastTime > now) return; double elapsed = (now - mLastTime) / 1000.0; mLastTime = now; // dUP and dDown, rotates the turret from 0 to 75 degrees. if (dUp) mHeading += 1 * (PHYS_SLEW_SEC * elapsed); if (mHeading >= 75) mHeading = 75; if (dDown) mHeading += (-1) * (PHYS_SLEW_SEC * elapsed); if (mHeading < 0) mHeading = 0; if (dSpace){ // missile Logic, a straight trajectorie for now x_bullet -= 1; y_bullet -= 1; //doesn't work, has to be updated every pixel or what? } boolean doKeyDown(int keyCode, KeyEvent msg) { boolean handled = false; synchronized (mSurfaceHolder) { if (keyCode == KeyEvent.KEYCODE_SPACE){ dSpace = true; handled = true; } if (keyCode == KeyEvent.KEYCODE_DPAD_UP){ dUp = true; handled = true; } if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN){ dDown = true; handled = true; } return handled; } } } a method run that runs the game... public void run() { while (mRun) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { if (mMode == STATE_RUNNING) updateGame(); doDraw(c); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } } So the question would be, how do I make that the bullet is fired on a single SPACE key press from the turret to the end of the screen? Could you help me out here, I seem to be in the dark here... Thanks, Niksa

    Read the article

  • code for TouchPad works, but not for DPAD ...please help me to fix this..

    - by Chandan
    package org.coe.twoD; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; //import android.graphics.Path; import android.graphics.Rect; //import android.graphics.RectF; import android.os.Bundle; //import android.util.Log; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; public class TwoD extends Activity implements OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View draw2d = findViewById(R.id.draw_button); draw2d.setOnClickListener(this); } public void onClick(View v) { if (R.id.draw_button == v.getId()) { setContentView(new draw2D(this)); } } public class draw2D extends View { private static final String TAG = "Sudoku"; private float width; // width of one tile private float height; // height of one tile private int selX; // X index of selection private int selY; // Y index of selection private final Rect selRect = new Rect(); public draw2D(Context context) { super(context); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { width = w / 9f; height = h / 9f; getRect(selX, selY, selRect); Log.d(TAG, "onSizeChanged: width " + width + ", height " + height); super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onDraw(Canvas canvas) { // Draw the background... Paint background = new Paint(); background.setColor(getResources().getColor(R.color.background)); canvas.drawRect(0, 0, getWidth(), getHeight(), background); // Draw the board... // Define colors for the grid lines Paint dark = new Paint(); dark.setColor(getResources().getColor(R.color.dark)); Paint hilite = new Paint(); hilite.setColor(getResources().getColor(R.color.hilite)); Paint light = new Paint(); light.setColor(getResources().getColor(R.color.light)); // Draw the minor grid lines for (int i = 0; i < 9; i++) { canvas.drawLine(0, i * height, getWidth(), i * height, light); canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1, hilite); canvas.drawLine(i * width, 0, i * width, getHeight(), light); canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(), hilite); } // Draw the major grid lines for (int i = 0; i < 9; i++) { if (i % 3 != 0) continue; canvas.drawLine(0, i * height, getWidth(), i * height, dark); canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1, hilite); canvas.drawLine(i * width, 0, i * width, getHeight(), dark); canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(), hilite); } /* * dark.setColor(Color.MAGENTA); Path circle= new Path(); * circle.addCircle(150, 150, 100, Path.Direction.CW); * canvas.drawPath(circle, dark); * * * Path rect=new Path(); * * RectF rectf= new RectF(150,200,250,300); rect.addRect(rectf, * Path.Direction.CW); canvas.drawPath(rect, dark); * * * canvas.drawRect(0, 0,250, 250, dark); * * * canvas.drawText("Hello", 200,200, dark); */ Paint selected = new Paint(); selected.setColor(Color.GREEN); canvas.drawRect(selRect, selected); } /* * public boolean onTouchEvent(MotionEvent event){ * if(event.getAction()!=MotionEvent.ACTION_DOWN) return * super.onTouchEvent(event); * select((int)(event.getX()/width),(int)(event.getY()/height)); * * * return true; } */ private void select(int x, int y) { invalidate(selRect); selX = Math.min(Math.max(x, 0), 8); selY = Math.min(Math.max(y, 0), 8); getRect(selX, selY, selRect); invalidate(selRect); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return super.onKeyUp(keyCode, event); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() != MotionEvent.ACTION_DOWN) return super.onTouchEvent(event); select((int) (event.getX() / width), (int) (event.getY() / height)); // game.showKeypadOrError(selX, selY); Log.d(TAG, "onTouchEvent: x " + selX + ", y " + selY); return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Log.d(TAG, "onKeyDown: keycode=" + keyCode + ", event=" + event); switch (keyCode) { case KeyEvent.KEYCODE_DPAD_UP: select(selX, selY - 1); break; case KeyEvent.KEYCODE_DPAD_DOWN: select(selX, selY + 1); break; case KeyEvent.KEYCODE_DPAD_LEFT: select(selX - 1, selY); break; case KeyEvent.KEYCODE_DPAD_RIGHT: select(selX + 1, selY); break; default: return super.onKeyDown(keyCode, event); } return true; } private void getRect(int x, int y, Rect rect) { rect.set((int) (x * width), (int) (y * height), (int) (x * width + width), (int) (y * height + height)); } } }

    Read the article

  • how to avoid flickering in awt [on hold]

    - by Ishanth
    import java.awt.event.*; import java.awt.*; class circle1 extends Frame implements KeyListener { public int a=300; public int b=70; public int pacx=360; public int pacy=270; public circle1() { setTitle("circle"); addKeyListener(this); repaint(); } public void paint(Graphics g) { g.fillArc (a, b, 60, 60,pacx,pacy); } public void keyPressed(KeyEvent e) { int key=e.getKeyCode(); System.out.println(key); if(key==38) { b=b-5; //move pacman up pacx=135;pacy=270; //packman mouth upside if(b==75&&a>=20||b==75&&a<=945) { b=b+5; } else { repaint(); } } else if(key==40) { b=b+5; //move pacman downside pacx=315; pacy=270; //packman mouth down if(b==645&&a>=20||b==645&&a<=940) { b=b-5; } else{ repaint(); } } else if(key==37) { a=a-5; //move pacman leftside pacx=227; pacy=270; //packman mouth left if(a==15&&b>=75||a==15&&b<=640) { a=a+5; } else { repaint(); } } else if(key==39) { a=a+5; //move pacman rightside pacx=42;pacy=270; //packman mouth right if(a==945&&a>=80||a==945&&b<=640) { a=a-5; } else { repaint(); } } } public void keyReleased(KeyEvent e){} public void keyTyped(KeyEvent e){} public static void main(String args[]) { circle1 c=new circle1(); c.setVisible(true); c.setSize(400,400); } }

    Read the article

  • how to use double buffering in awt? [on hold]

    - by Ishanth
    import java.awt.event.*; import java.awt.*; class circle1 extends Frame implements KeyListener { public int a=300; public int b=70; public int pacx=360; public int pacy=270; public circle1() { setTitle("circle"); addKeyListener(this); repaint(); } public void paint(Graphics g) { g.fillArc (a, b, 60, 60,pacx,pacy); } public void keyPressed(KeyEvent e) { int key=e.getKeyCode(); System.out.println(key); if(key==38) { b=b-5; //move pacman up pacx=135;pacy=270; //packman mouth upside if(b==75&&a>=20||b==75&&a<=945) { b=b+5; } else { repaint(); } } else if(key==40) { b=b+5; //move pacman downside pacx=315; pacy=270; //packman mouth down if(b==645&&a>=20||b==645&&a<=940) { b=b-5; } else{ repaint(); } } else if(key==37) { a=a-5; //move pacman leftside pacx=227; pacy=270; //packman mouth left if(a==15&&b>=75||a==15&&b<=640) { a=a+5; } else { repaint(); } } else if(key==39) { a=a+5; //move pacman rightside pacx=42;pacy=270; //packman mouth right if(a==945&&a>=80||a==945&&b<=640) { a=a-5; } else { repaint(); } } } public void keyReleased(KeyEvent e){} public void keyTyped(KeyEvent e){} public static void main(String args[]) { circle1 c=new circle1(); c.setVisible(true); c.setSize(400,400); } }

    Read the article

  • using Unity Android In a sub view and add style and actionbar

    - by aeroxr1
    I exported a simple animation from Unity3D (version 4.5) in android project. With eclipse I modified the manifest and added another activity. In this activity I put a button that it makes start the animation,and this is the result. The action bar appear in the main activity but it doesn't in the unity's activity :( This is the unity's activity's code : package com.rabidgremlin.tut.redcube; import android.app.NativeActivity; import android.content.res.Configuration; import android.graphics.PixelFormat; import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import com.unity3d.player.UnityPlayer; public class UnityPlayerNativeActivity extends NativeActivity { protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code // Setup activity layout @Override protected void onCreate (Bundle savedInstanceState) { //requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); getWindow().takeSurface(null); //setTheme(android.R.style.Theme_NoTitleBar_Fullscreen); getWindow().setFormat(PixelFormat.RGB_565); mUnityPlayer = new UnityPlayer(this); /*if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true)) getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); */ setContentView(mUnityPlayer); mUnityPlayer.requestFocus(); } // Quit Unity @Override protected void onDestroy () { mUnityPlayer.quit(); super.onDestroy(); } // Pause Unity @Override protected void onPause() { super.onPause(); mUnityPlayer.pause(); } // eliminiamo questa onResume() e proviamo a modificare la onResume() // Resume Unity @Override protected void onResume() { super.onResume(); mUnityPlayer.resume(); } // inseriamo qualche modifica qui // This ensures the layout will be correct. @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mUnityPlayer.configurationChanged(newConfig); } // Notify Unity of the focus change. @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mUnityPlayer.windowFocusChanged(hasFocus); } // For some reason the multiple keyevent type is not supported by the ndk. // Force event injection by overriding dispatchKeyEvent(). @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_MULTIPLE) return mUnityPlayer.injectEvent(event); return super.dispatchKeyEvent(event); } // Pass any events not handled by (unfocused) views straight to UnityPlayer @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); } /*API12*/ public boolean onGenericMotionEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); } } How can I add the action bar and the style of the first activity to unity's animation activity ?

    Read the article

  • JPopupMenu returning a null?

    - by Zenzen
    Ok so I'm working on an Eclipse plugin based on the JGraph example. The problem is I can't really get the "save" method to work, here's how the program works in short: - I have a DiagramEditor class with an init() method, where I create a GraphEditor object and call the createFrame() methord of that object. - GraphEditor extends the BasicGraphEditor (which extends JPanel), the createFrame() method returns a JFrame and has a line "frame.setJMenuBar(menuBar)" - the "menuBar" is an object variable, which is initialized in the BasicGraphEditor. Till here everything is cool, the problem is with the action listener which is supposed to save a file. To get the graph I need to get the GraphEditor component, so I do a Component component = (Component) e.getSource() whitch is the ActionEvent passed to that action listener and at that stage is the JMenuItem "save", then I get the parent which is the JPopupMenu, then I want to get that JPopupMenu's parent which should be the GraphEdiotor, but instead I get a null. Any idea why? Here's some source code: DiagramEditor.java: @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); this.diagram = ((DiagramEditorInput)input).getDiagram(); setPartName(this.diagram.getName()); gEditor = new GraphEditor(); gEditor.createFrame().setVisible(true); } BasicGraphEditor.java: public JFrame createFrame() { JFrame frame = new JFrame(); frame.getContentPane().add(this); frame.setJMenuBar(menuBar); //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(870, 640); return frame; } In the constructor: menuBar = new JMenuBar(); menu = new JMenu("File"); menu.setMnemonic(KeyEvent.VK_F); menuBar.add(menu); JMenuItem openMenuItem = new JMenuItem("Open", KeyEvent.VK_O); // ADD FILE OPENING //openMenuItem.addActionListener(menuListener); menu.add(openMenuItem); JMenuItem saveMenuItem = new JMenuItem("Save", new ImageIcon("/images/save.gif")); saveMenuItem.setMnemonic(KeyEvent.VK_S); saveMenuItem.addActionListener( new SaveAction(false) ); menu.add(saveMenuItem); // menu.add(new SaveAction(false)); JMenuItem saveMenuItemAs = new JMenuItem("SaveAs", new ImageIcon("/images/saveas.gif")); //saveMenuItemAs.setMnemonic(KeyEvent.VK_S); saveMenuItemAs.addActionListener( new SaveAction(true) ); menu.add(saveMenuItemAs); //menu.add(new SaveAction(true)); JMenuItem closeMenuItem = new JMenuItem("Close", KeyEvent.VK_C); closeMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } } ); menu.add(closeMenuItem);

    Read the article

  • JPopupMenu getParent() returning a null?

    - by Zenzen
    Ok so I'm working on an Eclipse plugin based on the JGraph example. The problem is I can't really get the "save" method to work, here's how the program works in short: - I have a DiagramEditor class with an init() method, where I create a GraphEditor object and call the createFrame() methord of that object. - GraphEditor extends the BasicGraphEditor (which extends JPanel), the createFrame() method returns a JFrame and has a line "frame.setJMenuBar(menuBar)" - the "menuBar" is an object variable, which is initialized in the BasicGraphEditor. Till here everything is cool, the problem is with the action listener which is supposed to save a file. To get the graph I need to get the GraphEditor component, so I do a Component component = (Component) e.getSource() whitch is the ActionEvent passed to that action listener and at that stage is the JMenuItem "save", then I get the parent which is the JPopupMenu, then I want to get that JPopupMenu's parent which should be the GraphEdiotor, but instead I get a null. Any idea why? Here's some source code: DiagramEditor.java: @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); this.diagram = ((DiagramEditorInput)input).getDiagram(); setPartName(this.diagram.getName()); gEditor = new GraphEditor(); gEditor.createFrame().setVisible(true); } BasicGraphEditor.java: public JFrame createFrame() { JFrame frame = new JFrame(); frame.getContentPane().add(this); frame.setJMenuBar(menuBar); //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(870, 640); return frame; } In the constructor: menuBar = new JMenuBar(); menu = new JMenu("File"); menu.setMnemonic(KeyEvent.VK_F); menuBar.add(menu); JMenuItem openMenuItem = new JMenuItem("Open", KeyEvent.VK_O); // ADD FILE OPENING //openMenuItem.addActionListener(menuListener); menu.add(openMenuItem); JMenuItem saveMenuItem = new JMenuItem("Save", new ImageIcon("/images/save.gif")); saveMenuItem.setMnemonic(KeyEvent.VK_S); saveMenuItem.addActionListener( new SaveAction(false) ); menu.add(saveMenuItem); // menu.add(new SaveAction(false)); JMenuItem saveMenuItemAs = new JMenuItem("SaveAs", new ImageIcon("/images/saveas.gif")); //saveMenuItemAs.setMnemonic(KeyEvent.VK_S); saveMenuItemAs.addActionListener( new SaveAction(true) ); menu.add(saveMenuItemAs); //menu.add(new SaveAction(true)); JMenuItem closeMenuItem = new JMenuItem("Close", KeyEvent.VK_C); closeMenuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } } ); menu.add(closeMenuItem);

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >