Regarding java swing JFrame

Sir!
Whenever I Create a JFrame or Frame, the components of the frame are not
visible until I maxmize the frame window.Once maximized, the components
remain visible even after restoring to the initial size of the frame set
by setSize() method.Why?

Did you call the validate method after adding all the components to your Frame?
abraham

Similar Messages

  • How to integrate Crystal Report viewer on java swing Jframe

    Dear, I want to display crystal reports in java Desktop applicaion. can any one help me how can i display crystal report developed report in java application. i searched best but not able to find right direction.
    Regards,
    Sahibzada
    Edited by: Sahibzada on Jan 27, 2010 4:32 AM

    You can use [i-net Crystal-Clear|http://www.inetsoftware.de/products/crystal-clear]. It is a Java Reporting Framework that can read and execute Crystal Reports files. It is very easy with i-net Crystal-Clear to show a report which is design with Crystal Reports in a Java Swing application.

  • Help regarding Java Swing

    Hi All,
    I am a bit confused witht the shortcut syntax for adding action listeners for event handling.
    In the Java tutorial it is mentioned that for implementing an event handler following are the three steps:
    1. Create a class that implements ActionListener interface.
    For example:
    public class MyClass implements ActionListener {
    2. Registers an instance of the event handler class as a listener on one or more components.
    For example:
    someComponent.addActionListener(instanceOfMyClass);
    3. In the event handler class, a few lines of code implement the methods in the listener interface.
    For example:
    public void actionPerformed(ActionEvent e) {
    ...//code that reacts to the action...
    In the tutorial a shortcut syntax is also given:
    For Example:
    Class TestApp {
    JButton btn = new JButton("Test");
    btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    ...//code that reacts to the action...
    My doubt is:
    1. How are we allowed to create an instance of ActionListener which is an "interface". (doesnt addActionListener expect instance of a class that implements the ActionListener interface? )
    2. How are we able to access local variables of class "TestApp" the inside the actionPerformed() function.
    Could anyone explain more about this shortcut syntax of adding action listeners?
    Thanks in regards
    Arun

    The example uses so-called "anonymous inner classes". ActionListener is an interface, of course. But if you use the construct
    new ActionListener() {
       public void actionPerformed(ActionEvent e) {
       ...//code that reacts to the action...
    }this is about equivalent to defining an inner class
    private class MyActionListener implements ActionListener {
       public void actionPerformed(ActionEvent e) {
       ...//code that reacts to the action...
    }and using that class. The difference is mainly, that the in nthe shortcut notation the class has no explicit name, it is anonymous.
    There are advantages and disadvantages to that. The main disadvantage is, that you create a large amount of classes in this way. I've read somewhere, that SUN is planning to rewrite the examples without the use of anonymous inner classes.

  • Objects in java Swing Jframe

    Can anybody tell me how do I get the list of objects in Jframe.
    Thnaks in adavance
    Dinesh

    use getComponent() methd....
    sami

  • Problem in compiling JAVA SWING

    Dear frens,
    I'm new in java swing. I have some knowledge in developing java in DOS, but dont have any knowledge in developing java in gui. I have write a program but it is unable to compile.
    I compile like this ----> javac HelloWorldSwing.java
    please help me to provide a guide.
    thank you
    regards
    Singaravelan

    import javax.swing.*;
    import java.lang.*;
    public class HelloWorldSwing {
         * Create the GUI and show it. For thread safety,
         * this method should be invoked from the
         * event-dispatching thread
         private static void createAndShowGUI() {
              //Make sure we have nice window decorations.
              JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new JFrame("HelloWorldSwing");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Add the ubiquitous "Hello World" label
              JLabel label = new JLabel("Hello World");
              frame.getContentPane().add(label);
         public static void main(String[] args) {
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
    This is my program, i can compile but cannot run the program

  • Creating file browser GUI using java swing tree

    Hi all,
    I have some questions which i wish to clarify asap. I am working on a file browser project using java swing. I need to create 2 separate buttons. 1 of them will add a 'folder' while the other button will add a 'file' to the tree when the buttons are clicked once. The sample source code known as 'DynamicTreeDemo' which is found in the java website only has 1 add button which is not what i want. Please help if you know how the program should be written. Thx a lot.
    Regards,

    Sorry, don't know 'DynamicTreeDemo'import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.io.File;
    public class Test extends JFrame {
      JTree jt = new JTree();
      DefaultTreeModel dtm = (DefaultTreeModel)jt.getModel();
      JButton newDir = new JButton("new Dir"), newFile = new JButton("new File");
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        newDir.setEnabled(false);
        newFile.setEnabled(false);
        jt.setShowsRootHandles(true);
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        File c = new File("C:\\temp");
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(c);
        dtm.setRoot(root);
        addChildren(root);
        jt.addTreeSelectionListener(new TreeSelectionListener() {
          public void valueChanged(TreeSelectionEvent tse) { select(tse) ; }
        JPanel jp = new JPanel();
        content.add(jp, BorderLayout.SOUTH);
        jp.add(newDir);
        jp.add(newFile);
        newDir.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            TreePath tp = jt.getSelectionPath();
            if (tp!=null) {
              DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
              File newFile = new File((File)dmtn.getUserObject(),"foo");
              if (newFile.mkdir()) {
                dmtn.add(new DefaultMutableTreeNode(newFile));
                dtm.nodeStructureChanged(dmtn);
              } else System.out.println("No Dir");
        newFile.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            TreePath tp = jt.getSelectionPath();
            if (tp!=null) {
              DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
              File newFile = new File((File)dmtn.getUserObject(),"foo.txt");
              try {
                if (newFile.createNewFile()) {
                  dmtn.add(new DefaultMutableTreeNode(newFile));
                  dtm.nodeStructureChanged(dmtn);
                } else System.out.println("No File");
              catch (java.io.IOException ioe) { ioe.printStackTrace(); }
        setSize(300, 300);
        setVisible(true);
      void select(TreeSelectionEvent tse) {
        TreePath tp = jt.getSelectionPath();
        newDir.setEnabled(false);
        newFile.setEnabled(false);
        if (tp!=null) {
          DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
          File f = (File)dmtn.getUserObject();
          if (f.isDirectory()) {
            newDir.setEnabled(true);
            newFile.setEnabled(true);
      void addChildren(DefaultMutableTreeNode parent) {
        File parentFile = (File)parent.getUserObject();
        File[] children = parentFile.listFiles();
        for (int i=0; i<children.length; i++) {
          DefaultMutableTreeNode child = new DefaultMutableTreeNode(children);
    parent.add(child);
    if (children[i].isDirectory()) addChildren(child);
    public static void main(String[] args) { new Test(); }

  • PL/SQL and Java Swing interface

    Everybody in this forum knows that Oracle is the best database around
    with many functionalities, stability, performance, etc. We also know
    that PL/SQL is a great language to manipulate information directly
    in the database with many built in functions, OOP capability,
    transaction control, among other features. Today an application that
    manipulates information, which needs user interface, requires components
    to be developed using different technologies and normally running in
    different servers or machines. For example, the interface is done using
    a dynamic HTML generator like JSP, PHP, PL/SQL Web Toolkit, etc.
    This page is executed in an application server like Oracle iAS or
    Tomcat, just to name two, which in turn access a database like Oracle to
    build the HTML. Also rich clients like Java applets require an intermediate
    server to access the database (through servlets for example) although
    it is possible to access the database directly but with security issues.
    Another problem with this is that complexity increases a lot, many
    technologies, skills and places to maintain code which leads to a greater
    failure probability. Also, an application is constantly evolving, new
    calculations are added, new tables, changed columns. If you have an
    application with product code for example and you need to increase its
    size, you need to change it in the database, search for all occurrences
    of it in the middle-tier code and perhaps adjust interfaces. Normally
    there is no direct dependency among the tier components. On another
    issue, many application interfaces today are based on HTML which doesn't
    have interactive capabilities like rich-client interfaces. Although it
    is possible to simulate many GUI widgets with JavaScript and DHTML, it is
    far from the interactive level we can accomplish in rich clients like
    Java Swing, Flash MX, Win32, etc. HTML is also a "tag-based" language
    originally created to publish documents so even small pages require
    many bytes to be transmitted, far beyond of what we see on the screen.
    Even in fast networks you have a delay time to wait the page to be
    loaded. Another issue, the database is in general the central location
    for all kinds of data. Most applications relies on it for security,
    transaction and availability. My proposal is to use Oracle as the
    central location for interface, processing and data. With this approach
    we can create not only the data manipulation procedures in the database,
    but procedures that also control and manage user interfaces. Having
    a Oracle database as the central location for all components has many
    advantages:
    - Unique point of maintenance, backup and restore
    - Integrated database security
    - One language for everything, PL/SQL or Java (even both if desired)
    - Inherited database cache, transaction and processing optimizations
    - Direct access to the database dictionary
    - Application runs on Oracle which has support for many platforms.
    - Transparent use of parallel processing, clusters and future
    background technologies
    Regarding the interface, I already created a Java applet renderer
    which receives instructions from the database on how to create GUI
    objects and how to respond to events. The applet is only 8kb and can
    render any Swing or AWT object/event. The communication is done
    through HTTP or HTTPS using Oracles's MOD_PLSQL included in the Apache
    HTTP server which comes with the database or application server (iAS).
    I am also creating a database framework and APIs in PL/SQL to
    create and manipulate the client interface. The applet startup is
    very fast because it is very small, you don't need to download large
    classes with the client interface. Execution is done "on-demand"
    according to instructions received from the database. The instructions
    are very optimized in terms of network bandwidth and based on preliminary
    tests it can be up to 1/10 of a similar HTML screen. Less network usage
    means faster response and means that even low speed connections will
    have a good performance (a future development can be to use this in
    wireless devices like PDAs e even cell phones, just an idea for now).
    The applet can also be executed standalone by using Java Web Start.
    With this approach no business code, except the interface, is executed
    on the client. This means that alterations in the application are
    dynamically reflected in the client, no need to "re-download" the
    application. Events are transmitted when required only so network
    usage is minimized. It is also possible to establish triggering
    events to further reduce network usage. Since the protocol used is
    HTTP (which is stateless), the database framework I am creating will
    be responsible to maintain the state of connections, variables, locks
    and session information, so the developer don't need to worry about it.
    The framework will have many layers, from communication up to
    application so there will be pre-built functions to handle queries,
    pagination, lock, mail, log, etc. The final objective is to have a
    rich client application integrated into the database with minimum
    programming and maintenance requirements, not forgetting customization
    capabilities. Below is a very small example of what can de done. A
    desktop with two windows, each window with two fields, a button with an
    image to switch the values, and events to convert the typed text when
    leaving the field or double-clicking it. The "leave" event also has an
    optimization to only be triggered when the text changes. I am still
    developing the framework and adjusting the renderer but I think that all
    technical barriers were transposed by now. The framework is still in
    the early stages, my guess is that only 5% is done so far. As a future
    development even an IDE can be created so we have a graphical environment
    do develop applications. I am willing to share this with the PL/SQL
    community and listen to ideas and comments.
    Example:
    create or replace procedure demo1 (
    jre_version in varchar2 := '1.4.2_01',
    debug_info in varchar2 := 'false',
    compress_buffer in varchar2 := 'false',
    optimize_buffer in varchar2 := 'true'
    ) as
    begin
    interface.initialize('demo1_init','JGR Demo 1',jre_version,debug_info,compress_buffer,optimize_buffer);
    end;
    create or replace procedure demo1_init as
    begin
    toolkit.initialize;
    toolkit.create_icon('icon',interface.global_root_url||'img/switch.gif');
    toolkit.create_internal_frame('frame1','Frame 1',50,50,300,136);
    toolkit.create_label('frame1label1','frame1',10,10,50,20,'Field 1');
    toolkit.create_label('frame1label2','frame1',10,40,50,20,'Field 2');
    toolkit.create_text_field('frame1field1','frame1',50,10,230,20,'Field 1','Field 1',focus_event=>true,mouse_event=>true);
    toolkit.create_text_field('frame1field2','frame1',50,40,230,20,'Field 2','Field 2',focus_event=>true,mouse_event=>true);
    toolkit.set_text_field_event('frame1field1',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 1','false');
    toolkit.set_text_field_event('frame1field2',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 2','false');
    toolkit.set_text_field_event('frame1field1',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 1','false');
    toolkit.set_text_field_event('frame1field2',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 2','false');
    toolkit.create_button('button1','frame1',10,70,100,25,'Switch','Switch the values of "Field 1" and "Field 2"','S','icon');
    toolkit.set_button_event('button1',toolkit.action_performed_event,'demo1_switch_fields(''frame1field1'',''frame1field2'')','frame1field1:'||toolkit.get_text_method||',frame1field2:'||toolkit.get_text_method);
    toolkit.create_internal_frame('frame2','Frame 2',100,100,300,136);
    toolkit.create_label('frame2label1','frame2',10,10,50,20,'Field 1');
    toolkit.create_label('frame2label2','frame2',10,40,50,20,'Field 2');
    toolkit.create_text_field('frame2field1','frame2',50,10,230,20,'Field 1','Field 1',focus_event=>true,mouse_event=>true);
    toolkit.create_text_field('frame2field2','frame2',50,40,230,20,'Field 2','Field 2',focus_event=>true,mouse_event=>true);
    toolkit.set_text_field_event('frame2field1',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 1','false');
    toolkit.set_text_field_event('frame2field2',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 2','false');
    toolkit.set_text_field_event('frame2field1',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 1','false');
    toolkit.set_text_field_event('frame2field2',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 2','false');
    toolkit.create_button('button2','frame2',10,70,100,25,'Switch','Switch the values of "Field 1" and "Field 2"','S','icon');
    toolkit.set_button_event('button2',toolkit.action_performed_event,'demo1_switch_fields(''frame2field1'',''frame2field2'')','frame2field1:'||toolkit.get_text_method||',frame2field2:'||toolkit.get_text_method);
    end;
    create or replace procedure demo1_set_upper as
    begin
    toolkit.set_string_method(interface.global_object_name,toolkit.set_text_method,upper(interface.array_event_value(1)));
    toolkit.set_text_field_event(interface.global_object_name,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(1)),'false');
    end;
    create or replace procedure demo1_set_lower as
    begin
    toolkit.set_string_method(interface.global_object_name,toolkit.set_text_method,lower(interface.array_event_value(1)));
    toolkit.set_text_field_event(interface.global_object_name,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(1)),'false');
    end;
    create or replace procedure demo1_switch_fields (
    field1 in varchar2,
    field2 in varchar2
    ) as
    begin
    toolkit.set_string_method(field1,toolkit.set_text_method,interface.array_event_value(2));
    toolkit.set_string_method(field2,toolkit.set_text_method,interface.array_event_value(1));
    toolkit.set_text_field_event(field1,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(2)),'false');
    toolkit.set_text_field_event(field2,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(1)),'false');
    toolkit.set_text_field_event(field1,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(2)),'false');
    toolkit.set_text_field_event(field2,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(1)),'false');
    end;

    Is it sound like Oracle Portal?
    But you want to save a layer 9iAS.
    Basically, that was the WebDB.(Oracle changed the name to Portal when version 3.0)
    Over all, I agree with you.
    &gt;&gt;Having a Oracle database as the central location for all components has many
    &gt;&gt;advantages:
    &gt;&gt;
    &gt;&gt;- Unique point of maintenance, backup and restore
    &gt;&gt;- Integrated database security
    &gt;&gt;- One language for everything, PL/SQL or Java (even both if desired)
    &gt;&gt;- Inherited database cache, transaction and processing optimizations
    &gt;&gt;- Direct access to the database dictionary
    &gt;&gt;- Application runs on Oracle which has support for many platforms.
    &gt;&gt;- Transparent use of parallel processing, clusters and future
    &gt;&gt;background technologies
    I would like to build 'ZOPE' inside Oracle DB as a back-end
    Using Flash MX as front-end.
    Thomas Ku.

  • Java Swing application problem in Windows vista

    When we execute the Swing application in windows vista environment.
    The look and feel of the swing components are displayed improperly.
    Do we need to put any specific look and feel for windows vista environment or any specific hardware configuration is required to setup windows vista environment.
    Please give some inputs to solve the problem.
    We have tried with the following sample code to run in windows vista.
    * Vista.java
    * Created on December 5, 2006, 5:39 PM
    public class Vista extends javax.swing.JFrame {
    /** Creates new form Vista */
    public Vista() {
    initComponents();
    pack();
    /** 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 ">//GEN-BEGIN:initComponents
    private void initComponents() {
    jButton1 = new javax.swing.JButton();
    jToggleButton1 = new javax.swing.JToggleButton();
    jPanel1 = new javax.swing.JPanel();
    jCheckBox1 = new javax.swing.JCheckBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jTextField1 = new javax.swing.JTextField();
    getContentPane().setLayout(null);
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jButton1.setText("Button 1");
    getContentPane().add(jButton1);
    jButton1.setBounds(20, 20, 170, 30);
    jToggleButton1.setText("Togle btn");
    getContentPane().add(jToggleButton1);
    jToggleButton1.setBounds(100, 80, 90, 20);
    jPanel1.setLayout(null);
    jCheckBox1.setText("jCheckBox1");
    jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0));
    jPanel1.add(jCheckBox1);
    jCheckBox1.setBounds(10, 40, 130, 13);
    getContentPane().add(jPanel1);
    jPanel1.setBounds(10, 150, 200, 130);
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(210, 150, 164, 94);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1);
    jTextField1.setBounds(240, 30, 140, 30);
    pack();
    }// </editor-fold>//GEN-END:initComponents
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Vista().setVisible(true);
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables
    }

    When we execute the Swing application in windows
    vista environment.
    The look and feel of the swing components are
    displayed improperly.Improperly means what? You must be aware that Vista's native L&F certainly isn't supported yet.

  • Problem with java swing button and loop

    Problem with java swing button and loop
    I�m using VAJ 4.0. and I�m doing normal GUI application. I have next problem.
    I have in the same class two jswing buttons named start (ivjGStart) and stop (ivjGStop) and private static int field named Status where initial value is 0. This buttons should work something like this:
    When I click on start button it must do next:
    Start button must set disenabled and Stop button must set enabled and selected. Field status is set to 1, because this is a condition in next procedure in some loop. And then procedure named IzvajajNeprekinjeno() is invoked.
    And when I click on stop button it must do next:
    Start button must set enabled and selected and Stop button must set disenabled.
    Field status is set to 0.
    This works everything fine without loop �do .. while� inside the procedure IzvajajNeprekinjeno(). But when used this loop the start button all the time stay (like) pressed. And this means that a can�t stop my loop.
    There is java code, so you can get better picture:
    /** start button */
    public void gStart_ActionEvents() {
    try {
    ivjGStart.setEnabled(false);
    ivjGStop.setEnabled(true);
    ivjGStop.setSelected(true);
    getJTextPane1().setText("Program is running ...");
    Status = 1;
    } catch (Exception e) {}
    /** stop button */
    public void gStop_ActionEvents() {
    try {
    ivjGStart.setEnabled(true);
    ivjGStart.setSelected(true);
    ivjGStop.setEnabled(false);
    getJTextPane1().setText("Program is NOT running ...");
    Status = 0;
    } catch (Exception e) {
    /** procedure IzvajajNeprekinjeno() */
    public void IzvajajNeprekinjeno() {  //RunLoop
    try {
    int zamik = 2000; //delay
    do {
    Thread.sleep(zamik);
    PreberiDat(); //procedure
    } while (Status == 1);
    } catch (Exception e) {
    So, I'm asking what I have to do, that start button will not all the time stay pressed? Or some other aspect of solving this problem.
    Any help will be appreciated.
    Best regards,
    Tomi

    This is a multi thread problem. When you start the gui, it is running in one thread. Lets call that GUI_Thread so we know what we are talking about.
    Since java is task-based this will happen if you do like this:
    1. Button "Start" is pressed. Thread running: GUI_Thread
    2. Event gStart_ActionEvents() called. Thread running: GUI_Thread
    3. Method IzvajajNeprekinjeno() called. Thread running: GUI_Thread
    4. Sleep in method IzvajajNeprekinjeno() on thread GUI_Thread
    5. Call PreberiDat(). Thread running: GUI_Thread
    6. Check status. If == 1, go tho 4. Thread running: GUI_Thread.
    Since the method IzvajajNeprekinjeno() (what does that mean?) and the GUI is running in the same thread and the event that the Start button has thrown isn't done yet, the program will go on in the IzvajajNeprekinjeno() method forever and never let you press the Stop-button.
    What you have to do is do put either the GUI in a thread of its own or start a new thread that will do the task of the IzvajajNeprekinjeno() method.
    http://java.sun.com/docs/books/tutorial/uiswing/index.html
    This tutorial explains how to build a multi threaded gui.
    /Lime

  • How to create the digital clock in java swing application ?

    I want to create the running digital clock in my java swing application. Can someone throw some light on this how to do this ? Or If someone has done it then can someone pl. paste the code ?
    Thanks.

    hi prah_Rich,
    I have created a digital clock you can use. You will most likely have to change some things to use it in another app although that shouldn't be too hard. A least it can give you some ideas on how to create one of your own. There are three classes.One that creates the numbers. a gui class and frame class.
    cheers:)
    Hex45
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.geom.*;
    public class DigitalClock extends Panel{
              BasicStroke stroke = new BasicStroke(4,BasicStroke.CAP_ROUND,
                                               BasicStroke.JOIN_BEVEL);
              String hour1, hour2;
              String minute1, minute2;
              String second1, second2;
              String mill1, mill2, mill3;
              int hr1, hr2;
              int min1, min2;
              int sec1, sec2;
              int mll1, mll2,mll3;       
        public void update(Graphics g){
             paint(g);
         public void paint(Graphics g){
              Graphics2D g2D = (Graphics2D)g;
              DigitalNumber num = new DigitalNumber(10,10,20,Color.cyan,Color.black);     
              GregorianCalendar c = new GregorianCalendar();
              String hour = String.valueOf(c.get(Calendar.HOUR));
              String minute = String.valueOf(c.get(Calendar.MINUTE));
              String second = String.valueOf(c.get(Calendar.SECOND));
              String milliSecond = String.valueOf(c.get(Calendar.MILLISECOND));
              if(hour.length()==2){
                   hour1 = hour.substring(0,1);
                   hour2 = hour.substring(1,2);
              }else{
                   hour1 = "0";
                   hour2 = hour.substring(0,1);
              if(minute.length()==2){
                   minute1 = minute.substring(0,1);
                   minute2 = minute.substring(1,2);
              }else{
                   minute1 = "0";
                   minute2 = minute.substring(0,1);
              if(second.length()==2){
                   second1 = second.substring(0,1);
                   second2 = second.substring(1,2);
              }else{
                   second1 = "0";
                   second2 = second.substring(0,1);
              if(milliSecond.length()==3){
                   mill1 = milliSecond.substring(0,1);
                   mill2 = milliSecond.substring(1,2);
                   mill3 = milliSecond.substring(2,3);
              }else if(milliSecond.length()==2){
                   mill1 = "0";
                   mill2 = milliSecond.substring(0,1);
                   mill3 = milliSecond.substring(1,2);
              }else{
                   mill1 = "0";
                   mill2 = "0";
                   mill3 = milliSecond.substring(0,1);
              hr1  = Integer.parseInt(hour1);     
              hr2  = Integer.parseInt(hour2);
              min1 = Integer.parseInt(minute1);
              min2 = Integer.parseInt(minute2);
              sec1 = Integer.parseInt(second1);
              sec2 = Integer.parseInt(second2);
              mll1 = Integer.parseInt(mill1);
              mll2 = Integer.parseInt(mill2);
              g2D.setStroke(stroke);
              g2D.setPaint(Color.cyan);
              num.setSpacing(true,8);
              num.setSpacing(true,8);
              if(hr1==0&hr2==0){
                   num.drawNumber(1,g2D);
                   num.setLocation(40,10);
                   num.drawNumber(2,g2D);
              else{
                   if(!(hr1 == 0)){     
                        num.drawNumber(hr1,g2D);
                   num.setLocation(40,10);
                   num.drawNumber(hr2,g2D);
              num.setLocation(70,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(100,10);
              num.drawNumber(min1,g2D);
              num.setLocation(130,10);
              num.drawNumber(min2,g2D);
              num.setLocation(160,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(190,10);
              num.drawNumber(sec1,g2D);
              num.setLocation(220,10);
              num.drawNumber(sec2,g2D);
              /*num.setLocation(250,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(280,10);
              num.drawNumber(mll1,g2D);
              num.setLocation(310,10);
              num.drawNumber(mll2,g2D);
              g2D.setPaint(Color.cyan);
              if((c.get(Calendar.AM_PM))==Calendar.AM){               
                   g2D.drawString("AM",260,20);
              }else{
                   g2D.drawString("PM",260,20);
         String dayOfweek = "";     
         switch(c.get(Calendar.DAY_OF_WEEK)){
              case(Calendar.SUNDAY):
                   dayOfweek = "Sunday, ";
                   break;
              case(Calendar.MONDAY):
                   dayOfweek = "Monday, ";
                   break;
              case(Calendar.TUESDAY):
                   dayOfweek = "Tuesday, ";
                   break;
              case(Calendar.WEDNESDAY):
                   dayOfweek = "Wednesday, ";
                   break;
              case(Calendar.THURSDAY):
                   dayOfweek = "Thursday, ";
                   break;
              case(Calendar.FRIDAY):
                   dayOfweek = "Friday, ";
                   break;
              case(Calendar.SATURDAY):
                   dayOfweek = "Saturday, ";
                   break;
         String month = "";     
         switch(c.get(Calendar.MONTH)){
              case(Calendar.JANUARY):
                   month = "January ";
                   break;
              case(Calendar.FEBRUARY):
                   month = "February ";
                   break;
              case(Calendar.MARCH):
                   month = "March ";
                   break;
              case(Calendar.APRIL):
                   month = "April ";
                   break;
              case(Calendar.MAY):
                   month = "May ";
                   break;
              case(Calendar.JUNE):
                   month = "June ";
                   break;
              case(Calendar.JULY):
                   month = "July ";
                   break;
              case(Calendar.AUGUST):
                   month = "August ";
                   break;
              case(Calendar.SEPTEMBER):
                   month = "September ";
                   break;
              case(Calendar.OCTOBER):
                   month = "October ";
                   break;
              case(Calendar.NOVEMBER):
                   month = "November ";
                   break;
              case(Calendar.DECEMBER):
                   month = "December ";
                   break;
         int day = c.get(Calendar.DAY_OF_MONTH);
         int year = c.get(Calendar.YEAR);
         Font font = new Font("serif",Font.PLAIN,24);
         g2D.setFont(font);
         g2D.drawString(dayOfweek+month+day+", "+year,10,80);
         public static void main(String args[]){
              AppFrame aframe = new AppFrame("Digital Clock");
              Container cpane = aframe.getContentPane();
              final DigitalClock dc = new DigitalClock();
              dc.setBackground(Color.black);
              cpane.add(dc,BorderLayout.CENTER);
              aframe.setSize(310,120);
              aframe.setVisible(true);
              class Task extends TimerTask {
                 public void run() {
                      dc.repaint();
              java.util.Timer timer = new java.util.Timer();
             timer.schedule(new Task(),0L,250L);
    class DigitalNumber {
         private float x=0;
         private float y=0;
         private float size=5;
         private int number;
         private Shape s;
         private float space = 0;
         public static final int DOTS = 10;
         private Color on,off;
         DigitalNumber(){          
              this(0f,0f,5f,Color.cyan,Color.black);          
         DigitalNumber(float x,float y, float size,Color on,Color off){
              this.x = x;
              this.y = y;
              this.size = size;
              this.on = on;
              this.off = off;
         public void drawNumber(int number,Graphics2D g){
              int flag = 0;
              switch(number){
                   case(0):          
                        flag = 125;
                        break;
                   case(1):
                        flag = 96;
                        break;
                   case(2):
                        flag = 55;
                        break;
                   case(3):
                        flag = 103;
                        break;
                   case(4):
                        flag = 106;
                        break;
                   case(5):
                        flag = 79;
                        break;
                   case(6):
                        flag = 94;
                        break;
                   case(7):
                        flag = 97;
                        break;
                   case(8):
                        flag = 127;
                        break;
                   case(9):
                        flag = 107;
                        break;
                   case(DOTS):
                        GeneralPath path = new GeneralPath();
                        path.moveTo(x+(size/2),y+(size/2)-1);
                        path.lineTo(x+(size/2),y+(size/2)+1);
                        path.moveTo(x+(size/2),y+(size/2)+size-1);
                        path.lineTo(x+(size/2),y+(size/2)+size+1);
                        g.setPaint(on);
                        g.draw(path);     
                        return;
              //Top          
              if((flag & 1) == 1){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Top = new GeneralPath();
              Top.moveTo(x + space, y);
              Top.lineTo(x + size - space, y);
              g.draw(Top);
              //Middle
              if((flag & 2) == 2){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Middle = new GeneralPath();
              Middle.moveTo(x + space, y + size); 
              Middle.lineTo(x + size - space,y + size);     
              g.draw(Middle);
              //Bottom
              if((flag & 4) == 4){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Bottom = new GeneralPath();
              Bottom.moveTo(x + space, y + (size * 2));  
              Bottom.lineTo(x + size - space, y + (size * 2));
              g.draw(Bottom);
              //TopLeft
              if((flag & 8) == 8){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath TopLeft = new GeneralPath();     
              TopLeft.moveTo(x, y + space);
              TopLeft.lineTo(x, y + size - space);          
              g.draw(TopLeft);
              //BottomLeft
              if((flag & 16) == 16){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath BottomLeft = new GeneralPath();     
              BottomLeft.moveTo(x, y + size + space);
              BottomLeft.lineTo(x, y + (size * 2) - space);
              g.draw(BottomLeft);
              //TopRight
              if((flag & 32) == 32){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath TopRight = new GeneralPath();     
              TopRight.moveTo(x + size, y + space);
              TopRight.lineTo(x + size, y + size - space);
              g.draw(TopRight);
              //BottomRight
              if((flag & 64) == 64){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath BottomRight = new GeneralPath();     
              BottomRight.moveTo(x + size, y + size + space);
              BottomRight.lineTo(x + size, y + (size * 2) - space);
              g.draw(BottomRight);
         public void setSpacing(boolean spacingOn){
              if(spacingOn == false){
                   space = 0;
              else{
                   this.setSpacing(spacingOn,5f);
         public void setSpacing(boolean spacingOn,float gap){
              if(gap<2){
                   gap = 2;
              if(spacingOn == true){
                   space = size/gap;
         public void setLocation(float x,float y){
              this.x = x;
              this.y = y;
         public void setSize(float size){
              this.size = size;
    class AppFrame extends JFrame{
         AppFrame(){
              this("Demo Frame");
         AppFrame(String title){
              super(title);
              setSize(500,500);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • Swings-JFrame

    IN my program ,JFrame,JButton1 named VIEW ALL ,JComboBox ,JButton2 by clicking this calender will be displayed select the date ,that selected date will come into JComboBox,JButton3 named BY DATE.
    when click on VIEW ALL button data from the database(oracle 10g) will be retrieved into JTable, that table will be displayed in same JFrame.
    If we click on BY DATE button data will be displayed by that date only in the same JFrame.
    view is like this:
    VIEW ALL JCOmboBox JButton2 BY DATE
    display of JTable resultsin the same frame
    i have written the code for JTable like this;
    package crm;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    import java.lang.*;
    * @author rajeshwari
    public class Callbacks extends javax.swing.JFrame {
    JTable table;
         JTableHeader header;
         Vector data = new Vector();
         String colnames[];
    public Callbacks() {
    getConnection();
    /** 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();
    // jPanel2 = new javax.swing.JPanel();
    // jButton1 = new javax.swing.JButton();
    // jButton2 = new javax.swing.JButton();
    // jButton3 = new javax.swing.JButton();
    // jButton4 = new javax.swing.JButton();
    // jButton5 = new javax.swing.JButton();
    // jButton6 = new javax.swing.JButton();
    // jButton7 = new javax.swing.JButton();
    // jLabel1 = new javax.swing.JLabel();
    // jTextField1 = new javax.swing.JTextField();
    // jLabel2 = new javax.swing.JLabel();
    // jTextField2 = new javax.swing.JTextField();
    // jLabel3 = new javax.swing.JLabel();
    // jScrollPane1 = new javax.swing.JScrollPane();
    // jTextArea1 = new javax.swing.JTextArea();
    // jLabel4 = new javax.swing.JLabel();
    // jTextField3 = new javax.swing.JTextField();
    // jLabel5 = new javax.swing.JLabel();
    // jTextField4 = new javax.swing.JTextField();
    // jLabel6 = new javax.swing.JLabel();
    // jTextField5 = new javax.swing.JTextField();
    // jLabel7 = new javax.swing.JLabel();
    // jTextField6 = new javax.swing.JTextField();
    // jLabel8 = new javax.swing.JLabel();
    // jTextField7 = new javax.swing.JTextField();
    // jLabel9 = new javax.swing.JLabel();
    // jTextField8 = new javax.swing.JTextField();
    // jLabel10 = new javax.swing.JLabel();
    // jTextField9 = new javax.swing.JTextField();
    // jLabel11 = new javax.swing.JLabel();
    // jTextField10 = new javax.swing.JTextField();
    // jButton8 = new javax.swing.JButton();
    // jButton9 = new javax.swing.JButton();
    // jPanel3 = new javax.swing.JPanel();
    // jLabel12 = new javax.swing.JLabel();
    // jTextField11 = new javax.swing.JTextField();
    // jLabel13 = new javax.swing.JLabel();
    // jTextField12 = new javax.swing.JTextField();
    // jLabel14 = new javax.swing.JLabel();
    // jTextField13 = new javax.swing.JTextField();
    // jLabel15 = new javax.swing.JLabel();
    // jTextField14 = new javax.swing.JTextField();
    // jScrollPane2 = new javax.swing.JScrollPane();
    // jTextPane1 = new javax.swing.JTextPane();
    // jButton10 = new javax.swing.JButton();
    // jScrollPane3 = new javax.swing.JScrollPane();
    // jTextPane2 = new javax.swing.JTextPane();
    // jMenuBar1 = new javax.swing.JMenuBar();
    // jMenu1 = new javax.swing.JMenu();
    // jMenu2 = new javax.swing.JMenu();
    // jMenu3 = new javax.swing.JMenu();
    // jMenu4 = new javax.swing.JMenu();
    // jMenu5 = new javax.swing.JMenu();
    // jMenu6 = new javax.swing.JMenu();
    // jMenu7 = new javax.swing.JMenu();
    // jMenu8 = new javax.swing.JMenu();
    // setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    // jButton1.setText("Call Back");
    // jButton2.setText("Not Interested");
    // jButton3.setText("Person Not Available\n");
    // jButton4.setText("Answering Machine");
    // jButton5.setText("Person Available");
    // jButton6.setText("Do not Call");
    // jButton7.setText("Next>>...");
    // org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
    // jPanel2.setLayout(jPanel2Layout);
    // jPanel2Layout.setHorizontalGroup(
    // jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel2Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)))
    // jPanel2Layout.setVerticalGroup(
    // jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel2Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jButton1)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton2)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton3)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton4)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton5)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton6)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton7)
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // jLabel1.setText("\nCustomer ID:");
    // jTextField1.setText("852");
    // jLabel2.setText("Customer Name:");
    // jTextField2.setText("Rajeshwari");
    // jLabel3.setText("Address:");
    // jTextArea1.setColumns(20);
    // jTextArea1.setRows(5);
    // jScrollPane1.setViewportView(jTextArea1);
    // jLabel4.setText("City:");
    // jTextField3.setText("HYD");
    // jLabel5.setText("State:");
    // jTextField4.setText("A.P");
    // jLabel6.setText("Zip:");
    // jTextField5.setText("39");
    // jLabel7.setText("Phone:");
    // jTextField6.setText("220288");
    // jLabel8.setText("Mobile:");
    // jTextField7.setText("9949162978");
    // jLabel9.setText("Fax:");
    // jTextField8.setText("2343535");
    // jLabel10.setText("Email:");
    // jTextField9.setText("[email protected]");
    // jLabel11.setText("Call Time:");
    // jTextField10.setText("12:34:23");
    // jButton8.setText("Call Backs");
    // jButton8.addActionListener(new java.awt.event.ActionListener() {
    // public void actionPerformed(java.awt.event.ActionEvent evt) {
    // jButton8ActionPerformed(evt);
    // jButton9.setText("Hang");
    // jLabel12.setText("Call Back Date:");
    // jTextField11.setText("12-03-98");
    // jLabel13.setText("Call Back Time:");
    // jTextField12.setText("12:23:45");
    // jLabel14.setText("Called on:");
    // jTextField13.setText("11:12:99");
    // jLabel15.setText("Called At:");
    // jTextField14.setText("jTextField14");
    // jScrollPane2.setViewportView(jTextPane1);
    // jButton10.setText("ADD");
    // org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
    // jPanel3.setLayout(jPanel3Layout);
    // jPanel3Layout.setHorizontalGroup(
    // jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel12)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField11, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel13)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
    // .add(27, 27, 27)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel14)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel15)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField14))))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 187, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(28, 28, 28)
    // .add(jButton10)))
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // jPanel3Layout.setVerticalGroup(
    // jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel12)
    // .add(jTextField11, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel14)
    // .add(jTextField13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(17, 17, 17)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel13)
    // .add(jTextField12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel15)
    // .add(jTextField14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
    // .add(jButton10)
    // .add(22, 22, 22))))
    // jScrollPane3.setViewportView(jTextPane2);
    // org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    // jPanel1.setLayout(jPanel1Layout);
    // jPanel1Layout.setHorizontalGroup(
    // jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(30, 30, 30)
    // .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(32, 32, 32)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jLabel2)
    // .add(jLabel1)
    // .add(jLabel3)
    // .add(jLabel4)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 46, Short.MAX_VALUE)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
    // .add(jTextField2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
    // .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 149, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(58, 58, 58))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
    // .add(jTextField4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE))
    // .add(66, 66, 66))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jTextField5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
    // .add(66, 66, 66))))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(254, 254, 254)))
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jButton8)
    // .add(27, 27, 27)
    // .add(jButton9))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    // .add(jLabel7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(jLabel8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel9))
    // .add(jLabel10)
    // .add(jLabel11))
    // .add(6, 6, 6)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
    // .add(jTextField10)
    // .add(jTextField9)
    // .add(jTextField8)
    // .add(jTextField7)
    // .add(jTextField6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)))
    // .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 212, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(45, 45, 45))
    // jPanel1Layout.setVerticalGroup(
    // jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(23, 23, 23)
    // .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(42, 42, 42)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel1)
    // .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel7)
    // .add(jTextField6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(16, 16, 16)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel2)
    // .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(25, 25, 25)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel3))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 17, Short.MAX_VALUE)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel4)
    // .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(18, 18, 18)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel5)
    // .add(jTextField4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jTextField5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jButton8)
    // .add(jButton9)
    // .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel8)
    // .add(jTextField7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel9)
    // .add(jTextField8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel10)
    // .add(jTextField9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(34, 34, 34)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel11)
    // .add(jTextField10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))))
    // .add(63, 63, 63)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
    // .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 88, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(44, 44, 44))))
    // jMenu1.setText("start");
    // jMenuBar1.add(jMenu1);
    // jMenu2.setText("Leads");
    // jMenuBar1.add(jMenu2);
    // jMenu3.setText("Campaign");
    // jMenuBar1.add(jMenu3);
    // jMenu4.setText("Reports");
    // jMenuBar1.add(jMenu4);
    // jMenu5.setText("Recordings");
    // jMenuBar1.add(jMenu5);
    // jMenu6.setText("Agents");
    // jMenuBar1.add(jMenu6);
    // jMenu7.setText("Time Zones");
    // jMenuBar1.add(jMenu7);
    // jMenu8.setText("Help");
    // jMenuBar1.add(jMenu8);
    // 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()
    // .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // layout.setVerticalGroup(
    // layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(layout.createSequentialGroup()
    // .add(78, 78, 78)
    // .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // pack();
    // }// </editor-fold>
    public void getConnection()
    // Object src=evt.getSource();
    String name="";
    String call_back_date="";
    String call_back_time="";
    String called_on="";
    String called_at="";
    String phone="";
    String comments="";
    // if(src==jButton8)
    try{
    colnames=new String[]{"name","call_back_date","call_back_time","called_on","called_at","phone","comments"};
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url="jdbc:oracle:thin:@localhost:1521:oracle";
    Connection con=DriverManager.getConnection(url,"scott","root");
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery("select * from Callbacks_details");
              while (rs.next())
              name=rs.getString("name");
              call_back_date=rs.getString("call_back_date");
              call_back_time=rs.getString("call_back_time");
    called_on=rs.getString("called_on");
    called_at=rs.getString("called_at");
              phone=rs.getString("phone");
    comments=rs.getString("comments");
    Vector row = new Vector(colnames.length);
    // Vector r=new Vector();
              row.addElement(name);
              row.addElement(call_back_date);
              row.addElement(call_back_time);
    row.addElement(called_on);
    row.addElement(called_at);
              row.addElement(phone);
    row.addElement(comments);
              data.addElement(row);
    // System.out.println(data);
    catch(Exception a)
    a.printStackTrace();
    System.out.println(a);
    table=new JTable(new MyTableModel(colnames,data));
    //int n=table.getColumnCount();
              TableColumn column=null;
              for (int i = 0; i<colnames.length; i++) {
              column = table.getColumnModel().getColumn(i);
         column.setPreferredWidth(100);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
    public class MyTableModel extends AbstractTableModel{
    String[] columnNames;
         Vector d= new Vector(6);
    MyTableModel(String[] columnNames, Vector data){
         this.columnNames = columnNames;
         d = data;
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return d.size();
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
         Vector d

    for displaying table on same frame(do not cross post and use code tags just click CODE and paste the code in between)
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    public class TableShow extends JFrame{
        /** Creates a new instance of TableShow */
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        public TableShow() {
            jTable1 = new javax.swing.JTable(5,5);
            jScrollPane1 = new javax.swing.JScrollPane(jTable1);
            jButton1 = new javax.swing.JButton("Show");
            jPanel1 = new javax.swing.JPanel();
            jPanel1.setLayout(new BorderLayout());
            jPanel1.add(jScrollPane1);
            jScrollPane1.setVisible(false);
            getContentPane().add(jButton1, BorderLayout.NORTH);
            getContentPane().add(jPanel1, BorderLayout.CENTER);
            setVisible(true);
            setSize(300,300);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(jScrollPane1.isVisible()) {
                        jScrollPane1.setVisible(false);
                    } else{
                        jScrollPane1.setVisible(true);
                    jPanel1.validate();
        public static void main(String args[]){
            new TableShow();
    }

  • Java swing dynamic forms (in a loop)

    Hi All,
    Is it possible to dynamically create forms using java swing? What I mean to ask is that if I have the necessary information in a table, like the label and a corresponding text field, I can loop through and create the required number of fields. If I do it this way and when the users add text, will I not lose the ability to access each JTextField through its own variable? Is this possible? Basically, I need to be able to access each field through its own variable to do some additional validations on the text entered, etc. Please let me know, if it is possible through java swing.
    Any help in this regard is greatly appreciated.
    Thanks.

    mrbean1975 wrote:
    ..Is it possible to dynamically create forms using java swing? If by java swing you mean Java Swing, then yes.

  • I need to control the position and size of each java swing component, help!

    I setup a GUI which include 2 panels, each includes some components, I want to setup the size and position of these components, I use setBonus or setSize, but doesn't work at all. please help me to fix it. thanks
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.FlowLayout;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.event.*;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.JPanel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.DefaultListModel;
    public class weather extends JFrame {
    private String[] entries={"1","22","333","4444"} ;
    private JTextField country;
    private JList jl;
    private JTextField latitude;
    private JTextField currentTime;
    private JTextField wind;
    private JTextField visibilityField;
    private JTextField skycondition;
    private JTextField dewpoint;
    private JTextField relativehumidity;
    private JTextField presure;
    private JButton search;
    private DefaultListModel listModel;
    private JPanel p1,p2;
    public weather() {
         setUpUIComponent();
    setTitle("Weather Report ");
    setSize(600, 400);
    setResizable(false);
    setVisible(true);
    private void setUpUIComponent(){
         p1 = new JPanel();
    p2 = new JPanel();
         country=new JTextField(10);
         latitude=new JTextField(12);
    currentTime=new JTextField(12);
    wind=new JTextField(12);
    visibilityField=new JTextField(12);
    skycondition=new JTextField(12);
    dewpoint=new JTextField(12);
    relativehumidity=new JTextField(12);
    presure=new JTextField(12);
    search=new JButton("SEARCH");
    listModel = new DefaultListModel();
    jl = new JList(listModel);
    // jl=new JList(entries);
    JScrollPane jsp=new JScrollPane(jl);
    jl.setVisibleRowCount(8);
    jsp.setBounds(120,120,80,80);
    p1.add(country);
    p1.add(search);
    p1.add(jsp);
    p2.add(new JLabel("latitude"));
    p2.add(latitude);
    p2.add(new JLabel("time"));
    p2.add(currentTime);
    p2.add(new JLabel("wind"));
    p2.add(wind);
    p2.add(new JLabel("visibility"));
    p2.add(visibilityField);
    p2.add(new JLabel("skycondition"));
    p2.add(skycondition);
    p2.add(new JLabel("dewpoint"));
    p2.add(dewpoint);
    p2.add(new JLabel("relativehumidity"));
    p2.add(relativehumidity);
    p2.add(new JLabel("presure"));
    p2.add(presure);
    this.getContentPane().setLayout(new FlowLayout());
    this.setLayout(new GridLayout(1,2));
    p2.setLayout(new GridLayout(8, 2));
    this.add(p1);
    this.add(p2);
    public static void main(String[] args) {
    JFrame frame = new weather();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    [http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]
    db

  • Java Swing App hangs on socket loop

    H}ello everyone i've run into a bit of a snag with my application, its a simple chat bot right now but will evolve into a chat client soon. I can't do that however since my app hangs when i look through the readLine() function to receive data and i dont know how to fix this error. The code is below.
    The doSocket() function is where the while loop is if anyone can help me with this i'd be very greatful.
    * GuiFrame.java
    * Created on August 13, 2008, 9:36 PM
    import java.net.*;
    import java.io.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author  brian
    public class GuiFrame extends javax.swing.JFrame {
        /** Creates new form GuiFrame */
        public GuiFrame() {
            initComponents();
        Socket client_sock = null;
        PrintWriter out = null;
        BufferedReader in = null;
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            convertButton = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Test Bot");
            convertButton.setText("Connect");
            convertButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    convertButtonActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addComponent(convertButton)
                    .addContainerGap(42, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addComponent(convertButton)
                    .addContainerGap(26, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
    private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        if (convertButton.getText()=="Connect") {
                    String old;
                    try {
                        client_sock = new Socket("www.spinchat.com", 3001);
                        out = new PrintWriter(client_sock.getOutputStream(), true);
                        in = new BufferedReader(new InputStreamReader(client_sock.getInputStream()));
                    } catch (UnknownHostException e) {
                    } catch (IOException e) {
                try {
                    doSocket();
                } catch (IOException ex) {
                    Logger.getLogger(GuiFrame.class.getName()).log(Level.SEVERE, null, ex);
        } else if (convertButton.getText()=="Disconnect") {
            out.println("e");
            out.close();
            try {
                client_sock.close();
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(GuiFrame.class.getName()).log(Level.SEVERE, null, ex);
    private void doSocket() throws IOException {
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String userInput;
        String old;
            while ((userInput = stdIn.readLine()) != null) {
                old = userInput;
                if (userInput != old) {
                    String proto = userInput.substring(0, 0);
                    if (proto == ":") {
                        out.println("{2");
                        out.println("BI'm a bot.");
                        out.println("aNICKHERE");
                        out.println("bPASSHERE");
                    } else if (proto == "a") {
                        convertButton.setText("Disconnect");
                        out.println("JoinCHannel");
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new GuiFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JButton convertButton;
        // End of variables declaration                  
    }Edited by: briansykes on Aug 13, 2008 9:55 PM
    Edited by: briansykes on Aug 13, 2008 9:56 PM

    >
    ..i've run into a bit of a snag with my application, its a simple chat bot right now but will evolve into a chat client soon. >Is this intended as a GUId app? If so, I would stick to using a GUI for input, rather than reading from the command line (which when I run it, is the DOS window that jumps up in the BG - quite counterintuitive). On the other hand, if it is intended as a non-GUId or headless app., it might be better to avoid any use of JComponents at all.
    My edits stick to using a GUI.
    Other notes:
    - String comparison should be done as
    s1.equals(s2)..rather than..
    s1 == s2- Never [swallow exceptions|http://pscode.org/javafaq.html#stacktrace] in code that does not work.
    - Some basic debugging skills are well called for here, to find where the program is getting stuck. When in doubt, print out!
    - What made you think that
    a) a test of equality on a member against which you had just set the value to the comparator, would logically lead to 'false'?
    old = userInput;
    if (userInput != old) ..b) A substring from indices '0 thru 0' would provide 1 character?
    String proto = userInput.substring(0, 0);
    if (proto == ":") ..
    >
    ..if anyone can help me with this i'd be very greatful.>Gratitude is often best expressed through the offering of [Duke Stars|http://wikis.sun.com/display/SunForums/Duke+Stars+Program+Overview].
    * GuiFrame.java
    * Created on August 13, 2008, 9:36 PM
    import java.net.*;
    import java.io.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    * @author  brian
    public class GuiFrame extends JFrame {
        /** Creates new form GuiFrame */
        public GuiFrame() {
            initComponents();
        Socket client_sock = null;
        PrintWriter out = null;
        BufferedReader in = null;
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            convertButton = new JButton();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Test Bot");
            convertButton.setText("Connect");
            convertButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    convertButtonActionPerformed(evt);
            GroupLayout layout = new GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addComponent(convertButton)
                    .addContainerGap(42, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addComponent(convertButton)
                    .addContainerGap(26, Short.MAX_VALUE))
            pack();
            setLocationByPlatform(true);
        }// </editor-fold>
    private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
        if (convertButton.getText()=="Connect") {
                    String old;
                    try {
                        System.out.println( "Connect start.." );
                        client_sock = new Socket("www.spinchat.com", 3001);
                        out = new PrintWriter(client_sock.getOutputStream(), true);
                        in = new BufferedReader(new InputStreamReader(client_sock.getInputStream()));
                        System.out.println( "Connect end.." );
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                try {
                    doSocket();
                } catch (IOException ex) {
                    Logger.getLogger(GuiFrame.class.getName()).log(Level.SEVERE, null, ex);
        } else if (convertButton.getText()=="Disconnect") {
            out.println("e");
            out.close();
            try {
                client_sock.close();
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(GuiFrame.class.getName()).log(Level.SEVERE, null, ex);
        private void doSocket() throws IOException {
            System.out.println( "doSocket start.." );
            String userInput;
            String old;
            userInput = JOptionPane.showInputDialog(this, "Send..");
            while(userInput!=null && userInput.trim().length()>0) {
                System.out.println( "doSocket loop 1.." );
                String proto = userInput.substring(0, 1);
                System.out.println("proto: '" + proto + "'");
                if (proto.equals(":")) {
                    System.out.println("Sending data..");
                    out.println("{2");
                    out.println("BI'm a bot.");
                    out.println("aNICKHERE");
                    out.println("bPASSHERE");
                } else if (proto.equals("a")) {
                    convertButton.setText("Disconnect");
                    out.println("JoinCHannel");
                userInput = JOptionPane.showInputDialog(this, "Send..");
            System.out.println( "doSocket end.." );
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new GuiFrame().setVisible(true);
        // Variables declaration - do not modify
        private JButton convertButton;
        // End of variables declaration
    }

  • FirstGUI.java:7: Package java.swing not found in import.

    Hi,
    I am currently taking JAVA at UGA and am trying to learn the GUI part on my own, since our professor is not going to cover this. This is the first error I get when I compile the program. Any help is greatly appreciated...
    Thanks,
    Joe
    Below is the program...
    /* A first GUI. This class creates a label and a button. The count in the label is incremented each
    time that the button is pressed.
    import java.awt.*;
    import java.awt.event.*;
    import java.swing.*;
    public class FirstGUI extends JPanel {
         // Instance variables
         private int count = 0;          // Number of pushes
         private JButton pushButton;     // Push button
         private JLabel label;          // Label
         // Initialization method
         public void init() {
              // Set the layout manager
              setLayout( new BorderLayout() );
              // Create a label to hold the push count
              label = new JLabel("Push Count: 0");
              add( label, BorderLayout.NORTH );
              label.setHorizontalAlignment( label.CENTER );
              // Create a button
              pushButton = new JButton("Test Button");
              pushButton.addActionListener( new ButtonHandler (this) );
              add( pushButton, BorderLayout.SOUTH );
              // Method to update push count
              public void updateLabel() {
                   label.setText( "Push Count: " + (++count) );
         // Main method to create frame
         public static void main(String a[]) {
              // Create a frame to hold the application
              JFrame fr = new JFrame("FirstGUI ...");
              fr.setSize(200,100);
              // Create a Window Listener to handle "close" events
              WindowHandler 1 = new WindowHandler();
              fr.addWindowListener(1);
              // Create and initialize a FirstGUI object
              FirstGUI fg = new FirstGUI();
              fg.init();
              // Add the object to the center of the frame
              fr.getContentPane().add(fg, BorderLayout.CENTER);
              // Display the frame
              fr,setVisible( true );
    class ButtonHandler implements ActionListener {
         private FirstGUI fg;
         // Constructor
         public ButtonHandler ( FirstGUI fg1 ) {
              fg = fg1;
         // Execute when an event occurs
         public void actionPerformed( ActionEvent e ) {
              fg.updateLabel();
    }

    The error is below...
    A:\ENGR1140>javac FirstGUI.java
    FirstGUI.java:39: Identifier expected.
    public static void main(String s[]) {
    ^
    FirstGUI.java:39: 'class' or 'interface' keyword expected.
    public static void main(String s[]) {
    ^
    I don't think the actual error is on line 39, I looked in the book that has the code and line 39 is typed just as it is shown in the book.
    Below is the program...
    /* A first GUI. This class creates a label and a button. The count in the label is incremented each
    time that the button is pressed.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FirstGUI extends JPanel {
         // Instance variables
         private int count = 0;          // Number of pushes
         private JButton pushButton;     // Push button
         private JLabel label;          // Label
         // Initialization method
         public void init() {
              // Set the layout manager
              setLayout( new BorderLayout() );
              // Create a label to hold the push count
              label = new JLabel("Push Count: 0");
              add( label, BorderLayout.NORTH );
              label.setHorizontalAlignment( label.CENTER );
              // Create a button
              pushButton = new JButton("Test Button");
              pushButton.addActionListener( new ButtonHandler (this) );
              add( pushButton, BorderLayout.SOUTH );
              // Method to update push count
              public void updateLabel() {
                   label.setText( "Push Count: " + (++count) );
         // Main method to create frame
         public static void main(String s[]) {
              // Create a frame to hold the application
              JFrame fr = new JFrame("FirstGUI ...");
              fr.setSize(200,100);
              // Create a Window Listener to handle "close" events
              WindowHandler 1 = new WindowHandler();
              fr.addWindowListener(1);
              // Create and initialize a FirstGUI object
              FirstGUI fg = new FirstGUI();
              fg.init();
              // Add the object to the center of the frame
              fr.getContentPane().add(fg, BorderLayout.CENTER);
              // Display the frame
              fr,setVisible( true );
    class ButtonHandler implements ActionListener {
         private FirstGUI fg;
         // Constructor
         public ButtonHandler ( FirstGUI fg1 ) {
              fg = fg1;
         // Execute when an event occurs
         public void actionPerformed( ActionEvent e ) {
              fg.updateLabel();

Maybe you are looking for

  • How can i force my E70 to use voise dialing !!!

    actualy just got this phone.. perfect staff, but... voice dialing dosent work at all !!!. I have broused a lot of discussions and forums but didnt find DIRECT answer. So, first: is i dont see any Option->Playback in the menu in the contact cards.. no

  • Error code -32731 pops up when I try to move files onto LaCie External HD.

    I have a Macbook Air 2014 with i7 and 8gb ram. I have around 20gb left on the internal hard drive. My current OS is Yosemite, 10.10.2. I'm unable to paste/move files to my external hard drive and am instead presented with error code -32731. The exact

  • HP Officejet Pro 8500A Periodically resets itself

    About every 20 minutes the screen on my HP Officejet Pro 8500A goes blank, then redisplays, followed by the carriage shifting sounding like the printer is resetting itself to print a job.  I'm set up on a WiFi connection and have no screen blanking s

  • Adobe reader 11.0.06 will not open

    this reader 11.0.06 which i updated to will not open any pdf or itself even after following tips,instructions etc,i have wasted a day on this ,even removed and installed it three times in case i missed something.i even tried putting back on version 9

  • How to add page numbers (centred) at the foot of a page?

    Even this is confusing! I typed my question hit return and was told I couldn't post a blank message. How do I post my message? I simply want to know how to add a page number at the foot (centred) of a page. Oh! Great! Now I see, I should have known t