Problem with backspace on JFrame

Hello,
I have a problem on a JFrame. Indeed, I add a keyListener to the frame, but the "Bakcspace" don't work. There is anything when a I press on Backspace (with KeyTyped, KeyReleased and KeyPressed). All other keys are working.
Thanks.

the solution of the problem is :
Version note: This page reflects the focus API introduced in released 1.4. As of that release, the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. If you need to prevent the focus traversal keys from being consumed, you can call
component.setFocusTraversalKeysEnabled(false)
on the component that is firing the key events. Your program must then handle focus traversal on its own. Alternatively, you can use a KeyEventDispatcher to pre-listen to all key events. The focus page (in the Creating a GUI with JFC/Swing trail) has detailed information on the focus subsystem.

Similar Messages

  • Problem with setContentPane() in JFrame class

    I recently discovered a problem with the setContentPane method in the JFrame class. When I use setContentPane(Container ..), the previously existing contentPane remains in the stack. I have tried nullifying getContentPane(), and all manner of things, but, each time I use setContentPane, I have another instance of a JPanel in the stack.
    I'm using code similar to setContentPane(new CustomJPanel()); and each time the user changes screens, and a similar call to that is made, the old CustomJPanel instance remains in the stack. Can anyone suggest a way around this? On their own the panels do not take up very much memory, but after several hours of usage, they will build up.

    I tried what you suggested; it only resulted in a huge performance decrease. The problem with memory allocation is still there.
    Here is the method I use to switch screens in my app:
    public static void changeScreen (JPanel panel){
              try{
                   appFrame.setTitle("Wordinary : \""+getTitle()+"\"");
                   appFrame.setContentPane(panel);
                   appFrame.setSize(appFrame.getContentPane().getPreferredSize());     
                   appFrame.getContentPane().setBackground(backColour);
                   for (int i = 0; i < appFrame.getContentPane().getComponents().length; i++)
                        appFrame.getContentPane().getComponents().setForeground(textColour);
                   //System.out.println("Background colour set to "+backColour+" text colour set to "+textColour);
                   appFrame.validate();
              catch (Exception e){
                   //System.out.println("change");
                   e.printStackTrace();
    And it is called like this:
    changeScreen(new AddWordPanel());The instantiation of the new instance is what is causing the memory problems, but I can't think of a way around it.

  • Problem with JPanel in JFrame

    hai ashrivastava..
    thank u for sending this one..now i got some more problems with that screen .. actually i am added one JPanel to JFrame with BorderLayout at south..the problem is when i am drawing diagram..the part of diagram bellow JPanel is now not visible...and one more problem is ,after adding 6 ro 7 buttons remaing buttons are not vissible..how to increase the size of that JPanel...to add that JPanel i used bellow code
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    f.getContentPane().add(BorderLayout.SOUTH, panel);

    Hi
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    // Add this line to ur code with ur requiredWidth and requiredHeight
    panel.setPreferredSize(new Dimension(requiredWidth,requiredHeight));
    f.getContentPane().add(BorderLayout.SOUTH, panel);
    This should solve ur problem
    Ashish

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java&#8482; Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • Weird problem with jpanel vs jframe

    I'm using jmathplot.jar from JMathTools which lets me do 3d plotting. I used a JFrame to get some code to work and it worked fine. Here's the code that worked for a JFrame:
    public class View extends JFrame
        private Model myModel;
        private Plot3DPanel myPanel;
        // ... Components
        public View(Model m)
            myModel = m; 
            // ... Initialize components
            myPanel = new Plot3DPanel("SOUTH");
            myPanel.addGridPlot("Test",myModel.getXRange(),myModel.getYRange(),myModel.getZValues());
            setSize(600, 600);
            setContentPane(myPanel);
            setVisible(true);
    }Here's the class that starts everything:
    public class TestApplet extends JApplet
        public void init()
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        createGUI();
            catch (Exception e)
                e.printStackTrace();
        private void createGUI()
            System.out.println("Creating GUI");
            Model model = new Model();
            View view = new View(model);
    }And here's the Model:
    public class Model
        private double[] myXRange,myYRange;
        private double[][] myZValues;
        public Model()
            createDataSet();
        public double[] getXRange()
            return myXRange;
        public double[] getYRange()
            return myYRange;
        public double[][] getZValues()
            return myZValues;
        private void createDataSet()
            myXRange = new double[10];
            myYRange = new double[10];
            myZValues = new double[10][10];
            for(double i=0;i<10;i++)
                for(double j=0;j<10;j++)
                    double x = i/10;
                    double y = j/10;
                    myXRange[(int) i] = x;
                    myYRange[(int) j] = y;
                    myZValues[(int) i][(int) j]= Math.cos(x*Math.PI)*Math.sin(y*Math.PI);
    }However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and changed:
    setSize(600, 600);
    setContentPane(myPanel);
    setVisible(true);to
    this.add(myPanel);and added these two lines to createGUI():
            view.setOpaque(true);
            setContentPane(view);When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet. I don't know if it's a problem with the library or if I'm doing something wrong in my applet.

    However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and (...)What do you mean? View extends JApplet? I thought View was meant to extend JPanel in the end...
    When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet.Or, the panel has its preferred size, and this latter is too small. Actually the panel has the size its container's layout manager awards it (taking or not the panel's preferred, minimum, and maximum sizes into account). See the tutorial on [layout managers|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html] .
    In particular, this line adds the myPanel to a parent panel (presumably, it is in class View which extends JPanel, whose default layout is FlowLayout):
    this.add(myPanel);
    I don't know if it's a problem with the library or if I'm doing something wrong in my applet.Likely not (presumably the library interfers only in how it computes the Plot3DPanel's preferred size). There's an easy way to tell: try to layout correctly a custom JPanel of yours, containing only e.g. a button with an icon. Once you understand the basics of layout management, revisit the example using ther 3rd-party library.
    N.B.: there are a lot of "likely" and "presumably" in my reply: in order to avoid hardly-educated guesses especially on what is or isn't in your actual code, you'd better provide an SSCCE , which means reproducing the problem without the 3rd party library.

  • Thread problem with displaying to JFrame :(

    Hi everyone I have a problem, I have a JFrame which I use to submit a transaction. I am submitting a multiple number but would like to do so sequentially. SO for now i am starting one transaction thread, waiting for it to finish then starting the next etc.
    My problem is that once a transaction is finished it will not print the msg to areaOutput untill all transactions have finished processing. But the call to system.out will print at the correct time.
    I am sure i have missed a point just don't know what.
    Thread m = new Thread(transactionN);
    m.start();
    try{
    m.join();
    areaOutput.append("Finshed thread #: " + threadNum + newline);
    System.out.println("Thread done");
    }catch(InterruptedException ie){
    System.out.println("interrupted.");
    threadNum ++;Thanks for any advice!!
    luv M

    Yes, like the previous poster said. If you are running your example code from the event thread (as response to some gui-interaction like pressing a button), you are blocking the event thread. The event thread is also the same thread that paints the screen. So nothing is painted until that piece of code is finished.

  • Problem with backspace

    Please help with this small problem have been coding a calculator program for several weeks and have everything working except the backspace button would really appreciate some help the code for my action performed class which would contain the code is posted below thanks in advance
         public void actionPerformed(ActionEvent e){
                   char currentOperator;
                   String newNumberField = newTextField.getText();
                   if(!beenBefore){
                        num1 = new Integer(newNumberField).intValue();
                        lastOperator = e.getActionCommand().charAt(0);
                        currentOperator = e.getActionCommand().charAt(0);
                        beenBefore = true;
                   else{
                        num2 = new Integer(newNumberField).intValue();
                        currentOperator = e.getActionCommand().charAt(0);
                        switch(lastOperator){
                             case '+': num1 = num1+num2;
                                         break;
                             case '-': num1 = num1-num2;
                                         break;
                             case '*': num1 = num1*num2;
                                         break;
                             case '/': num1 = num1/num2;
                                         break;
                        lastOperator = currentOperator;
                   if(currentOperator == '=')
                        newTextField.setText(String.valueOf(num1));
                   else
                        newTextField.setText("");
                   if(currentOperator == 'C')
                        beenBefore = false;
                if(e.getActionCommand().equals("1/x"))
                      newTextField.setText(String.valueOf(1/num1));
                  if (e.getActionCommand().equals("Backspace"))

    why even bother posting a reply if ur goin to be like that I'v tried several methods keep getting errors heres one I tried
    if (e.getActionCommand().equals("Backspace")
      String.valueOf(num1) = String.valueOf(num1)(0, String.valueOf(num1) - 1);I'm only looking for some help man an it aint homework either whats ur problem

  • Problems with resizing a JFrame

    Hello people! I'm having a problem setting the size of a JFrame while it is visible. Just resizing it by hand with the mouse is no problems, everything works ok, but when I call the setSize(blabla) method, the contents of the window doesn't notice that it has more space to draw the components on. The result is that the extended area of the window is just plainly white... until I resize it by hand, then everything looks ok. Does anyone have a solution? repaint() doesn't help...
    /Erik

    hay svenmeier...
    I'm all confused with the pack() method... I don't like it :) It always sets the size 2 pixels too large in windows 9x/Nt/2k/xp. Of course that's adjustable, but I'm unsure whether it will be the same on all other platforms. It's just one problem that I have that I have never been able to solve. Asking people around here for a solution never helped, because it seems others do not have this particular problem.
    So, to me it seems that the most reliable way to set the size of a frame is to first set it visible, and then resize it with respect to the insets.
    /Erik

  • Problem with threads in JFrame

    Hy everyone...i have a small problem when i try to insert clock in my JFrame , because all i get is an empty text field.
    What i do is that i create inner class that extends Thread and implements Runnable , but i dont know ... i saw some examples on the intrnet...but they are all for Applets...
    Does any one know how i can implement this in JFrame (JTextField in JFrame).
    Actually any material on threads in JFrame or JPanel would be great....THNX.

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Problem with IconImage for JFrame

    If I create an BufferedImage by ImageIO.read for example and then call getScaledInstance on this image and set the scaled Image to a JFrame as the IconImage (via setIconImage(Image image)), the application hangs.
    Has anyone else this problem?

    ok ok, i read it and now think that this is a sscce:
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class Start
         public static void main(String[] args)
              final JFrame frame = new JFrame();
              final Image image, imageScaled;
              try
                   image = ImageIO.read(new File("test.png"));
                   imageScaled = image.getScaledInstance(8, 8, Image.SCALE_DEFAULT);
                   frame.add(new JLabel(new ImageIcon(image)));
                   //frame.setIconImage(image); works
                   frame.setIconImage(imageScaled); // works not
                   frame.pack();
                   frame.setVisible(true);
              catch (IOException e)
                   System.err.println(e.getMessage());
                   e.printStackTrace(System.err);
    }

  • Problem with display of JFrame

    I have a run opperation in which i call a method that creates a j frame and displays it. all the j frame is used for is displaying the text "adding sample data...". It works fine when I have my main window open but when I have my layout editor open, the JFrame shows up grayed out. It clears after my samples are added. I have no Idea why it wont display correctly and I was just wondering if you had any ideas as to what whould cause this to happen. Thanks

    I can't be sure without seeing your code, or without more information about what it is your doing, but the problem could be threading. Is the JFrame that's showing up grayed out just supposed to tell the user to basically "please wait while I do something", and then dissapear after it's done working? If so, you should probably use a JDialog. In any case, try wrapping the code that opens the window in this:
    Thread opener new Thread(new Runnable(){
         public void run()
              // ... put your code that opens the window in here.  such as myFrame.setVisible(true);
    opener.start();

  • Problems with backspace in ServiceDesigner on IBM

    Hi
    Running ias9i we 1.1.
    When using the ServiceDesigner on a ex. Dell the backspace key functions fine, but when running on an IBM pc / laptop the backspace key do not function.
    Please advise
    null

    Hi,
    check that you aren't using JDK 1.3 on the IBM laptop.

  • Problem with backspace on Iphone 4.

    I have an Iphone 4 and I can't insert a word without deleting the entire sentence.

    Start at the bottom of page 25 "Editing Text":
    The User Guide is available at http://support.apple.com/manuals/ or downloadable from iTunes as an iBook.

  • Problem with JFrame resizing at runtime

    Hi All,
    I have a problem with resizing the JFrame at runtime. Even if i resize the JPanel. It is not affection on all the components over the frame. How can i solve that I am using AbsoluteLayout(jre1.6) and here i am going to provide you code snippet. My requirement is to resizt the form. If form is small in size then all the component should also be according tothe size of the form.
    public void initComponents(int size) {
    if(size >= 50) {
    x_co_or = 300;
    y_co_or = 300;
    } else if(size < 50) {
    x_co_or = 200;
    y_co_or = 200;
    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jButton1.setText("jButton1");
    jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, 110, 40));
    getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, x_co_or, y_co_or));
    pack();
    Can anybody suggest any idea/solution.
    Any idea/solution are most welcome.
    Regards,
    Pradeep Dubey

    How can i solve that I am using AbsoluteLayout(jre1.6)
    and here i am going to provide you code snippet.no need for the snippet, you're using absolute positioning, which means you're responsible for location and size on every single change.
    start coding now, take about a week, or you could use a layout manager, take maybe, 5 minutes

  • Problem with jDialog in a JFrame

    Hello to everyone...i'm newby java GUI developer, and i've got a problem with a JDialog within a JFrame...
    I made a JFrame which creates a new customized JDialog in his contructor, like this:
    MioJdialog dlg = new MioJdialog(this, true);
    dlg.setVisible(true);
    ...The "MioJdialog" class store his JFrame parent under a private attribute, in this way:
    class MioJdialog {...
    private Frame parent;
    public MioJdialog (Frame parent, boolean modal){
        this.parent=parent;
    ....}and here's the problem: when i try to close the parent JFrame with a command like this:
    parent.dispose();
    ( in order to close the whole window), sometimes happens that the JFrame is still visible on the screen...and i don't know why...
    got some hints?
    thanks to everyone!
    Edited by: akyra on Jan 14, 2008 4:36 AM
    Edited by: akyra on Jan 14, 2008 4:37 AM
    Edited by: akyra on Jan 14, 2008 4:37 AM

    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

Maybe you are looking for

  • How to use rule and send the same email to multiple recipents

    Hi, My requirement is to send the workitem to the multiple recipents. one of my reiend suggest me to use the rule but i don't know how to use that . can any one of you suggest me how to use rule in workflow. Also i want to send the same email to mult

  • Line separator in gui_download

    Hi all How can we write the fileds of an internal table into the file , with one field in one line Suppose ae have in internal table : Filed1                  Field2                Field3 ................. I want them to be written Filed1   Field2   

  • Please help this: JNLP association extensions confict with arguments

    Hello, Please help this: I use <argument> tag to transfer some parameters to JWS application. I also use <associatio> tag to associate a specila file(such as .zzz) to JNLP. But when I doulbe click .zzz file, my application only get "-open" and file p

  • Can't fill Color's in the Traced Image

    I have this image, of julie, what I did was that I copy and paste the image, then I made a new layer 2, I locked the first layer 1, and on the second layer where there is eye I pressed the ctrl+click on it to go to outline mode. I used the pen tool t

  • Class & Characteristics in variant configuration

    Hi PP guru's Pl  explain me in detail all the configuration path ,  spro , tcode for the above said . thanx in advance Regards, Vimalbalaji