Please add keyboard focus events to swing calculator.  Its very argent.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
A frame with a calculator panel.
class CalculatorFrame1 extends JFrame
     private static final long serialVersionUID=0;
public CalculatorFrame1()
setTitle("Calculator");
Container contentPane = getContentPane();
CalculatorPanel panel = new CalculatorPanel();
contentPane.add(panel);
pack();
setVisible(true);
public static void main(String[] args)
CalculatorFrame1 frame = new CalculatorFrame1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.show();
A panel with calculator buttons and a result display.
class CalculatorPanel extends JPanel implements KeyListener
private static final long serialVersionUID=0;
private JTextField display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
public CalculatorPanel()
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
// add the display
display = new JTextField("");
// display.addKeyListener(this);
// display.addKeyListener(this);
add(display, BorderLayout.NORTH);
display.setFocusable(true);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// add the buttons in a 4 x 4 grid
panel = new JPanel();
panel.setLayout(new GridLayout(5, 4));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
addButton("Clear", command);
add(panel, BorderLayout.CENTER);
//this.addKeyListener(this);
Adds a button to the center panel.
@param label the button label
@param listener the button listener
private void addButton(String label, ActionListener listener)
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
This action inserts the button action string to the
end of the display text.
private class InsertAction implements ActionListener
public void actionPerformed(ActionEvent event)
String input = event.getActionCommand();
if (start)
display.setText("");
start = false;
display.setText(display.getText() + input);
This action executes the command that the button
action string denotes.
private class CommandAction implements ActionListener
public void actionPerformed(ActionEvent evt)
String command = evt.getActionCommand();
// System.out.println("The value clear"+command);
if (command.equals("Clear"))
          display.setText("");
          start = false;
else
if (start)
if (command.equals("-"))
display.setText(command);
start = false;
else
lastCommand = command;
else
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
Carries out the pending calculation.
@param x the value to be accumulated with the prior result.
public void calculate(double x)
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
display.setText("" + result);
public void keyTyped(KeyEvent e) {
     //You should only rely on the key char if the event
//is a key typed event.
     int id = e.getID();
     String keyString="";
     System.out.println("The value KeyEvent.KEY_TYPED"+KeyEvent.KEY_TYPED);
if (id == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
//System.out.println("The value c"+c);
if(c=='*' || c=='/' || c=='-'||c=='+' || c=='=')
     start = true;
else
     start = false;
     keyString = display.getText()+ c ;
     System.out.println("The value keyString"+keyString);
else {
calculate(Double.parseDouble(display.getText()));
start = true;
display.setText(keyString);
public void keyPressed(KeyEvent e) {
     //You should only rely on the key char if the event
//is a key typed event.
     String keyString;
int id = e.getID();
if (id == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
keyString = "key character = '" + c + "'";
} else {
int keyCode = e.getKeyCode();
keyString = "key code = " + keyCode
+ " ("
+ KeyEvent.getKeyText(keyCode)
+ ")";
display.setText("keyPressed:::"+keyString);**/
public void keyReleased(KeyEvent e) {
     //You should only rely on the key char if the event
//is a key typed event.
     String keyString;
int id = e.getID();
if (id == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
keyString = "key character = '" + c + "'";
} else {
int keyCode = e.getKeyCode();
keyString = "key code = " + keyCode
+ " ("
+ KeyEvent.getKeyText(keyCode)
+ ")";
display.setText("keyReleased:::"+keyString);**/
}

Please state why the question is urgent?
You where given a suggestion 7 minutes after you posted the question, yet it has been over 2 hours and you have not yet responded indicating whether the suggest helped or not.
So I gues its really not the urgent after all and therefore I will ignore the question.
By the way, learn how to use the "Code Formatting Tags" when you post code, so the code you post is actually readable.

Similar Messages

  • Hi please provide me an solution for this..its very important for me..plz

    march      april a/c     may     june     july
    30 dpd          100     105     110     120     120
    60dpd          80     75     80     90     85
    90 dd          60     65     60     70     70
    120 dpd          40     35     40     40     35
    current          500     550     600     650     750
    Total          780     830     890     970     1060
              what is the exact percentage?                    
              120/970+85/890+70/830+35/780=%     
    Here dpd is days per deliquency
    dpd are mesaures in hierarchy, and total no.of accounts in monthly wise ( here rows and columns both are hierarchys)
    ex: there are 100 accounts in the month of march for 30 dpd, and 105 accounts in the month of april for 30 dpd
    Now i want the percentage to be calculated as per the below mentioned format
    120/970+85/890+70/830+35/780=%
    here 120 is no.of accounts in july for 30dpd and 970 is total no of accounts for all days for june
    here 85 is no.of accounts in july for 30dpd and 890 is total no of accounts for all days for May
    here 70 is no.of accounts in july for 30dpd and 830 is total no of accounts for all days for april
    here 35 is no.of accounts in july for 30dpd and 780 is total no of accounts for all days for march

    There are so many things wrong with your questions that I lost my appetite to help:
    http://catb.org/esr/faqs/smart-questions.html#bespecific
    http://catb.org/esr/faqs/smart-questions.html#urgent
    http://catb.org/esr/faqs/smart-questions.html#writewell
    http://catb.org/esr/faqs/smart-questions.html#formats

  • Please add Armenian keyboard in iOS

    Many Armenians are using Apple devices and in iOS many years don't become Armenian keyboard PLEASE ADD ARMENIAN KEYBOARD IN iOS.

    Meanwhile you can use a cool html5 app, called Type Armenian (http://www.algrapps.com) to satisfy basic needs:). I have built it myself.
    However, native Armenian keyboard support would be awesome!
    Albert

  • Please Add thai Keyboard

    please Add thai Keyboard . I want it . pleaseeeeee

    You may currently have iOS 5. So go to Settings > General > Keyboards > International Keyboards > Add new Keyboard... > Thai. Go to home screen, and swipe your finger right and you will see Spotlight Search, then tap the globe on the keyboard '(+)'. You will see:
    ๅ / _ ภ ถ ุ  ึ ค ต จ จ ข ช
    ๆ ไ ำ พ ะ  ั  ี ร น ย บ ล
      ฟ ห ก ด เ  ้  ่ า ส ว ง
       ผ ป แ อ. ิ  ื ท ม ใ ฝ ฃ
    .?123 (+)      .?123
    When you hit Shift, you will see:
    + ๑ ๒ ๓ ๔  ู ฿ ๕ ๖ ๗ ๘ ๙
    ๐ " ฎ ฑ ธ ํ  ๊ ณ ฯ ญ ฐ ,
      ฤ ฆ ฏ โ ฌ  ็  ๋ ษ ศ ซ .
       ( ) ฉ ฮ  ฺ  ์ ? ฒ ฬ ฦ ฅ
    .?123 (+)       .?123
    You will also be lucky, because this keyboard has the most keys in the iPad history! I hope this helps!
    Cheers,
    iGabe

  • PLEASE ADD SWISS FRENCH KEYBOARD WITH FRENCH DICTIONNARY

    PLEASE ADD SWISS FRENCH KEYBOARD WITH FRENCH DICTIONNARY
    We are asking since July is that possible that someone HEAR that request ?
    Getting tired

    Apple won't hear it here. This is a user forum.
    Tell Apple:
    http://www.apple.com/feedback/iphone.html

  • Loss of keyboard focus in Java appl running under linux

    I have a small sample program that replicates my problem. When this program is run a window is created. If you select File->New another instance of the program window is created. Now if you try to go back and bring to front the first window, keyboard focus is not
    transferred when run under linux. You can only type in the second window. The expected behavior does happen in Windows.
    > uname -a
    Linux watson 2.6.20-1.2933.fc6 #1 SMP Mon Mar 19 11:38:26 EDT 2007 i686 i686 i386 GNU/Linux
    java -versionjava version "1.5.0_11"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_11-b03)
    Java HotSpot(TM) Client VM (build 1.5.0_11-b03, mixed mode, sharing)
    javac -versionjavac 1.5.0_11
    import java.awt.event.*;
    import javax.swing.*;
    class SwingWindow extends JFrame {
        SwingWindow() {
         super("SwingWindow");
         JMenuBar menuBar = new JMenuBar();     
            JMenu fileMenu = new JMenu("File");
            JMenuItem newItem = new JMenuItem("New");
            newItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
              SwingWindow.createAndShowGUI();
         fileMenu.add(newItem);
            menuBar.add(fileMenu);
            setJMenuBar(menuBar);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);       
         JTextField text = new JTextField(200);
         getContentPane().add(text);
         pack();
         setSize(700, 275);
        public static void createAndShowGUI() {
            JFrame frame = new SwingWindow();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    You can implement the FocusListener interface. When
    the first JFrame gains focus, call
    text.requestFocusInWindow(). I hope this helps.The call requestFocusInWindow is not helping, perhaps even making it worse.
    The problem seems to be that I am in the situation where the call
    KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner()
    is returning the expected Component. The problem is that the KeyListener class that is registered with the Component is not being called when a key is being pressed.
    The issue is that I have a component that has the keyboard focus, but the KeyListener class
    is not responding.
    This seems to be a linux only problem which makes it only mysterious.

  • JPanel loses keyboard focus

    Ok, i have a JTextField which is initially disabled. A JPanel draws some stuff and receives keyboard input. When i enable the textfield, type some stuff, then press Esc (which disables it), i cant get the keyboard focus back on the JPanel. Here is an example:
    (you can move the red circle before you enable the textfield, after you disable it, you cant move it anymore).
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.util.Vector;
    public class example extends JPanel implements ActionListener,Runnable {
        JFrame frame;
        JMenuBar menubar;
        JMenu m_file;
        JMenuItem mi_open,mi_close;
        JPanel canvas,northpanel;
        JTextField textfield;
        Image canvasimg;
        Thread thread=new Thread(this);
        private Image dbImage;     // for flickering
         private Graphics dbg;     // for flickering
         int x1=400,y1=200;
        public example() {
            frame = new JFrame("Example");                         // window
            frame.setLayout(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setPreferredSize(new Dimension(1000,700));
            frame.setLayout(new BorderLayout());
            northpanel=new JPanel();
            northpanel.setLayout(null);
            northpanel.setPreferredSize(new Dimension(1000,20));     northpanel.setLocation(0,0);
            menubar=new JMenuBar();
            m_file=new JMenu("File");   
            mi_open=new JMenuItem("Open");
            mi_close=new JMenuItem("Close");
            m_file.add(mi_open);
            m_file.add(mi_close);   
            m_file.getPopupMenu().setLightWeightPopupEnabled(false);   
            menubar.add(m_file);
            northpanel.add(menubar);
            menubar.setLocation(0,0);     menubar.setSize(80,20);
            textfield=new JTextField();
            northpanel.add(textfield);
            textfield.setSize(200,20);     textfield.setLocation(500,0);   
            textfield.setEnabled(false);
            frame.add(northpanel,BorderLayout.NORTH);
            canvas=new JPanel();
            canvas.setLayout(null);
            canvas.setSize(1000,600);
            canvas.setBackground(Color.white);
             frame.add(canvas,BorderLayout.CENTER);      
            frame.pack();
            frame.setVisible(true);       
            thread.start();                                   // start the thread
            textfield.addMouseListener(new MouseAdapter(){
                    public void mousePressed(MouseEvent e){
                         textfield.setEnabled(true);
               textfield.addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e){
                      int key=e.getKeyCode();
                      if(key==27){     // esc
                           textfield.setEnabled(false); 
                           canvas.setEnabled(true);                // not working
                           canvas.requestFocus();
                           canvas.requestFocusInWindow();
               frame.addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e){                   
                      int key=e.getKeyCode();
                      if(key==37){ //left
                           x1-=5;
                      if(key==38){ //up
                           y1-=5;
                      if(key==39){ //right
                           x1+=5;
                      if(key==40){ //down
                           y1+=5;
        // Create the GUI and show it. 
        private static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            example ex = new example();
        public void run(){
             while(true){
                  try{
                       if(canvasimg==null)repaint();                   
                       Graphics g=canvas.getGraphics();
                       update(g);
                       thread.sleep(30);                                             // 1 sec
                  }      catch(InterruptedException ex){}
        // ActionPerformed handles button and menu events
        public void actionPerformed(ActionEvent e){              
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void update (Graphics g){          // get rid of flicker
              if (dbImage == null){
                   dbImage = canvas.createImage (canvas.getSize().width, canvas.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (canvas.getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (canvas.getForeground());
              paint (dbg);
              g.drawImage (dbImage, 0, 0, this);
         public void paint(Graphics g){
              g.drawImage(canvasimg,0,0,this);          
              g.setColor(Color.red);
             g.fillOval(x1,y1,10,10);
        public void repaint(){     
             if(canvas!=null && canvasimg==null)canvasimg=canvas.createImage(1000,670);
             if(canvasimg==null)return;
             Graphics g=canvasimg.getGraphics();
             if(g==null)return;
             g.setColor(Color.white);
             g.fillRect(0,0,1000,600);
    }  

    OK great guru since you're so damn confident that you're doing everything right, find out for yourself why this works and yours doesn't.
    I could list a few dozen things wrong with your code, but I'd be wasting my keystrokes.import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class TextFieldDisableNoProblem extends JPanel {
       JPanel northPanel;
       JMenuBar menubar;
       JMenu m_file;
       JMenuItem mi_open,mi_close;
       JTextField textField;
       int x1 = 400;
       int y1 = 200;
       public TextFieldDisableNoProblem () {
          setBackground (Color.WHITE);
          addKeyListener (new KeyAdapter () {
             public void keyPressed (KeyEvent e){
                int key = e.getKeyCode ();
                switch (key) {
                   case KeyEvent.VK_LEFT:
                         x1 -= 5;
                         break;
                   case KeyEvent.VK_UP:
                         y1 -= 5;
                         break;
                   case KeyEvent.VK_RIGHT:
                         x1 += 5;
                         break;
                   case KeyEvent.VK_DOWN:
                         y1 += 5;
                         break;
                repaint ();
       void makeUI () {
          JFrame frame = new JFrame ("");
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (600, 500);
          frame.setLocationRelativeTo (null);
          menubar=new JMenuBar ();
          m_file=new JMenu ("File");
          mi_open=new JMenuItem ("Open");
          mi_close=new JMenuItem ("Close");
          m_file.add (mi_open);
          m_file.add (mi_close);
          menubar.add (m_file);
          frame.setJMenuBar (menubar);
          textField=new JTextField ();
          textField.setEnabled (false);
          textField.setBounds (200, 0, 200, 20);
          textField.addMouseListener (new MouseAdapter (){
             public void mousePressed (MouseEvent e){
                textField.setEnabled (true);
          textField.addKeyListener (new KeyAdapter () {
             public void keyPressed (KeyEvent e){
                int key = e.getKeyCode ();
                if(key == KeyEvent.VK_ESCAPE){
                   textField.setEnabled (false);
                   requestFocus ();
          northPanel=new JPanel ();
          northPanel.setLayout (null);
          northPanel.setPreferredSize (new Dimension (600,20));
          northPanel.add (textField);
          frame.add (northPanel,BorderLayout.NORTH);
          frame.add (this, BorderLayout.CENTER);
          frame.setVisible (true);
          requestFocus ();
       public void paintComponent (Graphics g) {
          super.paintComponent (g);
          g.setColor (Color.RED);
          g.fillOval (x1, y1, 10, 10);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                JFrame.setDefaultLookAndFeelDecorated (true);
                new TextFieldDisableNoProblem ().makeUI ();
    }db

  • Calling1.4.1 signed applet from Javascript causes keyboard/focus problems

    Pretty sure there's a JRE bug here, but I'm posting to forums before I open one in case I'm missing something obvious :-)
    This issue may be specific to IE, I haven't tested elsewhere yet. Our web application is centered around a signed applet that is initialized with XML data via Javascript. We first noticed the problem when our users started upgrading from the 1.3.x plug-in to the 1.4.x plug-in. The major symptom was that shortcut keys stopped working. I debugged the problem off and on for about a month before I boiled it down to a very simple program that demonstrates the issue (included below). Basically, the program has a function that adds a JButton to a JPanel and registers a keyboard listener (using the new DefaultKeyboardFocusManager class) that prints a message to the console. This function is called by the applet's init() method, as well as by a public method that can be called from Javascript (called callMeFromJavascript()). I also included a very simple HTML file that provides a button that calls the callMeFromJavascript() method. You can test this out yourself: To recreate, compile the class below, JAR it up, sign the JAR, and put in the same dir with the HTML file. Load the HTML file in IE 5.0 or greater, and bring the console up in a window right next to it. Now click the button that says init--you should see the small box appear inside the button that indicates it has the focus. Now press some keys on your keyboard. You should see "KEY PRESSED!!!" appearing in the console. This is proper behavior. Now click the Init Applet from Javascript button. It has removed the button called init, and added one called "javascript". Press this button. Notice there is no focus occurring. Now press your keyboard. No keyboard events are registered.
    Where is gets interesting is that if you go back and make this an unsigned applet, and try it again, everything works fine. This bug only occurs if the applet is signed.
    Furthermore, if you try it in 1.3, signed or unsigned, it also works. So this is almost certainly a 1.4 bug.
    Anyone disagree? Better yet, anyone have a workaround? I've tried everything I could think of, including launching a thread from the init() method that sets up the components, and then just waits for the data to be set by Javascript. But it seems that ANY communication between the method called by Javascript and the code originating in init() corrupts something and we don't get keyboard events. This bug is killing my users who are very reliant on their shortcut keys for productivity, and we have a somewhat unique user interface that relies on Javascript for initialization. Any help or suggestions are appreciated.
    ================================================================
    Java Applet (Put it in a signed JAR called mainapplet.jar)
    ================================================================
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MainApplet extends JApplet implements KeyEventDispatcher
        JPanel test;
        public void init()
            System.out.println("init called");
            setUp("init");
        public void callMeFromJavascript()
            System.out.println("callMeFromJavascript called");
            setUp("javascript");
        private void setUp(String label)
            getContentPane().removeAll();
            test = new JPanel();
            getContentPane().add( test );
            JButton button = new JButton(label);
            test.add( button );
            test.updateUI();
            DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
        public boolean dispatchKeyEvent(KeyEvent e)
            System.out.println("== KEY PRESSED!!! ==");
            return false;
    }================================================================
    HTML
    ================================================================
    <form>
    <APPLET code="MainApplet" archive="mainapplet.jar" align="baseline" id="blah"
         width="200" height="400">
         No Java 2 SDK, Standard Edition v 1.4.1 support for APPLET!!
    </APPLET>
    <p>
    <input type="button" onClick="document.blah.callMeFromJavascript();" value="Init Applet via Javascript">
    </form>

    I tried adding the requestFocus() line you suggested... Same behavior.
    A good thought, but as I mention in my description, the applet has no trouble gaining the focus initially (when init() is called). From what I have seen, it is only when the call stack has been touched by Javascript that I see problems. This is strange though: Your post gave me the idea of popping the whole panel into a JFrame... I tried it, and the keyboard/focus problem went away! It seems to happen only when the component hierarchy is descended from the JApplet's content pane. So that adds yet another variable: JRE 1.4 + Signed + Javascript + components descended from JApplet content pane.
    And yes, signed or unsigned DOES seem to make a difference. Don't ask me to explain why, but I have run this little applet through quite a few single variable tests (change one variable and see what happens). The same JAR that can't receive keyboard events when signed, works just fine unsigned. Trust me, I'm just as baffled as you are.

  • Switching windows in Linux/Firefox loses keyboard focus. Workarounds?

    Hi,
    I've been stumbling on an issue in which an applet gets into a state where it can receive mouse events but not keyboard events. This state occurs some of the time when switching from a non-modal dialog to the applet.
    I've witnessed this behavior on:
    Linux (fc8), Firefox 3.0.10, Java plug-in 1.6.0_13, Gnome 2.20.3
    Sun Solaris (5.10), Firefox 3.0.8, Java plug-in 1.6.0_12, Sun Java Desktop System or CDE
    I can not reproduce this behavior using appletviewer, nor can I reproduce it on the Mac (Opera/Firefox/Safari), nor on Windows (Firefox/IE).
    I've crafted some code that shows the behavior:
    FocusApplet.java:
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.beans.*;
    public class FocusApplet extends JApplet {
      JTextArea infoText;
        Object activeWindow;
        Object focusOwner;
        Object permanentFocusOwner;
           Applet contains two components.
           NORTH: Text field
           CENTER: Info text
           The info text is updated whenever the following
           KeyboardFocusManager properties change:
              activeWindow
           focusOwner
           permanentFocusOwner
      public void init(){
          JTextField tf = new JTextField("Type here");
          infoText = new JTextArea();
          infoText.setEditable(false);
          infoText.setLineWrap(true);
          infoText.setWrapStyleWord(true);
          infoText.setBorder(new EtchedBorder());
          this.add(infoText, BorderLayout.CENTER);
          this.add(tf, BorderLayout.NORTH);
          KeyboardFocusManager focusManager =
           KeyboardFocusManager.getCurrentKeyboardFocusManager();
          activeWindow=focusManager.getActiveWindow();
          permanentFocusOwner=focusManager.getPermanentFocusOwner() ;
          focusOwner=focusManager.getFocusOwner() ;
          updateText();
          focusManager.addPropertyChangeListener(
           new PropertyChangeListener() {
             public void propertyChange(PropertyChangeEvent e) {
              String prop = e.getPropertyName();
              if ("focusOwner".equals(prop)) {
                  focusOwner = e.getNewValue();
                  updateText();
              } else if ("permanentFocusOwner".equals(prop)) {
                  permanentFocusOwner = e.getNewValue();
                  updateText();
              } else if ("activeWindow".equals(prop)) {
                  activeWindow = e.getNewValue();
                  updateText();
          // Create non-modal dialog
          JDialog jdl = new JDialog((Frame)null,"Extra dialog",
                        false/*modal*/);
          jdl.setSize (300,550);
          jdl.setVisible(true);
        public void updateText() {
         infoText.setText("Active window: "+getName(activeWindow)+
              "\nFocus owner: "+getName(focusOwner)+
            "\nPermanent focus owner: "+getName(permanentFocusOwner));
        public String getName(Object obj) {
         return (obj==null) ? "null" : obj.getClass().getName();
    }Applet HTML:
    <applet code="FocusApplet.class" width="400" height="400"></applet>When I run this applet, I can click on the text field ("Type here") and enter text. Then, I switch between the empty dialog box and the applet using the window manager. (I.e., clicking on the dialog, then clicking on the applet.) Sometimes I see the following Keyboard Focus settings when I bring the applet to the front:
    Active window: sun.plugin.viewer.frame.XNetscapeEmbeddedFrame
    Focus owner: javax.swing.JTextField
    Permanent focus owner: javax.swing.JTextField
    In this case, clicking on the text field will allows the user to edit text. Good! However, 10%-50% of the time I get the following settings after I bring the applet to the front:
    Active window: null
    Focus owner: null
    Permanent focus owner: javax.swing.JTextField
    In this case, I can click on the applet, and I can highlight text in the text field, but I can not edit the text. (No carat appears. Bad!) Since there is no keyboard focus owner, the applet appears non-responsive.
    I have a few questions:
    1. Is this a Java plug-in bug? A Firefox bug? Who do I file a bug with, assuming there's not something I'm missing?
    2. Can anyone suggest a workaround?
    Thanks,
    -David-

    I noticed the problem too. Is there any fix or workaround? Friends using Windows say that all is ok.
    Linux x86_64 (Gentoo), Firefox 3.5.1, jre 1.6.0.15.

  • Focus Event

    I have a problem like this:
    I have a form with 2 text fields: Text1, Text2. If focusing on Text1 and pass focus-event to Text2, a Message_Box will show to confirm: "Do you want to change focusing from Text1 to Text2 (Y/N)?". If you choose Yes then focus on Text2, otherwise keep focusing on Text1.
    I have tried with following codes but it shows Message_Box 2 times when choosing No.
    Please help me to solve this issue.
    Thanks alot.
    import com.fss.swing.*;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import java.awt.BorderLayout;
    import java.awt.Rectangle;
    import javax.swing.*;
    import javax.swing.JButton;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.Dimension;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: FSS-FPT</p>
    * @author not attributable
    * @version 1.0
    public class test extends JFrame
         public test()
              try
                   jbInit();
              catch(Exception ex)
                   ex.printStackTrace();
         private void jbInit() throws Exception
              jTextField1.setText("jTextField1");
              jTextField1.setBounds(new Rectangle(21,65,226,19));
              this.getContentPane().setLayout(null);
              this.getContentPane().add(jTextField1,null);
              jButton1.setBounds(new Rectangle(132,128,73,23));
              jButton1.setText("jButton1");
              this.getContentPane().add(jTextField2);
              this.getContentPane().add(jButton1);
              jTextField2.setText("jTextField2");
              jTextField2.setBounds(new Rectangle(267,66,64,19));
              jTextField1.addFocusListener(new FocusAdapter() {
                   public void focusLost(FocusEvent e){
                        if(e.isTemporary())
                             return;
                        int i = MessageBox.showConfirmDialog(test.this,"Do you want to change focusing from Text1 to Text2 (Y/N)?","Confirm");
                        if(i == MessageBox.YES_OPTION)
                             jTextField2.requestFocus();
    else
    jTextField1.requestFocus();
         JTextField jTextField1 = new JTextField();
         JTextField jTextField2 = new JTextField();
         JButton jButton1 = new JButton();
         public static void main(String args[]) {
              test t = new test();
              t.setTitle("Test");
              t.setSize(new Dimension(400,300));
              t.setVisible(true);
    Edited by: googlecomvn on Jul 4, 2008 3:23 AM

    The way I've seen to cancel focus events is using a VetoableChangeListener:
    [http://java.sun.com/j2se/1.5.0/docs/api/java/awt/doc-files/FocusSpec.html#FocusAndVetoableChangeListener]
    import java.awt.KeyboardFocusManager;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyVetoException;
    import java.beans.VetoableChangeListener;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class FocusTest extends JFrame {
       public FocusTest() {
          final JTextField field1 = new JTextField("type \"text\"");
          final JTextField field2 = new JTextField("then click on me!");
          setLayout( new BoxLayout( this.getContentPane(), BoxLayout.Y_AXIS ) );
          add(field1);
          add(field2);
          pack();
          KeyboardFocusManager.getCurrentKeyboardFocusManager().addVetoableChangeListener(
             new VetoableChangeListener() {
                public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
                   if ( evt.getOldValue() == field1 ) {
                      if ( !"text".equals(field1.getText()) ) { //simple validation
                         throw new PropertyVetoException("Invalid value for field1", evt);
       public static void main(String[] args) {
          new FocusTest().setVisible(true);
    }You'd definitely get in trouble with using a JOptionPane in the change listener, though (as it would throw more focus events, requiring more JOptionPanes, etc).
    Edited by: endasil on 4-Jul-2008 8:50 AM

  • JComboBox popup list remains open after losing keyboard focus

    Hi,
    I have noticed a strange JComboBox behavior. When you click on the drop down arrow to show the popup list, and then press the Tab key, the keyboard focus moves to the next focusable component, but the popup list remains visible.
    I have included a program that demonstrates the behavior. Run the program, click the drop down arrow, then press the Tab key. The cursor will move into the JTextField but the combo box's popup list is still visible.
    Does anyone know how I can change this???
    Thanks for any help or ideas.
    --Yeath
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Test extends JFrame
       public Test()
          super( "Test Application" );
          this.getContentPane().setLayout( new BorderLayout() );
          Box box = Box.createHorizontalBox();
          this.getContentPane().add( box, BorderLayout.CENTER );
          Vector<String> vector = new Vector<String>();
          vector.add( "Item" );
          vector.add( "Another Item" );
          vector.add( "Yet Another Item" );
          JComboBox jcb = new JComboBox( vector );
          jcb.setEditable( true );
          JTextField jtf = new JTextField( 10 );
          box.add( jcb );
          box.add( jtf );
       public static void main( String[] args )
          Test test = new Test();
          test.pack();
          test.setVisible( true );
          test.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    ran your code on 1.5.0_3, observed problem as stated.
    even though the cursor is merrily blinking in the textfield, you have to click into
    the textfield to dispose the dropdown
    ran your code on 1.4.2_08, no problems at all - tabbing into textfield immediately
    disposed the dropdown
    another example of 'usual' behaviour (involving focus) breaking between 1.4 and 1.5
    the problem is that any workaround now, may itself be broken in future versions

  • Keyboard Problem while running Swing App on LINUX

    Hi All,
    We have a Swing based Application running on Windows Platform. We need to run the Application on LINUX. The Application does not have any problem and runs without problems for a few minutes but after that the keyboard stops to respond inside the application. Keyboard runs fine outside the application but no key events are recognized inside the application. Mouse is working fine even after the keyboard stops responding.
    Key Points:
    �     The keyboard is a PS/2 keyboard.
    �     Read Hat Fedora 5.0 is being used.
    �     The problems occur on both KDE and GNONE.
    �     The Java Version is jdk1.5.0_09
    The application is data entry application using EJB at server side. The client UI has lot of JTables and Desktop Panes/ Internal Frames. User use ctrl+tab, ctrl+shift+tab, tab, shift+tab, and other hot keys to navigate between Components. Listeners on keyboard Focus Owner are also used. We are unable to diagnose the problem because of the undeterminable nature of the problem. The problem occurs at anytime and does not occur on any special key/ combinations press.
    Thanks and Regards,
    Nishant Saini
    http://www.simplyjava.com

    I've just installed the JDK 1.4 on my debian box. I
    can compile and run a basic Hello World app using
    System.println, but when I try to run a simple swing
    app, I get an error like:
    Exception in thread "main"
    java.lang.NoClassDefFoundError
    at java.lang.Class.forName0(Native Method)
    at java.lang.... etc, etc.
    It goes on with about 30 different classes. It
    compiles fine, with no errors, but when it comes time
    to run, that's what I get. This is what I have in my
    .bash_profile as far as environment variables go:
    export JAVA_HOME="/usr/local/j2sdk1.4.1_01"
    export PATH="$JAVA_HOME/BIN:$PATH"
    export
    CLASSPATH="$JAVA_HOME/jre/lib/:$JAVA_HOME/lib:."The code works fine in Windows, so unless there's
    something platform-specific, I don't think there's a
    problem there. I've checked to make sure I'm not
    running kaffe by accident and I'm definitely running
    the right java and javac. I'm out of ideas. Any
    suggestions would be greatly appreciated.
    -dudley
    I may just be crazy, but your PATH looks a little screwy to me. I was under the impression that the standard java installation has its executables in the 'bin' directory, not the 'BIN' directory. Unless Debian has fallen to the evil empire, then I'm fairly sure file names are case-sensitive. I don't know if that will fix your problem though. Do you compile from the command line, or do you use an IDE???

  • Swing Calculator - Logical errors

    Hello,
    I have a couple of problems with the code below
    one of them is with the setLayout().
    Can anyone give a look to that code and tell me what's going wrong , or help me to make it work ??
    Thanks in advance!
    import java.awt.*;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.Container;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.*;
    public class Calculator extends JFrame implements ActionListener
        public static final int Width = 500;
        public static final int Height = 500;
        private JTextField Board;
        private JButton jbo0, jbo1, jbo2, jbo3, jbo4, jbo5, jbo6, jbo7, jbo8, jbo9,
                        jboAddition, jboSubtraction, jboMultiplication, jboDivision,
                        jboDot, jboLp, jboRp, jboClear, jboResult;
        public static void main(String args[])
        JFrame applet = new Calculator();
        JFrame frame = new JFrame();
        frame.add(frame);
        frame.setSize(Width,Height);
        frame.show();
    public static void main(String args[])
        JFrame outputFrame = new Calculator();
    //panel1.add(allyourstuff);
    //panel1.add(moreofyourstuff);
        outputFrame.setVisible(true);
        public Calculator()
            Container outputPane = this.getContentPane();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setSize(Width, Height);
            outputPane.setLayout(new GridLayout (3, 3));
            Panel panel1 = new Panel();
            this.setDefaultCloseOperation( EXIT_ON_CLOSE );
            Board = new JTextField();
            panel1.add(Board);
            outputPane.add(panel1);
            //panel1.add(jbo0);
            //Numbers
            setLayout(new FlowLayout());
            setFont(new Font("Helvetica", Font.PLAIN, 8));
            JButton jbo0 = new JButton("0");
            jbo0.addActionListener(this);
            panel1.add(jbo0);
            jbo1 = new JButton("1");
            panel1.add(jbo1);
            jbo1.addActionListener(this);
            jbo2 = new JButton("2");
            panel1.add(jbo2);
            jbo2.addActionListener(this);
            jbo3 = new JButton("3");
            panel1.add(jbo3);
            jbo3.addActionListener(this);
            jbo4 = new JButton("4");
            panel1.add(jbo4);
            jbo4.addActionListener(this);
            jbo5 = new JButton("5");
            panel1.add(jbo5);
            jbo5.addActionListener(this);
            jbo6 = new JButton("6");
            panel1.add(jbo6);
            jbo6.addActionListener(this);
            jbo7 = new JButton("7");
            panel1.add(jbo7);
            jbo7.addActionListener(this);
            jbo8 = new JButton("8");
            panel1.add(jbo8);
            jbo8.addActionListener(this);
            jbo9 = new JButton("9");
            panel1.add(jbo9);
            jbo9.addActionListener(this);
            //Math Operations
            jboAddition = new JButton("+");
            panel1.add(jboAddition);
            jboAddition.addActionListener(this);
            jboSubtraction = new JButton("-");
            panel1.add(jboSubtraction);
            jboSubtraction.addActionListener(this);
            jboMultiplication = new JButton("*");
            panel1.add(jboMultiplication);
            jboMultiplication.addActionListener(this);
            jboDivision = new JButton("/");
            panel1.add(jboDivision);
            jboDivision.addActionListener(this);
            //Result etc..
            jboDot = new JButton(".");
            panel1.add(jboDot);
            jboDot.addActionListener(this);
            jboLp = new JButton("(");
            panel1.add(jboLp);
            jboLp.addActionListener(this);
            jboRp = new JButton(")");
            panel1.add(jboRp);
            jboRp.addActionListener(this);
            jboClear = new JButton("C");
            panel1.add(jboClear);
            jboClear.addActionListener(this);
            jboResult = new JButton("=");
            panel1.add(jboResult);
            jboResult.addActionListener(this);
        public void actionPerformed(ActionEvent e)
            if (e.getSource() instanceof JButton)
                JButton buClicked = (JButton) e.getSource();
                if (buClicked == jboClear)
                    boardClear();
                else if(buClicked == jboResult)
                    Calculate();
            else
                Calculate();
        public void UserInput(JButton buClicked)
            String input;
            input = Board.getText();
            if (buClicked == jbo0)
                Board.setText(input + "0");
            if (buClicked == jbo1)
                Board.setText(input + "1");
            if (buClicked == jbo2)
                Board.setText(input + "2");
            if (buClicked == jbo3)
                Board.setText(input + "3");
            if (buClicked == jbo4)
                Board.setText(input + "4");
            if (buClicked == jbo5)
                Board.setText(input + "5");
            if (buClicked == jbo6)
                Board.setText(input + "6");
            if (buClicked == jbo7)
                Board.setText(input + "7");
            if (buClicked == jbo8)
                Board.setText(input + "8");
            if (buClicked == jbo9)
                Board.setText(input + "9");
            if (buClicked == jboAddition)
                Board.setText(input + "+");
            if (buClicked == jboSubtraction)
                Board.setText(input + "-");
            if (buClicked == jboMultiplication)
                Board.setText(input + "*");
            if (buClicked == jboDivision)
                Board.setText(input + "/");
            if (buClicked == jboDot)
                Board.setText(input + ".");
            if (buClicked == jboLp)
                Board.setText(input + "(");
            if (buClicked == jboRp)
                Board.setText(input + ")");
         private void boardClear()
            Board.setText("");
        public void Calculate()
            int counter;
            int numParenthesis = 0;
            int lenInput;
            String calc;
            String Answer = "";
            char NumOther;
            calc = Board.getText();
            lenInput = calc.length();
            for (counter = 0; counter < lenInput; counter++)
                NumOther = calc.charAt(counter);
                if (NumOther == ')')
                    numParenthesis--;
                if (NumOther == '(')
                    numParenthesis++;
                if ((NumOther < '(') || (NumOther > '9') || (NumOther == '.'))
                    Board.setText("Error");
                if (NumOther == '.' && (counter + 1 < calc.length()))
                    for (int k = counter + 1; (k < calc.length()) && ((Character.isDigit(calc.charAt(k))) || ((calc.charAt(k))) == '.'); k++)
                        if (calc.charAt(k) == '.')
                            Board.setText("Error");
            if (numParenthesis != 0)
                Board.setText("Error");
            else
                Answer = Calculate2(calc);
                Board.setText(Answer);
        private String CalculatorImp(String oper1, String oper2, char Oper)
            Double op1, op2;
            double ops1, ops2;
            double ans = 0;
            String result;
            op1 = new Double (oper1);
            op2 = new Double (oper2);
            ops1 = op1.doubleValue();
            ops2 = op2.doubleValue();
            if (Oper == '+')
                ans = ops1 + ops2;
            if (Oper == '-')
                ans = ops1 - ops2;
            if (Oper == '*')
                ans = ops1 * ops2 ;
            if (Oper == '/')
                ans = ops1/ops2;
            result = Double.toString(ans);
            return result;
        private String Calculate2(String process)
            String answer = process;
            String op1 = "";
            String op2 = "";
            char userinput;
            int index = 0;
            int indexL = 0;
            int indexR = 0;
            int numInput = answer.length();
            int numPar = 0;
            int matchPar = 0;
            int indexOp1 = 0;
            int indexOp2 = 0;
            if (answer  != "Error")
                for (index = 0; index < numInput; index++)
                    userinput = answer.charAt(index);
                    if (userinput  == '(')
                        if (matchPar == 0)
                            indexOp1 = index;
                        matchPar++;
                        numPar++;
                    if (userinput == ')')
                        matchPar--;
                        if (matchPar ==0)
                            indexOp2 = index;
                if (indexOp1 + 1 == indexOp2)
                    Board.setText("Error");
                if (answer == "Error"  && numPar > 0)
                    if (indexOp1 == 0)
                        if (indexOp2 == (numInput - 1))
                            if (indexOp1 != indexOp2)
                                answer = Calculate2(answer.substring(indexOp1 + 1, indexOp2));
                    else if (indexOp1 == 0 && indexOp2 > 0)
                        if ((Character.isDigit(answer.charAt(indexOp2 + 1))))
                            Board.setText("Error");
                        else
                            answer = Calculate2(answer.substring(indexOp1 + 1, indexOp2)) + answer.substring(indexOp2 + 1);
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                    else if ((indexOp1 > 0) && (indexOp2 > 0) && (indexOp2 != numInput - 1))
                        if (((Character.isDigit(answer.charAt(indexOp2 + 1 ))) ||  (Character.isDigit(answer.charAt(indexOp1 - 1 ))) ))
                            Board.setText("Error");
                        else
                            answer = answer.substring(0, indexOp1) + Calculate2(answer.substring(indexOp1 + 1, indexOp2)) + answer.substring(indexOp2 + 1);
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                    else if (indexOp2 == numInput - 1 && indexOp1 > 0)
                        if (((Character.isDigit(answer.charAt(indexOp1 - 1)))))
                            Board.setText("Error");
                        else
                            answer = answer.substring(0, indexOp1) + Calculate2(answer.substring(indexOp1 + 1, indexOp2));
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                if (numPar == 0)
                    if (answer != "Error")
                        if (!(Character.isDigit(answer.charAt(0))))
                            if (answer.charAt(0) != '-')
                                if (!(Character.isDigit(answer.charAt(answer.length() - 1))))
                                    Board.setText("Error");
                for (index = 0; index < answer.length() && (answer == "Error"); index++)
                    userinput = answer.charAt(index);
                    if (userinput == '*' || userinput == '/')
                        if (!(Character.isDigit(answer.charAt(index-1))) || (!(Character.isDigit(answer.charAt(index + 1)))))
                            if (answer.charAt(index + 1) != '-')
                                Board.setText("Error");
                        if (answer.charAt(index + 1) == '-')
                            if (!(Character.isDigit(answer.charAt(index + 2))))
                                Board.setText("Error");
                        if (answer == "Error")
                            indexL = index - 1;
                            if (indexL > 2)
                                if ((answer.charAt(indexL - 1)) == '-')
                                    if ((answer.charAt(indexL - 2)) == 'E')
                                        indexL = indexL -2;
                                while ((indexL  > 0) && ((Character.isDigit(answer.charAt(indexL - 2)) || ((answer.charAt(indexL - 1)) == '.') || ((answer.charAt(indexL - 1)) == 'E' ))))
                                    indexL--;
                                if (indexL == 1)
                                    if ((answer.charAt(indexL - 1)) == '-')
                                        indexL--;
                                if (indexL > 2)
                                    if (((answer.charAt(indexL - 1)) == '-') && !(Character.isDigit(answer.charAt(indexL - 2))))
                                            indexL--;
                                op2 = answer.substring(index + 1, indexR + 1);
                    for (index = 0; index < answer.length() && (answer != "Error"); index++)
                        if (index == 0)
                            index = 1;
                    if (index > 0)
                            if (answer.charAt(index + 1) == '-')
                                index = index + 2;
                    userinput = answer.charAt(index);
                    if ((userinput == '+') || (userinput == '-'))
                        if (!(Character.isDigit(answer.charAt(index - 1))))
                            Board.setText("Error");
                        if (!(Character.isDigit(answer.charAt(index + 1))))
                            Board.setText("Error");
                        if ((answer.charAt(index+1) == '-') && (!(Character.isDigit(answer.charAt(index+2)))))
                             Board.setText("Error");
                        if (answer != "Error")
                            indexL = 0;
                            op1 = answer.substring(indexL , index);
                            indexR = index + 1;
                            while((indexR < answer.length()-1) && ((Character.isDigit(answer.charAt(indexR + 1))) || ((answer.charAt(indexR + 1)) == '.') || ((answer.charAt(indexR + 1)) == 'E')))
                                indexR++;
                                if (indexR < answer.length() - 2)
                                        if ((answer.charAt(indexR + 1)) == '-')
                                            indexR++;
                            op2 = answer.substring(index + 1, indexR + 1);
                            answer = CalculatorImp(op1, op2, userinput ) + answer.substring(indexR + 1);
                            index = 0;
            return answer;
    }

    Your UserInput method doesn't seem to get called anywhere.
    You need to sort out the layout - try a vertical box containing the input and horizontal boxes for the button, or a simple grid. If using a GridLayout, the number of rows and column you give in the constructor should
    Move the actual calculation code out into a separate class - you then can test it more easily with a driver which feeds it lots of expressions, and your UI code isn't all mixed up with it.
    It's a convention to use lower case initial letters on variable and method names.
    Your code is very redundant - create one ActionListener which you attach to each your single character button to append the value of that button to the input box, rather than having all those tests, and extract that code into a single method.
    When you add a swing component to another, it keeps a reference to it so it can draw it. You don't need to, unless you want to do something else which it later on.
    Eg:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SwingCalculator extends JFrame {
      public static void main(String args[]) {
        new SwingCalculator().setVisible(true);
      final JTextField board;
      public SwingCalculator () {
        Container outputPane = this.getContentPane();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setFont(new Font("Helvetica", Font.PLAIN, 18));
        setTitle("SwingCalculator");
        outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
        board = new JTextField();
        outputPane.add(board);
        final JPanel buttons = new JPanel();
        buttons.setLayout(new GridLayout (5, 4));
        outputPane.add(buttons);
        // Buttons which append to the board
        addButtons(buttons, "7", "8", "9", "+");
        addButtons(buttons, "4", "5", "6", "-");
        addButtons(buttons, "1", "2", "3", "*");
        addButtons(buttons, ".", "0", "E", "/");
        addButtons(buttons, "(", ")");
        // the C and = buttons have special action listeners
        final JButton cancel = new JButton("C");
        buttons.add(cancel);
        cancel.addActionListener(new ActionListener() {
          public void actionPerformed (ActionEvent event) {
            board.setText("");
        final JButton calculate = new JButton("=");
        buttons.add(calculate);
        // move the expression code to a separate class and call it here
        calculate.addActionListener(new ActionListener() {
          public void actionPerformed (ActionEvent event) {
            try {
              board.setText(ExpressionParser.evaluate(board.getText()));
            } catch (ExpressionParseException ex) {
              board.setText("ERROR");
        pack();
      // adds buttons which, when pressed, append their label to the board
      public void addButtons (JPanel panel, String... labels) {
        for (final String label:labels) {
          JButton button = new JButton(label);
          panel.add(button);
          button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              board.setText(board.getText() + label);
    }

  • My MacBook Pro Retina's Bluetooth chipset unknown/odd login message on the login screen states Login Window Authentication Login window Name edit text has keyboard focus. In addition, the login screen is not remembering me

    I have been experiencing several issues with my MacBook Pro Retina mid 2012. My MBPR is scheduled to go into the depot. However, I am wondering if anyone may be able to shed light on a few issues as this is the third "official" time my MBPR is going back for service ("one depot" trip; "one authorized" dealer; several in-store visits).
    My Bluetooth is stating that the Bluetooth Chipset is Unknown (0). I also have had Bluetooth Preferences mysteriously change on me. In addition, while Bluetooth is off there are two serial modems turning on. I have turned them off, but they continue to pop up.
    In addition, when I log in, my MBPR is not remembering me and my login name is not appearing on the slate-gray screen. The name and password are blank and the following message appears in the lower left hand corner. "login window authentication login window Name edit text has keyboard focus."  As a side note, I am the only user. The login issue is a recent occurrence as we just totally wiped it again via a Command + R, and I don't believe I have an accessibility setting set to anything that would cause this, but wanted to check.
    Should I be concerned here? Has anyone else had issues like this? I don't want to worry if I don't have to. I have had so many issues over the course of nine months. 5-6 wipes. Airport card replaced and I am about to pull my hair out if my MBPR doesn't come back worldly like clock work this time. I just can't send my days trying to get a $2300 product to work for me any longer. No idea what is wrong with it, but it is driving me insane. Cross your fingers for me and any guidance you have or thoughts would be welcomed. Thank you. EMM

    A few more issues...
    In Console, the following is greyed out:
    User and Diagnostic reports
    Com.apple.launchd.peruser.0
    Com.apple.launchd.peruser.88
    Com.apple.launchd.peruser.89
    Com.apple.launchd.peruser.92
    Com.apple.launchd.peruser.97
    Com.apple.launchd.peruser.200
    Com.apple.launchd.peruser.201
    Com.apple.launchd.peruser.202
    Com.apple.launchd.peruser.212
    *[user logs are accessible]
    Krb5kdc
    Radius
    My guest files are locked, but again I am the administrator of MBPR.
    I am worried about a keystroke logged or at least, trying to rule it out.
    Also:
    Mdworker32(225) [and other mdworker numbers] are sandboxing; stating deny Mach-lookup
    Com.apple.Powermanagement.control, etc. long attachment with those files with version: ??? (???).
    Postinstall: removing applications/Microsoft Office 2011/Microsoft Outlook.app
    WARNINGS in Console include:
    [NSImage compositeToPoint:fromRect:operation:fraction:] is deprecated in MacOSX 19.8 and later. Please use -[NSImage drawAtPoint:fromRect:operation:fraction] instead.
    There are a ton of other warnings. Before I go through this again, can someone tell me if this is normal (all of it -- above too); or if these are symptoms is a keystroke logger or hardware issues? 
    I ask because originally, when my computer went in for diagnostics (more than once), Apple stated the hardware was fine (other than Airport Card -- finally). However, if I've done 5-6 total wipes; created new users; do not have sharing set-up; have not played around in Terminal; and am up-to-date with versions -- and various issues KEEP COMING BACK -- I am left wondering if a keystroke logger would be possible here?!? I thought maybe a faulty logic board, but why would diagnostics be okay, then? Not trying to be hyperbole, just desperate.
    Please help me rule keystroke logger out or at least, tell me so I know, so I can take appropriate action. If you think it could be the logic board with symptoms above, that would be a great too.
    All I want to do is use the computer as intended, but I can't seem to get a real answer, so after nine months -- I am turning to the communities to see if anyone -- anyone at all -- can help. The last thing I can do is have the MBPR come back from the depot and the same thing occur. Any guidance or advice would be so gratefully appreciated.

  • When I try to add a new event to iCal a dialog says "you can't add or change events in the Birthday Calendar". How do I cancel this?

    When I try to add a New Event to iCal a dialog box keeps saying "you can't add or change events in the Birthday Calendar". iCal is, however, receiving up-dates from my other devoces via iCloud. Can anyone help unblock this for me please?

    You can not add events to the birthday's calendar. To add birthday's to the birthday calendar you need to add the birthday to a contact in the Contacts app.
    You can set your default calendar here:
    iCal > Preferences > General  > Default Calendar and chose the calendar you want to default to.

Maybe you are looking for

  • Can I sync documents via iCloud with Lion?

    Can I sync documents via iCloud with Lion?

  • Home Sharing stopped working  ATV2 and 15" Macbook Pro OSX 10.7.2 & iTunes 10.51 (42)

    I was working fine up until yesterday evening. I've tried everything from restoring and reseting the ATV2, restarting and reinstalling iTunes, turning homesharing off and back on again. Also I can't use Airplay from my Iphone 4S or my Ipad2. Both pro

  • PS CC does not display images

    I use (hope to) PS CC in combo with LR and Windows 8. When I select right click in LR and edit in PS CC, PS loads but does not display the image. If I look in PS under recently opened files, the file imported from LR shows. If I initiate the opening

  • Can't Turn Hardware Accelerator off in Lion

    I've been trying all day to turn hardware acceleration off on my computer and can not. The settings are unresponsive to a mouse and the keyboard shortcuts will cycle through the icons and I can select them, but making a change (i.e. unticking the har

  • PHOTO SHOP ELEMENTS 5.0

    I AM UN ABLE TO USE ANY EDIT (QUICK FIX AND/OR FULL EDIT) IN PHOTO SHOP EELEMENTS 5.0   CAN ANYONE HELP?