Pages

Tuesday, 31 May 2011

combining two strings using java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

//////////////////////////////////////////////////////////////// CombineName
public class CombineName extends JFrame {
    //=================================================== instance variables
    private JTextField _fNameTf        = new JTextField(8);
    private JTextField _lNameTf        = new JTextField(8);
    private JTextField _combinedNameTf = new JTextField(14);
    
    //================================================================= main
    public static void main(String[] args) {
        JFrame window = new CombineName();   // Create window.
    }
    
    //========================================================== constructor
    public CombineName() {
        //... 1. Create or set attributes of components.
        _combinedNameTf.setEditable(false);  // Don't let user change output.
        JButton combineBtn = new JButton("Combine");
        
        //... 2. Add listener(s).
        combineBtn.addActionListener(new CombineAction());
        
        //... 3. Create a panel, set layout, and add components to it.
        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.add(new JLabel("First"));
        content.add(_fNameTf);
        content.add(new JLabel("Last"));
        content.add(_lNameTf);
        content.add(combineBtn);
        content.add(new JLabel("Combined Name"));
        content.add(_combinedNameTf);
        
        //... 4. Set the content panel of window and perform layout.
        this.setContentPane(content);
        this.setTitle("CombineName Example");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();                       // Do layout.
        this.setLocationRelativeTo(null);  // Center window.
        this.setVisible(true);
    }
    
    ///////////////////////////////////// inner listener class CombineAction
    class CombineAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //... Get text from the text fields, combine, set text.
            //    Please make this program do something interesting.
            String first = _fNameTf.getText();
            String last  = _lNameTf.getText();
            String combined = last + ", " + first;  // Trivial logic!!!
            _combinedNameTf.setText(combined);
        }
    }
}

1 comment:

  1. Great site you have here but I was curious if you knew of any forums that
    cover the same topics talked about in this article?
    I'd really love to be a part of community where I can get suggestions from other experienced people that share the same interest. If you have any recommendations, please let me know. Thank you!

    my web page ... raspberry ketones reviews

    ReplyDelete