FocusGained after caretUpdate in JTextArea

I have built a display with a JTextArea as well as several JTextFields; all share common cut,copy,paste actions. And all but one action works properly. However, when I select text activating the Cut menu item, then select Cut in the menu, the caretUpdate occurs before the JTextArea regains focus. Because I test for focus in caretUpdate before resetting the actions, the Cut and Copy actions remain enabled. Has anyone else seen this behavior and is there a workaround?

What you want to test for is whether the component is the permanent focus owner. When a menu takes the focus, the focusLost event is flagged as temporary. The KeyboardFocusManager keeps track of which component "really" has the focus so it can return it there when the menu goes away. You can find out which component that is with  KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner()That's how I do it, anyway.

Similar Messages

  • Creating a Frame with two JTextareas

    Please Help,
    I am currently studying java at the moment i am new to programming and find it difficult. However i have a problem using Swing. I am trying to create a "JTextarea" in the NORTH of the Frame and another "JTextarea" in the CENTER. I have write both bits of code to do this. When i added the second JTextarea i lost the first JTextArea when i ran the program. I figure the program is reading the first part of code then overwriting it with the second part of the code. Can anyone help?
    The code i wrote was as follows;
    //Java extension Package
    import javax.swing.*;
    //Java core Pakages
    import java.awt.*;
    import java.awt.event.*;
    public class Panel extends JFrame
    public JTextArea textArea1, textArea2;
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Swing Example");
    //Displays NORTH JTextArea
    JTextArea textArea1 = new JTextArea("Click something to see what happens...");
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(textArea1,BorderLayout.NORTH);
    //Displays text in CENTER
    JTextArea textArea2 = new JTextArea("This is a JTextArea\n" +
    "component. It is placed in\n" +
    "the Center position after the\n" +
    "JTextArea is placed North,\n" +
    "the three JButtons are\n" +
    "placed in a West JPanel\n" +
    "and the JComboBox\n" +
    "components is placed in an\n" +
    "East JPanel.");
    frame.getContentPane() .setLayout(new BorderLayout());
    frame.getContentPane() .add(textArea2,BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    }

    Hello,
    Thankyou for helping me with that problem it is much appreciated no doubt ill have some more questions.
    L. Tambiah

  • Save JTextArea content to database problem.

    after save the JTextArea content in database,
    how to show them as you input,
    my main meaning is how to save the enter?
    thanks!

    Hi,
    You can use the following code to export to memory
    *data variable required for background processing
    data: wa_indx type indx.
    *EXPORT Internal Table TO MEMORY ID 'XYZ'.
    *part for background processing
      export tab = <your table> to database indx(xy) from wa_indx client
      sy-mandt id 'XYZ'.
    the following code will import from Memory and clear memory
    *data variable required for background processing
    data: wa_indx type indx.
    imports from database the list sent by the calling program
    IMPORT tab = <your table> FROM DATABASE indx(xy) TO wa_indx CLIENT sy-mandt
    ID 'XYZ'.
    deletes the data to save wastage of memory
    DELETE FROM DATABASE indx(xy)
      CLIENT sy-mandt
      ID 'XYZ'.
    Regards,
    Samson Rodrigues.

  • JTextArea stop work after a method involke by other class

    This is my code:
    * Console.java
    * Created on November 5, 2007, 5:23 PM
    package javaapplication6;
    import java.io.IOException;
    import java.lang.String;
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.net.Socket;
    * @author  root
    public class Console extends javax.swing.JFrame {
        private LoadFirmware    loadfirmware;
        /** Creates new form Console */
        public Console() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            jButton4 = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenuItem1 = new javax.swing.JMenuItem();
            jMenuItem2 = new javax.swing.JMenuItem();
            jMenu2 = new javax.swing.JMenu();
            jMenuItem3 = new javax.swing.JMenuItem();
            jMenuItem4 = new javax.swing.JMenuItem();
            jMenuItem5 = new javax.swing.JMenuItem();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("append");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jButton2.setText("Exit");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            jButton3.setText("Switch to Program Mode");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
            jButton4.setText("Switch to Run Mode");
            jButton4.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton4ActionPerformed(evt);
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jButton1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jButton3)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jButton4)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jButton2)
                    .addContainerGap(170, Short.MAX_VALUE))
                .add(jPanel1Layout.createSequentialGroup()
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 622, Short.MAX_VALUE)
                    .add(20, 20, 20))
            jPanel1Layout.linkSize(new java.awt.Component[] {jButton1, jButton2}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
            jPanel1Layout.linkSize(new java.awt.Component[] {jButton3, jButton4}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 247, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 90, Short.MAX_VALUE)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton1)
                        .add(jButton3)
                        .add(jButton4)
                        .add(jButton2))
                    .add(98, 98, 98))
            jMenu1.setText("File");
            jMenuItem1.setText("New");
            jMenu1.add(jMenuItem1);
            jMenuItem2.setText("Open");
            jMenu1.add(jMenuItem2);
            jMenuBar1.add(jMenu1);
            jMenu2.setText("Tool");
            jMenuItem3.setText("Load Firmware");
            jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    load_firmware(evt);
            jMenu2.add(jMenuItem3);
            jMenuItem4.setText("Start Console Service");
            jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    StartService(evt);
            jMenu2.add(jMenuItem4);
            jMenuItem5.setText("Monitor");
            jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem5ActionPerformed(evt);
            jMenu2.add(jMenuItem5);
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>
        private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {                                          
            CmdHandle loadMon = new CmdHandle();
            loadMon.main(null);
        private void StartService(java.awt.event.ActionEvent evt) {                             
                try {
              //Process proc = Runtime.getRuntime().exec("java MyTest");
              Runtime rt = Runtime.getRuntime();
              String[] cmd={"cmd.exe" , "/c" , "start" ,"c:/cygwin/home/root/ugconsole/main.exe"};
                    //String[] cmd={"c:/cygwin/home/root/ugconsole/main.exe"};
              rt.exec(cmd);
              //System.out.println("***Executed java MyTest***");
         } catch (IOException e) {e.printStackTrace();}
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            appendmsg("apn msg\n");
        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            Tcp cmd = new Tcp();
            cmd.PID_SwToRunMode();
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            Tcp cmd = new Tcp();
            cmd.ProgramMode();
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            System.exit(0);
        private void load_firmware(java.awt.event.ActionEvent evt) {                              
            loadfirmware.main(null);
        public static void PROGRAMPAGE(){
            String command = "PROGRAMPAGE";
            writer.print(command);
            writer.flush();
          //  appendmsg(command);
            try {
                String response = reader.readLine();
                System.out.println(response);
            } catch (IOException ex) {
                ex.printStackTrace();
        public static void appendmsg(String msg){
           // jTextArea1.append("but this ok le");
            jTextArea1.append(msg);
            System.out.println(msg);
        public static void main(String args[])
             throws IOException
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Console().setVisible(true);
            final int DEST_PORT = 20000;
            s = new Socket("localhost", DEST_PORT);
            in = s.getInputStream();
            out = s.getOutputStream();
            reader = new BufferedReader(new InputStreamReader(in));
            writer = new PrintWriter(out);
            //String asd = "asd";
            //writer.print(asd);
           // writer.flush();
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JButton jButton4;
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JMenuItem jMenuItem2;
        private javax.swing.JMenuItem jMenuItem3;
        private javax.swing.JMenuItem jMenuItem4;
        private javax.swing.JMenuItem jMenuItem5;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        public static javax.swing.JTextArea jTextArea1;
        // End of variables declaration
        private static Socket s;
        private static InputStream in;
        private static OutputStream out;
        private static BufferedReader reader;
        private static PrintWriter writer;   
    }After PROGRAMPAGE() is call, appendmsg() won't work anymore.
    anyone can help ? thank!
    Edited by: mjava on Nov 15, 2007 7:26 PM

    -> After PROGRAMPAGE() is call, appendmsg() won't work anymore.
    How do you know? That method isn't invoked anywhere in your posted code.
    We don't all use JDK6 so we don't all have access to GroupLayout. Design a demo that we can all run that duplicates your problem.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

  • JTextArea requestFocusInWindow -- after a moment focus moves on?

    Hey, I'm trying to give the keyboard focus to a JTextArea. by calling textArea.requestFocusInWindow(). What I'm finding is that the text area gets the keyboard focus for a brief moment, and then the focus moves onto the next text area in the application and stays there. What the?

    What the? And that is exactly my comment.
    Your code is obviosly wrong. We have no idea the context of your question. So we can't offer any help. Now is a good time to learn how to ask a proper question on the forum.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • JTextArea is not focused after minimize a window

    Hi guys,
    I have a screen in a JPanel and has a JTextArea (and a ScrollPane attached) where the user types his/her information. So, when he minimizes the entire application and then restore it the cursor is lost.
    I�m using JDK 1.4.1_01 and appreciate your help.

    question
    ========
    hi,
    Are you having many number of components on your frame or is that you are having only one a textarea on the same.
    the following code might help you so some extent,
    import java.awt.*;
    import javax.swing.*;
    public class JTextAreaTest extends JFrame
         public JTextAreaTest()
              JPanel pan = (JPanel) getContentPane();
              JTextArea ta = new JTextArea();
              int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
              JScrollPane sp = new JScrollPane(ta,v,h);
              pan.add(sp);
         public static void main(String args[])
              JTextAreaTest tat = new JTextAreaTest();
              tat.setSize(200,200);
              tat.setVisible(true);
    Regards,
    Balaji.SN

  • Edit behavior in Component (JSpinner, JTextArea, ect...) objects

    There is one thing that is annoying me with the Jxxxx Objects. Any of the editable objects (JSpinner, JTextArea, ect...) after a value is in them, or if you are using a model that has a default value (like SpinnerNumberModel ), when you click in the field area, the focus changes to the component, but it does not select what it in it, so you have to either backspace, delete or select everything with the mouse to enter a new value. For example, a JSpinner with a SpinnerNumberModel with a value of 2.9, after clicking in the field and if you enter 4.5 to change it, you end up with 2.94.5 instead of 4.5. Is there a way to universally have the objects automatically highlight the value (like if you selected it all with the mouse) so if you just start typing it replaces the current value instead of adding to it? Widgets in other languages like tcl/tk, an nearly all programs that I have noticed, highlight the current value when the focus changes to that object. I am fairly new to Java, so am I missing something? Thanks!

    I did some poking around width using FocusListeners and found a post that had what I was looking for for JTextArea, and modified it for JSpinners also, here it is...
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JSpinner;
    import javax.swing.SwingUtilities;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.text.JTextComponent;
    public class autoSelect implements FocusListener, ChangeListener {
         public void focusGained(FocusEvent e) {          
              System.out.println(e.getSource());
              if (e.getSource() instanceof JTextComponent) {
                   final JTextComponent textComponent=((JTextComponent)e.getSource());
                   SwingUtilities.invokeLater(new Runnable(){
                     public void run() {textComponent.selectAll();}});
              } else if (e.getSource() instanceof JSpinner) {
                   final JSpinner vcomp = (JSpinner)e.getSource();
                   SwingUtilities.invokeLater(new Runnable(){
                     public void run() {((JSpinner.DefaultEditor )
                               vcomp.getEditor ()).getTextField().selectAll(); }});
         public void focusLost(FocusEvent e) { }
         public void stateChanged(ChangeEvent e) {
              if (e.getSource() instanceof JSpinner) {
                   final JSpinner vcomp = (JSpinner)e.getSource();
                   SwingUtilities.invokeLater(new Runnable(){
                     public void run() {((JSpinner.DefaultEditor )
                               vcomp.getEditor ()).getTextField().selectAll(); }});
    }For JTextArea's I just add it as a listener,
    private autoSelect selFill = new autoSelect();
    custName = new JTextArea();
    custName.addFocusListener(selFill);For JSpinners it is more involved,
    private autoSelect selFill = new autoSelect();
    startTime = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 24.0, .1));
    ((JSpinner.DefaultEditor )startTime.getEditor ()).getTextField().addFocusListener(selFill);
    startTime.addChangeListener(selFill);I would not use it for large JTextArea's, just for those small ones for a one line/word input, or for a number.
    Thanks for all the Help!

  • How to refresh a JPanel/JTextArea

    My main problem is that I don't know how to correctly refresh a JTextArea in an Applet. I have an Applet with 2 internal frames. Each frame is comprised of a JPanel.
    The first internal frame calls the second one as shown below:
    // Set an internal frame for Confirmation and import the Confirm class into it//
    Container CF = nextFrame.getContentPane();
    //<Jpanel>
    confirmation = new Confirmation( );
    CF.add ( confirmation, BorderLayout.CENTER );
    mFrameRef.jDesktopPane1.add(nextFrame,JLayeredPane.MODAL_LAYER);
    currentFrame.setVisible(false); // Hide this Frame
    nextFrame.setVisible(true); // Show Next Frame/Screen of Program
    confirmation (Jpanel) has a JTextArea in it. When it's called the first time it displays the correct information (based on choices from the first frame). If a user presses the back button (to return to first frame) and changes something, it doesn't refresh in the JTextArea when they call the confirmation(Jpanel) again. I used System.out.println (called right after jtextareas code), and it shows the info has indeed changed...I guess I don't know how to correctly refresh a JTextArea in an Applet. Here is the relevent code for the 2nd Internal Frame (confirmation jpanel):
    // Gather Info to display to user for confirmation //
    final JTextArea log = new JTextArea(10,35);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    log.append("Name: " storeInfoRef.getFirstName() " "
    +storeInfoRef.getLastName() );
    log.append("\nTest Project: " +storeInfoRef.getTestProject() );
    JScrollPane logScrollPane = new JScrollPane(log);

    Here is the relevant code that I am having the problem with...
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class Confirmation extends JPanel {
    // Variables declaration
    private StoreInfo storeInfoRef; // Reference to StoreInfo
    private MFrame mFrameRef; // Reference to MFrame
    private Progress_Monitor pmd; // Ref. to Progress Monitor
    private JLabel ConfirmMessage; // Header Message
    private JButton PrevButton;                // Navigation Button btwn frames
    private JInternalFrame prevFrame, currentFrame; // Ref.to Frames
    // End of variables declaration
    public Confirmation(MFrame mFrame, StoreInfo storeInfo) {
    mFrameRef = mFrame; // Reference to MFrame
    storeInfoRef = storeInfo; // Reference to Store Info
    prevFrame = mFrameRef.FileChooserFrame; // Ref. to Previous Frame
    currentFrame = mFrameRef.ConfirmationFrame; // Ref. to this Frame
    initComponents();
    // GUI for this class //
    private void initComponents() {
    ConfirmMessage = new JLabel();
    PrevButton = new JButton();
    UploadButton = new JButton();
    setLayout(new GridBagLayout());
    GridBagConstraints gridBagConstraints1;
    ConfirmMessage.setText("Please confirm that the information "
    +"entered is correct");
    add(ConfirmMessage, gridBagConstraints1);
    // Gather Info to display to user for confirmation //
    final JTextArea log = new JTextArea(10,35);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    log.append("Name: " storeInfoRef.getFirstName() " "
    +storeInfoRef.getLastName() );
    log.append("\nTest Project: " +storeInfoRef.getTestProject() );
    log.append("\nTest Director: " +storeInfoRef.getTestDirector() );
    log.append("\nTest Location: " +storeInfoRef.getTestLocation() );
    log.append("\nDate: " +storeInfoRef.getDate() );
    String fileOutput = "";
    Vector temp = new Vector( storeInfoRef.getFiles() );
    for ( int v=0; v < temp.size(); v++ )
    fileOutput += "\n " +temp.elementAt(v);  // Get File Names
    log.append("\nFile: " +fileOutput );
    // log.repaint();
    // log.validate();
    // log.revalidate();
    JScrollPane logScrollPane = new JScrollPane(log);
    System.out.println("Name: " storeInfoRef.getFirstName() " " +storeInfoRef.getLastName() );
    System.out.println("Test Project: " +storeInfoRef.getTestProject() );
    System.out.println("Test Director: " +storeInfoRef.getTestDirector() );
    System.out.println("Test Location: " +storeInfoRef.getTestLocation() );
    System.out.println("Date: " +storeInfoRef.getDate() );
    System.out.println("File: " +fileOutput );
    // End of Gather Info //
    add(logScrollPane, gridBagConstraints1);
    PrevButton.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    PrevButtonMouseClicked(evt);
    PrevButton.setText("Back");
    JPanel Buttons = new JPanel();
    Buttons.add(PrevButton);
    add(Buttons, gridBagConstraints1);
    // If User Presses 'Prev' Button //
    private void PrevButtonMouseClicked(java.awt.event.MouseEvent evt) {
    try
    currentFrame.setVisible(false); // Hide this Frame
    prevFrame.setVisible(true); // Show Next Frame/Screen of Program
    catch ( Throwable e ) // If A Miscellaneous Error
    System.err.println( e.getMessage() );
    e.printStackTrace( System.err );
    }// End of Confirmation class

  • How to put a Jpanel always over a JtextArea ?

    I want to have a little Jpanel above a JTextArea.
    At the initialize section, I add first the Jpanel and after the JtextArea (both in a 'parent' Jpanel with null layout)
    When I run the program I see the Jpanel over the JtextArea, but when I write on it and it reaches the area when the Jpanel is placed, the JtexArea brings to front and the Jpanel is no longer visible.
    So, how can I have my Jpanel on top always ?
    And another question , is there a hierarchy that control that I Jpanel is always over a Jbutton (even if the initial z-order of the button is higher than the Jpanel's)
    Thanks
    ( I do not send any code because it is so simple as putting this two components into a Jpanel)

    tonnot wrote:
    And another question , is there a hierarchy that control that I Jpanel is always over a Jbutton (even if the initial z-order of the button is higher than the Jpanel's)JLayeredPane
    ( I do not send any code because it is so simple as putting this two components into a Jpanel)Try it with a JLayeredPane and if you still have problems, post a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html].
    db

  • Keyevent used for setMnemonic show in editable jtextarea

    I don't know if this has been fix. I notice that if I used the setMnemonic to access a editable jtextarea, that the key I used is inserted into the jtextarea. After searching the web, I found nothing about this problem.
    So, I took the program from the java tutorial, MenuDemo.java and reproduct the same problem but setting the jtextarea to editable (output.setEditable(true). It happens everytime. Below is the MenuDemo.java with the change. By selecting t or b in the A Menu menu,then which ever t or b used will show up in the text area after the expected line displays. I am using 1.5 so this problem may have been fix.
    If anyone knows if it has or a work around, please let me know.
    Thanks
    Kevin
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    * This class adds event handling to MenuLookDemo.
    public class MenuDemo extends JFrame
    implements ActionListener, ItemListener {
    JTextArea output;
    JScrollPane scrollPane;
    String newline = "\n";
    public MenuDemo() {
    JMenuBar menuBar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Add regular components to the window, using the default BorderLayout.
    Container contentPane = getContentPane();
    output = new JTextArea(5, 30);
    output.setEditable(true);
    scrollPane = new JScrollPane(output);
    contentPane.add(scrollPane, BorderLayout.CENTER);
    //Create the menu bar.
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription(
    "The only menu in this program that has menu items");
    menuBar.add(menu);
    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item",
    KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription(
    "This doesn't really do anything");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem("Both text and icon",
    new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_B);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_D);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    //a group of radio button menu items
    menu.addSeparator();
    ButtonGroup group = new ButtonGroup();
    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    //a group of check box menu items
    menu.addSeparator();
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    //a submenu
    menu.addSeparator();
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);
    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_2, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menuItem = new JMenuItem("Another item");
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menu.add(submenu);
    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription(
    "This menu does nothing");
    menuBar.add(menu);
    public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Action event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")";
    output.append(s + newline);
    public void itemStateChanged(ItemEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Item event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")"
    + newline
    + " New state: "
    + ((e.getStateChange() == ItemEvent.SELECTED) ?
    "selected":"unselected");
    output.append(s + newline);
    // Returns just the class name -- no package info.
    protected String getClassName(Object o) {
    String classString = o.getClass().getName();
    int dotIndex = classString.lastIndexOf(".");
    return classString.substring(dotIndex+1);
    public static void main(String[] args) {
    MenuDemo window = new MenuDemo();
    window.setTitle("MenuDemo");
    window.setSize(450, 260);
    window.setVisible(true);

    Yes your are correct. I forgot why I went to 1.5 but until better time come along and I can get a new computer, I will have to live with 1.4.2._06. But, it did fit my problem.

  • Bug in JTextArea/JTextPane ??

    Hi,
    I am facing huge memory leak problems with JTextArea/JTextPane. After considerable investigation, I found out that the Document associated with the component is not being GC'ed properly. I ran OptimizeIt and found out that the memory is being consumed by the JTextPane.setText() method. I have implmented a HTML viewer to display large amounts of HTML data and it is leaking memory like crazy on each successive execution. Any thoughts ??
    JDK1.4.2_01, WinXP
    Here is the code fragment:
    public class ReportViewer extends BaseFrame implements FontChange_int
         private     String          cReport;          
         private boolean          testMode = false;     
         // Graphical components
         private     BorderLayout     cMainLayout;
         private     JButton          cClose;
         private     JTextPane     cRptPane;
         private     Button          cClose2;
         private ViewUpdater cViewUpdater = null;
         // Constants
         final     static     int     startupXSize = 650;
         final     static     int     startupYSize = 500;
         // Methods
         public ReportViewer(String report, ReportMain main)
              // BaseFrame extends JFrame
              super("Reports Viewer", true, startupXSize, startupYSize);
              testMode = false;
              cReport = report;
              cViewUpdater = new ViewUpdater();
              initialize();
         public void initialize()
              // Create main layout manager
              cMainLayout = new BorderLayout();
              getContentPane().setLayout(cMainLayout);
              // Quick button bar - print, export, save as
              JToolBar     topPanel = new JToolBar();
              topPanel.setBorder(new BevelBorder(BevelBorder.RAISED) );
              java.net.URL     url;
              topPanel.add(Box.createHorizontalStrut(10));
              url = Scm.class.getResource("images/Exit.gif");
              cClose = new Button(new ImageIcon(url), true);
              cClose.setToolTipText("Close Window");
              topPanel.add(cClose);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              // Main view window - HTML
              cRptPane = new JTextPane();
              cRptPane.setContentType("text/html");
              cRptPane.setEditable(false);
              JScrollPane sp = new JScrollPane(cRptPane);
              getContentPane().add(sp, BorderLayout.CENTER);
              // Main button - Close
              JPanel     bottomPanel = new JPanel();
              url = Scm.class.getResource("images/Exit.gif");
              cClose2 = new Button(new ImageIcon(url), "Close");
              bottomPanel.add(cClose2);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              cClose.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              cClose2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              show();
              cViewUpdater.setText(cReport);
              SwingUtilities.invokeLater(cViewUpdater);
         protected void
         closeWindow()
              super.closeWindow();
              // If I add the following lines, the GC reclaims
    // part of the memory but does not flush out the text
    // component as a whole
              /*Document doc = cRptPane.getDocument();
              try
                   doc.remove(0,doc.getLength());
              catch(Exception e) {;}
              doc=null; */
              cRptPane=null;
              cReport = null;
              cViewUpdater = null;
              dispose();
         private class ViewUpdater implements Runnable
              private String cText = null;
              public ViewUpdater() {;}
              public void
              setText(String text) {
                   cText = text;
              public void
              run() {
                   cRptPane.setText(cText);
                   cRptPane.setCaretPosition(0);
                   cText = null;
         // Local main - for testing
         public static void main(String args[])
              //new ReportViewer(str,comp);
    Sudarshan
    www.spectrumscm.com

    Hi,
    I am facing huge memory leak problems with JTextArea/JTextPane. After considerable investigation, I found out that the Document associated with the component is not being GC'ed properly. I ran OptimizeIt and found out that the memory is being consumed by the JTextPane.setText() method. I have implmented a HTML viewer to display large amounts of HTML data and it is leaking memory like crazy on each successive execution. Any thoughts ??
    JDK1.4.2_01, WinXP
    Here is the code fragment:
    public class ReportViewer extends BaseFrame implements FontChange_int
         private     String          cReport;          
         private boolean          testMode = false;     
         // Graphical components
         private     BorderLayout     cMainLayout;
         private     JButton          cClose;
         private     JTextPane     cRptPane;
         private     Button          cClose2;
         private ViewUpdater cViewUpdater = null;
         // Constants
         final     static     int     startupXSize = 650;
         final     static     int     startupYSize = 500;
         // Methods
         public ReportViewer(String report, ReportMain main)
              // BaseFrame extends JFrame
              super("Reports Viewer", true, startupXSize, startupYSize);
              testMode = false;
              cReport = report;
              cViewUpdater = new ViewUpdater();
              initialize();
         public void initialize()
              // Create main layout manager
              cMainLayout = new BorderLayout();
              getContentPane().setLayout(cMainLayout);
              // Quick button bar - print, export, save as
              JToolBar     topPanel = new JToolBar();
              topPanel.setBorder(new BevelBorder(BevelBorder.RAISED) );
              java.net.URL     url;
              topPanel.add(Box.createHorizontalStrut(10));
              url = Scm.class.getResource("images/Exit.gif");
              cClose = new Button(new ImageIcon(url), true);
              cClose.setToolTipText("Close Window");
              topPanel.add(cClose);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              // Main view window - HTML
              cRptPane = new JTextPane();
              cRptPane.setContentType("text/html");
              cRptPane.setEditable(false);
              JScrollPane sp = new JScrollPane(cRptPane);
              getContentPane().add(sp, BorderLayout.CENTER);
              // Main button - Close
              JPanel     bottomPanel = new JPanel();
              url = Scm.class.getResource("images/Exit.gif");
              cClose2 = new Button(new ImageIcon(url), "Close");
              bottomPanel.add(cClose2);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              cClose.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              cClose2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              show();
              cViewUpdater.setText(cReport);
              SwingUtilities.invokeLater(cViewUpdater);
         protected void
         closeWindow()
              super.closeWindow();
              // If I add the following lines, the GC reclaims
    // part of the memory but does not flush out the text
    // component as a whole
              /*Document doc = cRptPane.getDocument();
              try
                   doc.remove(0,doc.getLength());
              catch(Exception e) {;}
              doc=null; */
              cRptPane=null;
              cReport = null;
              cViewUpdater = null;
              dispose();
         private class ViewUpdater implements Runnable
              private String cText = null;
              public ViewUpdater() {;}
              public void
              setText(String text) {
                   cText = text;
              public void
              run() {
                   cRptPane.setText(cText);
                   cRptPane.setCaretPosition(0);
                   cText = null;
         // Local main - for testing
         public static void main(String args[])
              //new ReportViewer(str,comp);
    Sudarshan
    www.spectrumscm.com

  • How do i update a JTextArea?

    Hey
    I have a main GUI class where i can add one number to an ArrayList in an ohter class (Basket). After i added the number to the ArrayList
    i can click a button to open anohter window (which is created in BasketGUI class) where a JTextArea are showing the numbers i have
    added in the ArrayList.
    But notthing is showing, i know the addition to the ArrayList works because it works with a System.out.println.
    I have to post alot of code, so you could just skip the code and eksplain to me in generel how to update a JTextArea.
    BasketGUI:
    * Basket.java
    * Created on 5. februar 2008, 15:29
    package userclasses;
    import java.util.ArrayList;
    * @author  Lille mus
    public class BasketGUI extends javax.swing.JFrame {
        private Basket basket;
        private Stock stock;
        private String newline = "\n";
        /** Creates new form Basket */
        public BasketGUI() {
            stock = new Stock();
            basket = new Basket();
            initComponents();
        public String showBasket(){
            ArrayList newBasket = basket.getArrayList();
            String returnBasket = "";
            for(Object item : newBasket){
                returnBasket += item+newline;
            return returnBasket;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Indk?bskurv");
            jLabel1.setText("Indk?bskurv");
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jTextArea1.setText(stock.printAllStockItems());
            jTextArea1.setText(showBasket());
            jScrollPane1.setViewportView(jTextArea1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(21, 21, 21)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(224, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addGap(20, 20, 20)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(159, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new BasketGUI().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        // End of variables declaration
    }This code is what happends when i click the button which adds a number to the ArrayList:
    private void putInBasket(java.awt.event.ActionEvent evt) {                            
            //Integer itemId = Integer.parseInt(itemIdField.getText());
            basket.addItemToBasket(3);
            System.out.println(basket.showBasket());
        }Basket class:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package userclasses;
    import java.util.ArrayList;
    * @author Jesper
    public class Basket {
        private ArrayList<Integer> basket;
        private String returnBasket;
        private Stock stock;
        private String newline = "\n";
        public Basket(){
            basket = new ArrayList<Integer>();
            add4ItemsToBasket();
        public void addItemToBasket(int itemId){
            basket.add(itemId);
        public void add4ItemsToBasket(){
            addItemToBasket(1);
            addItemToBasket(2);
        public String showBasket(){
            for(Integer item : basket){
                returnBasket += item+newline;
            return returnBasket;
        public ArrayList getArrayList(){      
            return basket;
    }Thank you!

    okay... i cant figure out the logic in this. i have put this code into the BasketGUI class:
    public void setBasketList(){
            basketListTextArea.append(basket.showBasket());
        }this function i call in my MainGUI here:
    private void putInBasket(java.awt.event.ActionEvent evt) {                            
            //Integer itemId = Integer.parseInt(itemIdField.getText());
            basket.addItemToBasket(3);
            basketGUI.setBasketList();
            System.out.println(basket.showBasket());
        }What am i doing wrong?

  • Selection problem in JTextArea

    hi all
    i have a TextArea in which i have some coded charecters in a group of ten charactes i treet these ten characters as a single character ,so when i delete or insert these charactes all these charactes r deleted and no other character r inserted in between , i do it with the caretListener,
    But the problem which i face is on the selection i want to select these characters as when we select some part of the URL then it is selected completely.
    help in the prob.

    this might work
    paste some text into the textArea (ensure it contains a sequence "12345")
    click anywhere in area of 12345
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    class Testing extends JFrame
      String specialChars = "12345";
      boolean settingCaret = false;
      public Testing()
        setSize(200,200);
        setLocation(300,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        final JTextArea ta = new JTextArea(10,10);
        JScrollPane sp = new JScrollPane(ta);
        sp.setPreferredSize(new Dimension(175,150));
        JPanel jp = new JPanel();
        jp.add(sp);
        getContentPane().add(jp);
        pack();
        ta.addCaretListener(new CaretListener(){
          public void caretUpdate(CaretEvent ce){
            if(settingCaret == false)
              int startPos = ta.getText().indexOf(specialChars);
              if(startPos > -1)
                if(ta.getCaretPosition() >= startPos && ta.getCaretPosition() <= startPos+specialChars.length())
                  settingCaret = true;
                  ta.setSelectionStart(startPos);
                  ta.setSelectionEnd(startPos+specialChars.length());
                settingCaret = false;
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • SQLException after end of result set

    hi guys.
    im in a lot of bother at the moment.
    i have a GUI with a database in mysql. my gui is a recommender system and so users need to log in etc...
    i know for certain that the gui does connect to the database because when a new user enters there details it does get updated in the database.
    my problem is that when the user tries to gain acces to the system by going to the 'current user' and entering there details nothing happens.
    i am finding it very difficult to find out what the problem is, i have been trying for over a week but no luck and im hoping somebody will know how to help me.
    please could somebody help me here, i have a very short time aswell. monday.
    here is my code below.
    thank-you very much for your help
    its not normal to post the whole class here but im really really stumped.
    the errors that appears in the dos window is SQLException After end of result set.
    *     Function: This class is used for loggin in. It looks for the user name and password           *
    *          the user enters in the database. If there is no match an error message will appear     *
    *          to the user. If there is a match the system logs the user in and dispalys the chose      *
    *          topic page                                   *
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import com.mysql.jdbc.Driver;
    import java.sql.*;
    import java.awt.BorderLayout;
    import java.io.IOException;
    public class CurrentUserFrame extends JPanel implements ActionListener {
         // private is used so object variables cannot be changes by another class.
         private JButton loginButton = null ;
         private JTextField userName = null ;
         private JTextField password = null ;
         private JLabel userLabel = null ;
         private JLabel passwordLabel = null ;
         Boolean loginSuccess ;
         private JPanel cardPanel = null ;
         public CardLayout cardLayout = null ;
         protected static com.mysql.jdbc.Driver mysqlDriver = null;
         String passwordDbase ;
         String usernameDbase ;
              private CardLayout getCardLayout () {
              if (cardLayout == null ) {
              cardLayout = new CardLayout () ;
              return cardLayout ;
         private JPanel getCardPanel () {
         if (cardPanel == null) {
         cardPanel = new JPanel () ;
         return cardPanel ;
         // creates the background colours for the panels by specifying the amounts of red
         // green, blue where 0.5F is the least amount and 1.0F is the most
         Color currentTitleColor = new Color (0.58F, 0.73F, 0.83F) ;
         Color currentMainPanelColor = new Color (0.980F, 0.973F, 0.843F) ;
         public CurrentUserFrame ()
              setLayout (new BorderLayout ()) ;
              JPanel mainCPnl = new JPanel () ;
              mainCPnl.setLayout (new BorderLayout ()) ;
              JPanel mainPanel = new JPanel () ;
              // maindisplaypanel will be set with a borderlayout
              mainPanel.setLayout (new BorderLayout ());
              JPanel descriptionPanel = new JPanel ();
              descriptionPanel.setLayout(new BorderLayout ());
              // creates a textarea for the title and description
              JTextArea description2 = new JTextArea ("\t\tCurrent User Page\n\n" +
              "Please enter your user name and password to login.\n\n" +
              "If you have forgotten your user name or password click on " +
              " 'FORGOT PASSWORD'.") ;
              // stops the text area being edited by the user
              description2.setEditable (false) ;
              // once the text in description reaches the end of the textarea it will start a new line
              description2.setLineWrap (true) ;
              //sets the background colour of the textarea
              description2.setBackground (currentTitleColor) ;
              //sets the type of font with its size for the description textarea
              description2.setFont (new Font ("TimesRoman", Font.BOLD, 16)) ;
              // the descriptionpanel will be placed in the mainpanel at the top.
              mainPanel.add (descriptionPanel, BorderLayout.NORTH) ;
              descriptionPanel.add(description2, BorderLayout. NORTH) ;
              JPanel currentUserPanel = new JPanel () ;
              currentUserPanel.setLayout (new BoxLayout (currentUserPanel, BoxLayout.Y_AXIS)) ;
              // creates a button with an actionlistener so t can carryout a task when it is pressed.
              // the settooltiptext () method displays a message when the user hovers over the button with the curser
              loginButton = new JButton ("Log In") ;
              loginButton.addActionListener(this) ;
              loginButton.setToolTipText ("Logs you into the system") ;
              // creates a text field which is 25 characters in length for the user to enter their name
              userName = new JTextField (25) ;
              // creates a text field which is 15 characters in length for the user to enter their password
              password = new JPasswordField (15) ;
              userLabel = new JLabel ("User Name") ;
              passwordLabel = new JLabel ("Password") ;
              //adds the text fields and the JLabels to the currentuserPanel
              currentUserPanel.add (userLabel) ;
              currentUserPanel.add (userName) ;
              currentUserPanel.add (passwordLabel) ;
              currentUserPanel.add (password) ;
              currentUserPanel.add (loginButton) ;
              JPanel loginPanel = new JPanel () ;
              loginPanel.setLayout (new FlowLayout (FlowLayout.CENTER, 0, 170)) ;
              loginPanel.setBackground (currentMainPanelColor) ;
              loginPanel.add (currentUserPanel, BorderLayout.CENTER) ;
              mainPanel.add (loginPanel, BorderLayout.CENTER) ;
              JPanel chooseTopicCard = new JPanel () ;
              chooseTopicCard.setLayout (new GridLayout (0, 1, 0, 10)) ;
              ChooseTopic frame8 = new ChooseTopic () ;
              frame8.setVisible (true) ;
              chooseTopicCard.add(frame8) ;
              // this will create the panel for the maincontent area and sets the layout
              JPanel cp = getCardPanel();
              cp.setLayout(getCardLayout());
              cp.add("card3",mainPanel) ;
              cp.add("card7", chooseTopicCard) ;
              cardLayout.show (getCardPanel () , "card3") ;
              // this adds the cardlayout to the main panel and then adds the mainpanel screen
              mainCPnl.add(cp) ;
              this.add (mainCPnl) ;
         public void actionPerformed (ActionEvent event) {
              Object source = event.getSource () ;
              if (source == loginButton) {
                   // creates a string to connect to the local host and database
                   // the following 10 lines of code is from the mysql website
                   String url = "jdbc:mysql://:3306/project" ;
                   Connection con = null ;
                   // com.mysql.jdbc.Driver is a folder downloaded from mysql website
                   try {
                        mysqlDriver = (com.mysql.jdbc.Driver) Class.forName ("com.mysql.jdbc.Driver").newInstance () ;
                   } catch ( Exception E) {
                   throw new RuntimeException ("Can not load driver class com.mysql.jdbc.Driver") ;
                   try {
                   // attempts a connection with the computer     
                   // root is used as a default so i can have full access to the database
                   con = DriverManager.getConnection (url,"root","") ;
                   // trys to log in to the database
                   // statement is a mysql class
                   Statement select = con.createStatement ();
                   ResultSet result = select.executeQuery ("select * from user_login") ;                    
                   String userNameText = userName.getText();
                   String passwordText = password.getText();
                   if (userNameText.equals("") || passwordText.equals("")) {
                        JOptionPane okoptionpane = new JOptionPane () ;
                        okoptionpane.showMessageDialog(null, "You have entered your username or password incorrectly, please try again") ;
                        while ((result.next()) && (result != null))
                             //String usernameval ;
                             //String passwordval ;
                             passwordDbase = result.getString("password");
                             usernameDbase = result.getString("user_name");
                             //passwordDbase = "password";
                             //usernameDbase = "user_name";
                             if ((passwordDbase.equals(passwordText)) && (usernameDbase.equals(userNameText))) {
                             cardLayout.show(getCardPanel(), "Card7");                         
                        catch (Exception e) {
                        e.printStackTrace() ;
                        finally {
                        if (con != null ) {               
                             try {con.close () ;  }
                             catch (Exception e) {
                             e.printStackTrace () ;
    LIZ

    ooppps, very sorry, you can guess im new to this forum. sorry again. i thought maybe the whole code was needed.
    i have posted all the output from the dos window.
    java.sql.SQLException: After end of result set
    at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:3628)
    at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1763)
    at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1827)
    " at CurrentUserFrame.actionPerformed(CurrentUserFrame.java:214) "
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Unknow
    n Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
    ce)
    at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    i think it is mainly line that is in speach marks. line 214.
    the error that comes up says." after end of result set "
    thank-you
    and sorry once again, im in a bit of a panic,
    Liz

  • How do I give the program time to write to a JTextArea field

    Hi,
    I created a swing application which listens for user input with a simple button that starts a whole process of reading database records, looping the records, writing files to a file system etc.
    What I would like to do, is to present the user of the application with regular feedback on how far the program is in the overall execution of this big task.
    something like:
    - file a.pdf moved
    - file b.gif moved
    etc..
    I write these line of text to a JTextArea control in my main panel.
    I know the routines work, as feedback from the other controls are posted without problems in the JTextArea.
    In a previous life (...those days) I did some work with .Net, and with something similar I learned that sometimes the application needs some time to "catch up" to be able to write to an UI component, by sleeping the thread for a second after each pass.
    However, Thread.sleep(1000) does not seem to do the trick in my swing app.
    Any ideas on how to do this?
    Thanks,
    -Rogier

    JTextArea.append() is a thread-safe method, so you can call it and java thread scheduling will do everything for you
    I'm not sure what you mean by "catch up", if your GUI stays responsive during your long job, than textArea will be updated.
    public void runVeryLongJob(){
          for(int i=0;i<numOfTasksInLongJob;i++){
               doStuff(i);
               //update JTextArea     
           yourTextArea.append("Task "+i+" done");
    }ok...camickr already answere this.. of course you have to be in separate thread for long job

Maybe you are looking for

  • Ever since updating my iOs to 7 I can no longer download apps from the store.

    It will ask for my password like normal but then it will tell me that 'such and such app cannot be purchased at this time.' I've tried signing in and out of my apple ID, restarting my phone, etc, etc but nothing seems to be working. Any leads on how

  • My ipod touch is fliiping out

    I dont even touch the screen and it will start to type all kinds of things and open apps on its own.

  • Sharing internet connection from MacBook Pro to iMac G3

    My goal here is to connect my iMac G3 (that I just got) to my cable internet connection. However, there are some hurdles in doing so. On the other side of my house lies my modem. It's connected to a D-Link wireless router to give my PC, Xbox 360, Wii

  • Iphoto (and Safari) crash when I try to access photos on desktop

    Apologies if this is the incorrect forum. Whenever I try to import from my desktop iphoto crashes without fail with the errors as below. Once the first photo is selected it'll take about 5 seconds for the crash. Safari does the same if I try to brows

  • Image in Web Dynpro ABAP

    Hi Experts,                   I 've converted the image as RAW STRING and stored in Database.i need to display from Database.is this possible to Display a image without using MIME object ?