About JtextField and JButton problem

hi, I dont know how to make this, hope to get help:)
I wanna like this:
A JtextField object -- for user to input some Integer
A JButton -- when users click the button, the content in JtextFiled will be delivered to a variable (say, int a, sent to this "a")in my program.
Here, We dont need to check the content if it is Integer or not for simple.
Any idea for me? thanks!

Write a listener class that implements listener interface. in that class implement the actionPerformed method of the super interface as u need.( I.e assign the value to the variable). Then bind this class with ur button using addActionListener() method( look in API).
ex:
bottonName.addActionListener( new ActionListener()
          public void actionPerformed(ActionEvent e)
               var = textarea.val;
     });

Similar Messages

  • JTextfield and JButton

    Hi all
    My problem is that i have a JTextfield that is connected to a Oracle database that allow the user to enter data in the database. I want to have a button that will allow the user to test to see whether the data entered in the textfield is valid.
    I'm not sure if i need to use sqlj or not. Any help would be gladly received.
    Thanks
    null

    Hmmm... lots and lots of ways to handle this, depending on your particular need for the particular type of 'validation'. ( More info? )
    "JTextField" is not connected to a database in the same way that the infoswing "TextFieldControl" is.. .therefore one could trap the event ActionPerformed off the JTextField and do the checks ( or use the jbutton like you suggest..but it would seem like you'd always want it checked and corrected before continuing towards the inevitable commit attempt??? ).
    You can use sqlj, or you can not use it... depends upon the way you've architected your application/environment and your needs and desires.
    Note (if you haven't already ) that you can also do a heck of a lot of validation at the entity/view object level.
    In my case ( an application ) I have a jdbc connection up at the front end for all my miscellaneous stuff, and a validate PL/SQL stored function. The nice things about using stored procedures/functions are that the validate routines can be nested for quick and easy use by triggers and stored procedures. If you put it outside the database it gets more fun should you want to get at the common validation routines from all approaches.
    Curious as to how other folk are architecting their validations....

  • JTextField and JButtons not appearing until clicked.

    I'm writing a program to refresh my CS1 java skills. For some reason when I try to add a JTextField and two JButtons to my container they don't appear until Ive clicked them.
    Actually more specifically, this only happens after a 100ms wait after setting the frame visible. Any less and the components wind up visible, but scrunched up in the top middle of my frame.
    Ive found that if I add the components before and after the wait they are visible and in the correct place, but this makes a noticeable flicker.
    I'm running windows vista if that matters.
    If someone could help me I would appreciate it.
    snippet of code:
    public scrollText()
         drawingThread.start();
         mainFrame.setSize(640,160);
         mainFrame.setContentPane(draw);
         mainPane = mainFrame.getContentPane();
         mainPane.setBackground(Color.white);
         mainFrame.setResizable(false);
         mainFrame.setVisible(true);
         try
              Thread.sleep(100);
              addInterface();
         catch(InterruptedException e){}
    public void addInterface()
         textInput.setBounds(1,103,501,31);
         play.setBounds(502,103,65,30);
         play.addActionListener(this);
         stop.setBounds(568,103,65,30);
         stop.addActionListener(this);
         mainPane.add(textInput);
         mainPane.add(play);
         mainPane.add(stop);
    }

    Postings can't be moved between forums. Now you know for the next time.
    The general form for building a GUI is
    frame.getContentPane().add( yourComponentsHere );
    frame.pack();
    frame.setVisible( true );Then all the compnoent will show up according to the rules of the layout managers used.
    However is you add components to the GUI "after" the GUI is visible then the components are not automatically painted. You need to tell the GUI to invoke the layout manager again so your code would be:
    frame.getContentPane().add( componentsToVisibleGUI );
    frame.getContentPane().validate();

  • How to for JTextField and JButton..

    How can i set the size of the JTextField and getting the words alignment to be in Center format?? Can i use JButton, click on it and key in value to be displayed in text form?

    Hi,
    you can change the alignment really simple:
    JTextField textField = new JTextField("Your Text");
    textField.setHorizontalAlignment(JTextField.LEFT);
    textField.setHorizontalAlignment(JTextField.CENTER);
    textField.setHorizontalAlignment(JTextField.RIGHT);The size can be set by
    setPrefferedSize(int w, int h)or try
    setColumns(int columns)L.P.

  • How to put JTextfield and JButton in a cell of JTable

    I'm trying to put two Components into one cell of a JTable. This is no
    problem (in the TableCellRenderer) unless it comes to editing in these
    cells. I have written my own CellEditor for the table.but there is one
    minor problem: Neither the JTextfield nor the JButton has the focus so I
    can't make any input! Does anybody know what's wrong, please help me for this issue ,plese urgent

    Here you go
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    public class TableEdit extends JFrame
         JTable table = new JTable();
         private String[] columnNames = {"non-edit1", "edit", "non-edit2"};
         public TableEdit()
              super("Table Edit");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              createGUI();
              setLocationRelativeTo(null);
              setSize(400, 300);
              setVisible(true);
         private void createGUI()
              table.setModel(new DefaultTableModel(3,3)
                   public int getColumnCount()
                        return 3;
                   public boolean isCellEditable(int row, int column)
                        if(column == 1)
                             return true;
                        return false;
                   public String getColumnName(int column)
                        return columnNames[column];
                   public int getRowCount()
                        return 3;
                   public Class getColumnClass(int column)
                        return String.class;
                   public Object getValueAt(int row, int column)
                        return row + "" + column;
              table.setRowHeight(20);
              table.setDefaultEditor(String.class, new MyTableEditor());
              JScrollPane sp = new JScrollPane(table);
              add(sp);
         public class MyTableEditor extends AbstractCellEditor
         implements TableCellEditor
              JPanel jp = new JPanel(new BorderLayout(5,5));
              JTextField tf = new JTextField();
              JButton btn = new JButton("...");
              public MyTableEditor()
                   jp.add(tf);
                   jp.add(btn, BorderLayout.EAST);
                   btn.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e)
                             JOptionPane.showMessageDialog(null, "Clicked Lookup");
              public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
                   tf.setText(String.valueOf(value));
                   return jp;
              public Object getCellEditorValue()
                   return tf.getText();
         public static void main(String[] parms)
              new TableEdit();
    }

  • JPasswordField and JButton Problem

    Happy New Year to all of you guys and gals. Here's the problem
    I have a String Array of buttons made already .. The design and measuring of the buttons are similar to a regular calculator.
    Now depending on the button that I press I set the text of the JPasswordField to "whatever", which is wrong because it's not being appended. So there has to be another way to do this.
    Take a calculator or bank for example. You press one button, it shows, and press the same button, so you have two digits appear on screen. That's exactly what I'm looking for. But I'm stuck...
    Here's the code to create the buttons
    for (int i = 0; i < 13; i++)
    button[i] = new JButton(Buttons);
    button[i].addActionListener(this);
    button[i].setFont(new Font("Comic Sans MS", Font.BOLD, 12));
    button[i].setSize(50, 30);
    button[i].setLocation(x, y);
    button[i].setBackground(Color.darkGray);
    button[i].setForeground(Color.white);
    button[i].setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.black, Color.lightGray));
    theKeysP.add(button[i]);
    x = x + 50;
    if((i + 1) % 4 == 0)
    x = 210;
    y = y + 30;
    if(i == 12)
    button[i].setLocation(410, 65);
    button[i].setBackground(Color.green);
    button[i].setForeground(Color.black);
    Lets say starting from button 0 to 5 are numbers starting from 1 - 6
    Since I'm clicking on the button it's an ActionEvent,
    so If(e.getSource() == button[0])
    PF.setText("1"); //Wrong because it's not being appended. Therefore it resets everytime button[0] is clicked.
    I hope this I made clear enough. Can anyone provide suggestions for this problem.

    Try doing it this way instead
    password.setText( password.getText() + "1" );Next time please use the code tags when posting
    ICE

  • Backup or Clone Stalls at about 200GB and other problems

    I cannot backup more than about 210GB out of 440GB on a 500GB boot drive. I have tried Disk Utility to create a clone of my boot drive and I have tried SuperDuper! to do the same thing. I have tried creating a clone on another internal drive and I have tried to create a clone to an external drive. No matter which drive or disk software I use, the backup proceeds quickly (25 to 50 MB/sec depending upon the drive) until it reaches a little more 200GB, then the backup stalls. In the case of Disk Utility, all of my Application and Library files are captured correctly, but my User files are not. SuperDuper! Starts at the bottom of the drive directory and captures most or all of my User files, but SuperDuper stalls when it reaches the Application and System files (including Library files). In both cases, as I mentioned above, 205GB to 212GB are transferred before the backup stalls.
    My hardware config is just below and other symptoms are shown below that.
    2006 MacPro
    Model Name: Mac Pro (September 2006)
    Model Identifier: MacPro1,1
    Processor Name: Dual-Core Intel Xeon
    Processor Speed: 2.66 GHz
    Number Of Processors: 2
    Total Number Of Cores: 4
    L2 Cache (per processor): 4 MB
    Memory: 10 GB
    Bus Speed: 1.33 GHz
    Boot ROM Version: MP11.005C.B08
    SMC Version (system): 1.7f10
    Two 1TB Drives configured as one 1TB RAID Set (software RAID)and used for Video and Photos
    Two 500GB drives. One is the boot drive and one was being used as a Time Machine backup drive until I started having problems.
    • Apple’s “Backup” Software does not complete a backup designed to copy Microsoft Office and Apple iWork files. The software scans more than six million files (there are only 900,000 files on my hard drive) and then fails.
    • The computer will not boot from the Mac Pro Install Disk. Every attempt leads to descending dark gray scree with the message, “You need to restart your computer.”
    • I cannot empty the Trash. I usually keep Trash empty, so there are never very many files in Trash. Recently I tried to empty the trash and the system started to count files to be removed an it quickly reached one million files after which I “Force Quit” Finder to stop it.
    • My computer was going to sleep frequently despite Preference Settings designed to prevent any sleep at all. I thought this was interrupting the backup processes, despite the fact that SuperDuper, at least, seems to stave off the computer’s attempt to sleep. I installed Caffeine and that stopped the unrequested sleep behavior, but did not solve the backup problem.
    • Recently my computer failed to find the boot drive. When this happens I can hold the “option” key during boot and select the boot drive myself.
    • I have reset the PRAM and VRAM.
    • The Install disk Extended Hardware test does not find a problem.
    • Disk utility does not find a problem with the boot drive although a small number of disk permissions always need to be fixed when I run Repair Disk Permissions. Most, but not all of the failed and then repaired permissions are related to Java. One is related to Parental Controls.
    • I reinstalled the OS by downloading and executing the Mac OS X 6.5 Combo update.
    • I have not installed any new hardware for about a year.
    • I am running Disk Warrior right now but it has not completed its check yet
    • I have started to use DropBox to protect my User files (mostly Office and pdf files)—get them off the computer, but I am worried about restoring my Applications if I “lose” the system.

    Thanks to all of you; I appreciate your expertise and the time you take to help me out. I have made progress. Let me start by saying that my system has 10GB of DRAM memory. One of you commented that I might have needed more disk swap space, but I don't think this is likely. I do think file corruption is a possibility. I am interested in all of your comments but first, will you please explain this in more detail?
    "Rebuilding the extensions drivers which are in a cache file, thru Safe Boot, may help - a good driver when installed should force the mkext to rebuild or be deleted, but not all do."
    Now, here is the update that I provided to SuperDuper!... In my update I commented that Trash had many more than a million files in it--I think six million. When I deleted the application mentioned below, there is no way that I had that many files, or that much content associated with the app--something pathological happened. My system stability has improved but I will watch for a few more days before I declare victory. In a few days I will do a file system rebuild on the boot drive using DiskWarrior, but I am interested in learning what all of you think might be a better maintenance procedure.
    ----------------------<snip>----------------------------------
    I fixed the problem and SuperDuper successfully ran a full backup.
    I bought and ran DiskWarrior which showed that one directory in my .Trash file had about ten sub-directories in it and each one had more than 100,000 files. I think the true number might have been six times that. The directory in Trash was attributed to an application that I deleted recently--SugarSync.
    I ran this UNIX command: rm -rf ~/.Trash. It took many hours to complete. When completed I was surprised to see that about 200GB had disappeared from my boot drive--all from Trash and nothing I care about. I ran DiskWarrior again and got a clean report. I repaired disk permissions, re-booted and ran SuperDuper immediately. It copied 249GB in 1:59:00 to an internal drive.
    Time Machine now also works.
    I think I have some more cleanup to do but I appreciate your help.

  • JMenuBar and JButton problem

    The problem is a simple one.
    Simply I don't know how to have the two together, every time I try to create a contentPane with the buttons in it I always get errors I would love it if some one could show me how to do this.
    Thanx

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.setLayout(new FlowLayout());
        JMenuBar jmb = new JMenuBar();
        setJMenuBar(jmb);
        JMenu jm = new JMenu("Menu");
        jmb.add(jm);
        for (int i=0; i<5; i++) {
          JMenuItem jmi = new JMenuItem("MenuItem-"+i);
          jm.add(jmi);
          jmi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
              System.out.println(((JMenuItem)ae.getSource()).getText());
          JButton jb = new JButton("Button-"+i);
          content.add(jb);
          jb.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
              System.out.println(((JButton)ae.getSource()).getText());
        setSize(200,400);
        show();
      public static void main(String[] args) { new Test(); }
    }

  • JTextField and Actionlistner problem

    Hi ALL
    I have a JTextfiled and i added and actionlistner that prints out a word if it is equal to what i tell the textfield to get, when enter is pressed. in my example below it only works if i only put the word "open" into the textfield. however if i write a sentence e.g. " you mus open the door" it does not work. it does not print open.
    Does anyone have an idea how i can find and print keywords in a sentence?, if so i will really appreciate it. even if it is possible with JTextArea
    Thank you
    public void actionPerformed(ActionEvent ae) {
    if (jtf.getText().equals("open"))
    System.out.println("open");
    }

    ahmed86 wrote:
    public void actionPerformed(ActionEvent ae) {
    if (jtf.getText().equals("open"))
    System.out.println("open");
    }in your example equals() look for exact match of the key word you supplied. and also its case sensitive.
    you better use
    if (jtf.getText().contains("open"))this will look for the key word existance in the entire string.
    alternatly you can go for regx (regular expressions) search.
    but i think in your casse the first one will work.

  • About socket and port problem

    hi,all.
    i write a chat server use java socket. now is more than 2000 users connect to my server. but too many user make the chat message speed slow. now my server is open one port to listen the client connection. who can tell me if i change my server to open multi port to listen the client connection will rather than open one port. or it is same effect.
    please give me some advice. thanks.

    Maybe your machine is not strong enough to serve that many users at a time anyway. In that case using several ports won't help.

  • Snow Leopard and DNS problems

    Hi
    I read a lot about SL and DNS problems while accessing websites. It seems that you have to put your DNS server in system settings/network so that you don't get the error message "can't connect to the internet' in your browser window. My problem is that I change locations with my mac quite frequently (home, uni etc) so whenever I am a a new location I have to go to the network settings and manually put in the DNS server. Why do I have to do that with SL when it worked completely fine before the upgrade to SL?
    Cheers
    Martin

    waschbaer22 wrote:
    That is exactly what is happening. The problem with my DHCP server at home is that it doesn't submit the DNS address to the computer somehow. That's why I have to put it in manually each time I reconnect the MB at home after I had it at uni. Once back at uni I then have to go into the settings and delete my manually added home DNS server. Right after that the uni DNS server address appears automatically. So I guess that is just how SL now works and I have to live with it, right? However, why do we need a DNS server anyway to connect to the internet. I thought a DNS server just facilitates the connection to websites but I didn't know that it is crucial.
    You should really try to figure out why your home router isn't providing you with a DNS server address and fix that. It could be a firmware issue, or it could be as simple as you have things set up so that one must manually be set up in the router, and one is not.
    You are also misinformed as to DNS' importance.
    DNS is the service that translates names - say "apple.com" - to the IP addresses - say "17.149.160.49" - that your machine needs to be able to connect to any site.
    Without being able to resolve names to addresses, you have to manually specify numeric IP addresses for everything - effectively meaning you will be unable to use the Internet.

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • It's so annoying!! I have created a new Apple ID but after I click verify it just goes back to the previous page!!! It''s really frustrating I have tried for more than 4H, and the problem is not about the apple ID. I can download apps with the apple ID, w

    It's so annoying!! I have created a new Apple ID but after I click verify it just goes back to the previous page!!! It''s really frustrating I have tried for more than 4H, and the problem is not about the apple ID. I can download apps with the apple ID, which means IMessage is the problem! I restarted my iPad, I logged in and out of the apple ID in the store, AND YET IT STILL WON'T WORK, PLEASE HELP!

    Hi Vmanfromusa!
    It sounds like you are having an issue with activating your iMessage app on your iPad. An article outlining some troubleshooting steps for this issue can be found here:
    iOS: Troubleshooting FaceTime and iMessage activation
    http://support.apple.com/kb/ts4268
    Thanks for using the Apple Support Communities. Have a good one!
    -Braden

  • Hello apple I have the problem with my iPhone and my friends have this problem too. My iPhone have the problem about calling and answer the call. When I use my iPhone to call I can't hear anything from my iPhone but the person that I call can answer it bu

    Hello apple
    I have the problem with my iPhone and my friends have this problem too.
    My iPhone have the problem about calling and answer the call. When I use my iPhone to call I can't hear anything from my iPhone but the person that I call can answer it but when answer both of us can't hear anything and when I put my iPhone to my face the screen is still on and when I quit the phone application and open it again it will automatic call my recent call. And when my friends call me my iPhone didn't show anything even the missed call I'm only know that I missed the call from messages from carrier. Please check these problem I restored my iPhone for 4 time now in this week. I lived in Hatyai, Songkhla,Thailand and many people in my city have this problem.
    Who have this problem??

    Apple isnt here. this is a user based forum for technical questions. The solution is to restart, reset, and restore as new which is in the manual after that get it replaced for hard ware failure. if your within your one year warranty its replaced if it is out of the warranty then it is 199$

  • I have read up on all about crashes and i cant even open it in safe mode :( i have tried deleting it and reinstalling it but the problem still persists. What would you suggest i do and is there any way i canget hold of firefox 6 for mac?

    i have read up on all about crashes and i cant even open it in safe mode :( i have tried deleting it and reinstalling it but the problem still persists. What would you suggest i do and is there any way i canget hold of firefox 6 for mac?

    Does the regular Firefox 8 release version work or does the version crash as well?
    *Firefox 8.0.x: http://www.mozilla.com/en-US/firefox/all.html
    Create a new profile as a test to check if your current profile is causing the problems.
    See "Basic Troubleshooting: Make a new profile":
    *https://support.mozilla.com/kb/Basic+Troubleshooting#w_8-make-a-new-profile
    There may be extensions and plugins installed by default in a new profile, so check that in "Tools > Add-ons > Extensions & Plugins" in case there are still problems.
    If that new profile works then you can transfer some files from the old profile to that new profile, but be careful not to copy corrupted files.
    See:
    *http://kb.mozillazine.org/Transferring_data_to_a_new_profile_-_Firefox

Maybe you are looking for