Learning Swing

Hi all,
I have been working on JSP, EJB and business aplications.
I want to upgrade my oppurtunities in GUI development using Java Swing. But, I Hardly see few applications on Java Swing. I don 't know the reasons why.
I saw beautiful applications in the "Swing Sightings" in java web site. But, when I search for the books on GUI development using Java Swing, I find there are very less number of applications on Java Swing.
Can somebody suggest me an open source available(something big) in the net which describes a client server based application whose user interface is coded in Java Swing with business logic.
Your help will be greatly appreciated.
Thanks.
Sincerely & truly,
J. Stancil

http://swexpert.com/CA/
This is from an online magazine (no longer published).
There is a very in depth description of producing an IMAP email client in Java. The GUI forms a major part of this and uses Swing. It takes a while to figure out which lessons come where! I found it pretty useful - it's well written.

Similar Messages

  • Infinite loop error after using Java Sun Tutorial for Learning Swing

    I have been attempting to create a GUI following Sun's learning swing by example (example two): http://java.sun.com/docs/books/tutorial/uiswing/learn/example2.html
    In particular, the following lines were used almost word-for-word to avoid a non-static method call problem:
    SwingApplication app = new SwingApplication();
    Component contents = app.createComponents();
    frame.getContentPane().add(contents, BorderLayout.CENTER);I believe that I am accidentally creating a new instance of the gui class repeatedly (since it shows new GUI's constantly and then crashes my computer), possibly because I am creating an instance in the main class, but creating another instance in the GUI itself. I am not sure how to avoid this, given that the tutorials I have seen do not deal with having a main class as well as the GUI. I have googled (a nice new verb) this problem and have been through the rest of the swing by example tutorials, although I am sure I am simply missing a website that details this problem. Any pointers on websites to study to avoid this problem would be appreciated.
    Thanks for your time-
    Danielle
    /** GUI for MicroMerger program
    * Created July/06 at IARC
    *@ author Danielle
    package micromerger;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.swing.JFileChooser;
    import java.lang.Object;
    public class MGui
         private static File inputFile1, inputFile2;
         private static File sfile1, sfile2;
         private static String file1Name, file2Name;
         private String currFile1, currFile2;
         private JButton enterFile1, enterFile2;
         private JLabel enterLabel1, enterLabel2;
         private static MGui app;
         public MGui()
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        System.out.println("About to run create GUI method");
                        app = new MGui();
                        System.out.println("declared a new MGui....");
                        createAndShowGUI();
         //initialize look and feel of program
         private static void initLookAndFeel() {
            String lookAndFeel = null;
         lookAndFeel = UIManager.getSystemLookAndFeelClassName();
         try
              UIManager.setLookAndFeel(lookAndFeel);
         catch (ClassNotFoundException e) {
                    System.err.println("Couldn't find class for specified look and feel:"
                                       + lookAndFeel);
                    System.err.println("Did you include the L&F library in the class path?");
                    System.err.println("Using the default look and feel.");
                } catch (UnsupportedLookAndFeelException e) {
                    System.err.println("Can't use the specified look and feel ("
                                       + lookAndFeel
                                       + ") on this platform.");
                    System.err.println("Using the default look and feel.");
                } catch (Exception e) {
                    System.err.println("Couldn't get specified look and feel ("
                                       + lookAndFeel
                                       + "), for some reason.");
                    System.err.println("Using the default look and feel.");
                    e.printStackTrace();
         // Make Components--
         private Component createLeftComponents()
              // Make panel-- grid layout
         JPanel pane = new JPanel(new GridLayout(0,1));
            //Add label
            JLabel welcomeLabel = new JLabel("Welcome to MicroMerger.  Please Enter your files.");
            pane.add(welcomeLabel);
         //Add buttons to enter files:
         enterFile1 = new JButton("Please click to enter the first file.");
         enterFile1.addActionListener(new enterFile1Action());
         pane.add(enterFile1);
         enterLabel1 = new JLabel("");
         pane.add(enterLabel1);
         enterFile2 = new JButton("Please click to enter the second file.");
         enterFile2.addActionListener(new enterFile2Action());
         pane.add(enterFile2);
         enterLabel2 = new JLabel("");
         pane.add(enterLabel2);
         return pane;
         /** Make GUI:
         private static void createAndShowGUI()
         System.out.println("Creating a gui...");
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("MicroMerger");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Add stuff to the frame
         //MGui app = new MGui();
         Component leftContents = app.createLeftComponents();
         frame.getContentPane().add(leftContents, BorderLayout.WEST);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
    private class enterFile1Action implements ActionListener
         public void actionPerformed(ActionEvent evt)
              JFileChooser chooser = new JFileChooser();
              int rVal = chooser.showOpenDialog(enterFile1);
              if(rVal == JFileChooser.APPROVE_OPTION)
                   inputFile1 = chooser.getSelectedFile();
                   PrintWriter outputStream;
                   file1Name = inputFile1.getName();
                   enterLabel1.setText(file1Name);
    private class enterFile2Action implements ActionListener
         public void actionPerformed(ActionEvent evt)
              JFileChooser chooser = new JFileChooser();
              int rVal = chooser.showOpenDialog(enterFile1);
              if(rVal == JFileChooser.APPROVE_OPTION)
                   inputFile2 = chooser.getSelectedFile();
                   PrintWriter outputStream;
                   file2Name = inputFile2.getName();
                   enterLabel2.setText(file2Name);
    } // end classAnd now the main class:
    * Main.java
    * Created on June 13, 2006, 2:29 PM
    * @author Danielle
    package micromerger;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Main
        /** Creates a new instance of Main */
        public Main()
         * @param args the command line arguments
        public static void main(String[] args)
            MGui mainScreen = new MGui();
            //mainScreen.setVisible(true);
            /**Starting to get file choices and moving them into GPR Handler:
             System.out.println("into main method");
         String file1Name = new String("");
             file1Name = MGui.get1Name();
         System.out.println("good so far- have MGui.get1Name()");
        }// end main(String[] args)
    }// end class Main

    um, yeah, you definitely have a recursion problem, that's going to create an infinite loop. you will eventually end up an out of memory error, if you don't first get the OS telling you you have too many windows. interestingly, because you are deferring execution, you won't get a stack overflow error, which you expect in an infinite recursion.
    lets examine why this is happening:
    in main, you call new MGui().
    new MGui() creates a runnable object which will be run on the event dispatch thread. That method ALSO calls new MGui(), which in turn ALSO creates a new object which will be run on the event dispatch thead. That obejct ALSO calls new MGui(), which ...
    well, hopefully you get the picture.
    you should never unconditionally call a method from within itself. that code that you have put in the constructor for MGui should REALLY be in the main method, and the first time you create the MGui in the main method as it currently exists is unnecessary.
    here's what you do: get rid of the MGui constructor altogether. since it is the implicit constructor anyway, if it doesn't do anything, you don't need to provide it.
    now, your main method should actually look like this:
    public static void main( String [] args ) {
      SwingUtilities.invokeLater( new Runnable() {
        public void run() {
          MGui app = new MGui();
          app.createAndShowGUI();
    }// end mainyou could also declare app and call the constructor before creating the Runnable, as many prefer, because you would have access to it from outside of the Runnable object. The catch there, though, is that app would need to be declared final.
    - Adam

  • Where to learn swing text package

    Hello.
    I have been programming in java for a few year. I haven't made any real project (I am a college student). However, I have learnt lots of java stuff. I have used most of swing component. I even implements my own Renderer, Model, and Component. However I found it very hard to me to start learning about JTextPane and JEditorPane. I need to make my own TextPane to display text getting from my custom Object.
    can anyone tell me place to learn about the JTextPane and its StyleDocuments and those stuffs. I found sun tutorial but did not help much. Thanks in advance.

    Try this Sun's Java Swing Tutorial site:
    http://java.sun.com/docs/books/tutorial/uiswing/index.html

  • Learning swing gui by hand or gui builder?

    Hello,
    Which is a better way of start learning writing swing gui based apps? by hand or using gui builder?
    Do you know any useful web links? or do you consider buying books?
    Thanks.

    >>
    Hmm, the differences:
    1) The GUI builder app resizes correctly.-->>falseJust stating it is false doesn't make it so. I never have any issues with my GUI builder apps resizing correctly. I do have issues making my coded by hand apps resize correctly. Ignorance on my part? Possibly
    I used to use a GUI builder just for complicated layouts and use GridBagLayout for simple dialogs inside an app, but I find myself just using a GUI builder now. Just much quicker and much less hassle.
    As far as maintaining the code if you use the GUI builder for maintanence where is the issue?
    i have never seen a GUI builer that uses
    layoutmangers please point me to the one that you are
    using i would love to take a look
    secondly have you seen tried the little exersise you
    will be suprised at how complex the code is compared
    to the one done by hand!!!!IntelliJ's GUI builder appears to use a custom GridLayout manager, the code it generates appears pretty straightforward to me, doesn't seem overly complicated:
    private void $$$setupUI$$$() {
            mainPanel = new JPanel();
            mainPanel.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
            final JSplitPane splitPane1 = new JSplitPane();
            splitPane1.setContinuousLayout(true);
            splitPane1.setDividerLocation(142);
            mainPanel.add(splitPane1, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, 200), null));
            fileListing = new JTree();
            splitPane1.setLeftComponent(fileListing);
            tabPane = new JTabbedPane();
            splitPane1.setRightComponent(tabPane);
            renameTab = new JPanel();
            renameTab.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(2, 7, new Insets(0, 0, 0, 0), -1, -1));
            tabPane.addTab("Untitled", renameTab);
            final JLabel label1 = new JLabel();
            label1.setHorizontalAlignment(4);
            label1.setText("Current Filename");
            renameTab.add(label1, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null));
            imageScrollPane = new JScrollPane();
            imageScrollPane.setHorizontalScrollBarPolicy(30);
            imageScrollPane.setVerticalScrollBarPolicy(20);
            renameTab.add(imageScrollPane, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 7, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null));
            currentFilenameField = new JTextField();
            renameTab.add(currentFilenameField, new com.intellij.uiDesigner.core.GridConstraints(1, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null));
            final JLabel label2 = new JLabel();
            label2.setText("New Filename");
            renameTab.add(label2, new com.intellij.uiDesigner.core.GridConstraints(1, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null));
            newFilenameField = new JTextField();
            renameTab.add(newFilenameField, new com.intellij.uiDesigner.core.GridConstraints(1, 3, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null));
            renameButton = new JButton();
            renameButton.setText("Rename");
            renameTab.add(renameButton, new com.intellij.uiDesigner.core.GridConstraints(1, 4, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null));
            previousButton = new JButton();
            previousButton.setText("");
            renameTab.add(previousButton, new com.intellij.uiDesigner.core.GridConstraints(1, 5, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null));
            nextImageButton = new JButton();
            nextImageButton.setText("");
            renameTab.add(nextImageButton, new com.intellij.uiDesigner.core.GridConstraints(1, 6, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null));
            htmlGeneratorTab = new JPanel();
            tabPane.addTab("Untitled", htmlGeneratorTab);
        }

  • Haw can i learn swing or 2d?

    i'm from argentina. i studied the basics of java in thinking in java, but honestly, i don't understand anything of swing.i tried reading the html documentation of the API's but i'm new in this and i don't know how to use them nor understand them.
    this is the first programming language i'm studying(or at least trying) to learn deeply. i want to be a java programmer. waht do you think is the next thing i have to do to keep learning java? do i have to study swing or another thing?a little game? please help me cause i'm getting frustrated.(my english isn't good but at least i hope you understood what i tried to say)

    Jan.Gressmann wrote:
    There's a really good documentation on swing avaible at: http://java.sun.com/docs/books/tutorial/uiswing/
    Ditto, for 2D:
    http://java.sun.com/docs/books/tutorial/2d/index.html

  • How to learn Swing....

    Hi all,
    I just start to learn the Swing recently, but I found
    I have completely lost....
    I know Swing is fantastic with all the features, but
    the problems is how I could start to learn them all
    RIGHT FROM THE GROUND and STEP-BY-STEP.
    Any good suggestions on how I should start?
    eg: Books from the ground up, helpful website.....
    Thanks!
    Regds,
    GM.
    p/s: I don't have AWT background.

    The tutorials on the Java site really help you come along there.
    Just come up with a basic idea of what each component does, and then try to use it in 3 or 4 different ways.
    Eventually you'll find ways to combine the parts and pieces together. Even the tutorials hold your hand in using the pieces together.
    The best thing, as in any software learning, is to play with your tools. Try and break 'em. See what they do. Don't be afraid to touch them.

  • Learning Swing - Can't get JLabel to appear in JFrame

    Hi,
    I'm a complete beginner to Java. I'm taking a course that's moving way too fast, in my opinion, and we're currently studying Swing. I've likely missed a lot of basic basic Java fundamentals due to the speed of this class, so if I'm making a ridiculous mistake, please let me know.
    I'm trying to create the following:
    +"Create a GUI interface using the Swing API. Use the JOptionPane class to create a dialog box to ask the+
    +user for the University Name. Create a JFrame that has a label with the University name and create your+
    +own logo. The window should have the capability of inputting first name , last name, and id for a student+
    +in text fields. Once the id is entered open another dialog box with the student information."+
    I'm pretty much done, I'm just having issues getting the output from the first JFrame to appear in the second JFrame. When I create a new JFrame, the title I specify appears, but the normal syntax for a JLabel just isn't working and I'm not sure why.
    I suspect it has something to do with the general structure of my program rather than my syntax. ...I know I'm missing a lot of fundamentals that I should have developed, thanks to the way the course I'm in is structured.
    I'm posting two .java files. The first, called GUIFrame.java is the class that basically does everything, it calls JOptionPane, opens the first and second JFrames, and uses ActionEvent and ActionListener to read text from the text fields. The second .java file is called GUITest.java and all it does is instantiate GUIFrame and sets the JFrame parameters.
    If anyone has any suggestions, at all, about how to fix this, or especially how to structure these better... Any suggestion would be greatly appreciated.
    CODE:
    import javax.swing.JFrame; //provides basic window features
    import javax.swing.JOptionPane; //simple GUI input/output
    import javax.swing.JLabel; //displays text and images
    import javax.swing.Icon; //interface used to manipulate images
    import javax.swing.ImageIcon; //loads images
    import java.awt.FlowLayout; // specifies how components are arranged
    import javax.swing.SwingConstants; //common constants used with Swing
    import javax.swing.JTextField;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class GUIFrame extends JFrame
         private JLabel line1;
         private JLabel line2;
         private JLabel line3;
         private JLabel line4;
         private JTextField textField1;
         private JTextField textField2;
         private JTextField textField3;
         //This method prompts the user in a JOptionPane for the university's name.
         public static String obtainUniversityName()
              //Obtain user input from JOptionPane input dialog for universityName.
              String uName = JOptionPane.showInputDialog(null,"Enter the University's name","University Name",JOptionPane.QUESTION_MESSAGE);
              return uName;     
         //This method creates an image icon if possible, or it will print an error and return null
         protected ImageIcon createImageIcon(String path,String description)
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null)
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         public GUIFrame()
              //Create a new JFrame for the university info to be placed in
              //The title of the window is also declared here
              super(obtainUniversityName());
              //Sets way things are arranged
              setLayout(new FlowLayout());
              //Grabs logo and aligns it with "Welcome to the University"
              ImageIcon logo = createImageIcon("girl.gif","This is a logo");
              line1 = new JLabel("Welcome to the University", logo, JLabel.CENTER);
              add(line1);
              //"First Name" + Text Field
              line2 = new JLabel("First Name");
              add(line2);
              textField1 = new JTextField(10);
              add(textField1);
              //"Last Name" + Text Field
              line3 = new JLabel("Last Name");
              add(line3);
              textField2 = new JTextField(10);
              add(textField2);
              //"Student ID" + Text Field
              line4 = new JLabel("Student ID");
              add(line4);
              textField3 = new JTextField(10);
              add(textField3);
              //Register event handlers
              TextFieldHandler handler = new TextFieldHandler();
              textField1.addActionListener(handler);
              textField2.addActionListener(handler);
              textField3.addActionListener(handler);
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
                   String fname = "";
                   String lname = "";
                   String stuid = "";
                   //When user presses enter in any text field, these set values for input into text field
                   if(event.getSource()==textField1)
                        fname = String.format("First Name: %s", event.getActionCommand());
                             else if(event.getSource()==textField2)
                                  lname=String.format("Last Name: %s", event.getActionCommand());
                                       else if(event.getSource()==textField3)
                                            stuid=String.format("Student ID: %s", event.getActionCommand());
                                                 else
                                                      System.out.println("ERROR! You didn't fill in atleast one of the text boxes...");
                   //Creates a new JFrame with title "Student Info"          
                   JFrame frame2 = new JFrame("Student Info");
                   //Sets way things are arranged
                   setLayout(new FlowLayout());
                   //Temporary - Tests to see that processing of text field events occurs correctly
                   System.out.println(fname);
                   System.out.println(lname);
                   System.out.println(stuid);               
                   //Puts data into JLabels for display in new JFrame
                   JLabel label1=new JLabel(fname);
                   add(label1);
                   JLabel label2=new JLabel("Can you see this!?");
                   add(label2);          
                   JLabel label3=new JLabel(stuid);
                   add(label3);
                   //Sets parameters, size, close, visibility, etc, for new JFrame
                   frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame2.setSize(275,210);
                   frame2.setVisible(true);
              }//end void actionPerformed
         }//end TextFieldHandler
    }//end GUIFrame
    ==================================================================================
    import javax.swing.JFrame; //provides basic window features
    public class GUITest
         public static void main(String args[])
              //Calls on GUIFrame class. Instantiates.
              GUIFrame guiFrame = new GUIFrame();
              //Set the window to exit when closed
              guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Size the window
              guiFrame.setSize(275,210);
              //Center the window on the screen
              guiFrame.setLocationRelativeTo(null);
              //Make the window visible
              guiFrame.setVisible(true);
    }

    Thanks so much for the quick response. Yeah, I guess I'm a bit oblivious, I guess I missed that it was supposed to be another JOptionPane.
    I fixed that and got rid of all the second JFrame stuff. Thank you.
    And you're right, now that I can see my output, it's obvious I have serious issues in the actionPerformed() method with the ActionListener. I guess it's just a simple question of how to take what's in all three boxes and output to JOptionPane. Simple logic I guess.
    I don't completely understand the ActionListener. I've read my textbook about it and looked at a few online resources, but I don't have a complete understanding.
    How then, would I be able to use the ActionListener to get the text from all three text fields?
    The way it is now, as you correctly predicted, it waits for enter to be inputted from each text field and whichever text field you hit enter in, despite what's in the other text fields, is the only thing that is outputted to the string in the JOptionPane.
    Do you have a suggestion for that?
    Thanks again.
    CODE:
    import javax.swing.JFrame; //provides basic window features
    import javax.swing.JOptionPane; //simple GUI input/output
    import javax.swing.JLabel; //displays text and images
    import javax.swing.Icon; //interface used to manipulate images
    import javax.swing.ImageIcon; //loads images
    import java.awt.FlowLayout; // specifies how components are arranged
    import javax.swing.SwingConstants; //common constants used with Swing
    import javax.swing.JTextField;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class GUIFrame extends JFrame
         private JLabel line1;
         private JLabel line2;
         private JLabel line3;
         private JLabel line4;
         private JTextField textField1;
         private JTextField textField2;
         private JTextField textField3;
         //This method prompts the user in a JOptionPane for the university's name.
         public static String obtainUniversityName()
              //Obtain user input from JOptionPane input dialog for universityName.
              String uName = JOptionPane.showInputDialog(null,"Enter the University's name","University Name",JOptionPane.QUESTION_MESSAGE);
              return uName;     
         //This method creates an image icon if possible, or it will print an error and return null
         protected ImageIcon createImageIcon(String path,String description)
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null)
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         public GUIFrame()
              //Create a new JFrame for the university info to be placed in
              //The title of the window is also declared here
              super(obtainUniversityName());
              //Sets way things are arranged
              setLayout(new FlowLayout());
              //Grabs logo and aligns it with "Welcome to the University"
              ImageIcon logo = createImageIcon("girl.gif","This is a logo");
              line1 = new JLabel("Welcome to the University", logo, JLabel.CENTER);
              add(line1);
              //"First Name" + Text Field
              line2 = new JLabel("First Name");
              add(line2);
              textField1 = new JTextField(10);
              add(textField1);
              //"Last Name" + Text Field
              line3 = new JLabel("Last Name");
              add(line3);
              textField2 = new JTextField(10);
              add(textField2);
              //"Student ID" + Text Field
              line4 = new JLabel("Student ID");
              add(line4);
              textField3 = new JTextField(10);
              add(textField3);
              //Register event handlers
              TextFieldHandler handler = new TextFieldHandler();
              textField1.addActionListener(handler);
              textField2.addActionListener(handler);
              textField3.addActionListener(handler);
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
                   String fname = "";
                   String lname = "";
                   String stuid = "";
                   //When user presses enter in any text field, these set values for input into text field
                   if(event.getSource()==textField1)
                        fname = String.format("First Name: %s", event.getActionCommand());
                             else if(event.getSource()==textField2)
                                  lname=String.format("Last Name: %s", event.getActionCommand());
                                       else if(event.getSource()==textField3)
                                            stuid=String.format("Student ID: %s", event.getActionCommand());
                                                 else
                                                      System.out.println("ERROR! You didn't fill in atleast one of the text boxes...");
                   String out = fname + "\n" + lname + "\n" + stuid;
                   JOptionPane.showMessageDialog(null,out);
              }//end void actionPerformed
         }//end TextFieldHandler
    }//end GUIFrame
    import javax.swing.JFrame; //provides basic window features
    public class GUITest
         public static void main(String args[])
              //Calls on GUIFrame class. Instantiates.
              GUIFrame guiFrame = new GUIFrame();
              //Set the window to exit when closed
              guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Size the window
              guiFrame.setSize(275,210);
              //Center the window on the screen
              guiFrame.setLocationRelativeTo(null);
              //Make the window visible
              guiFrame.setVisible(true);
    }Edited by: heathercmiller on Apr 5, 2008 8:56 AM

  • Newbie learning swing

    Hello all. I am trying my hand at swing development for the first time. My experience with C++ has made my transition to java alot simpler. But I am having a problem with a simple little test program. I have a JComboBox, a JList, and a JTextField control. When the combobox gets a new selection, I want it to set the selection in the listbox. This is working. I also want the combobox to be updated when the list selection is updated. This is not working. I know there are probably tons of newbie mistakes so please take it easy on me. I have pasted the class below. Any and all help is appreciated.
    class windemo extends JFrame {
         JTextField jt = new JTextField(150);
         JLabel jl = new JLabel("Foobar");
         JList jl3 = new JList();
         JComboBox jb = new JComboBox();
         public windemo(){
              super("This is my frame");
              addWindowListener(new WindowAdapter() {
                             public void windowClosing(WindowEvent e) {
                                  System.exit(0);
              JPanel jp = new JPanel();
              setContentPane(jp);
              jp.add(jl);
              jt.setSize(new Dimension(100,200));
              jp.add(jt);
              String s[] = {"one", "two","three"};
              jl3 = new JList(s);
              jl3.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
              jl3.setSelectedIndex(0);
              jl3.addListSelectionListener(new ListSelectionListener() {
                   public void valueChanged(ListSelectionEvent e){
                        JList jl2 = (JList) e.getSource();
                        jt.setText((String) jl2.getSelectedValue());
                        if(jb.getItemCount() >0){
                             jb.setSelectedItem((String)jl2.getSelectedValue());
              JComboBox jb = new JComboBox(s);
              jb.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e){
                        JComboBox<String> jb2 = (JComboBox<String>)e.getSource();
                        jt.setText((String) jb2.getSelectedItem());
                        jl3.setSelectedValue(jb2.getSelectedItem(),true);
              jb.addItem(s);
              jb.setSelectedIndex(0);
              jp.add(jb);
              jp.add(jt);
              jp.add(new JScrollPane(jl3));
              pack();
              setVisible(true);
    }

    gimbal2 wrote:
    T.PD wrote:
    2. never use <tt>System.exit()</tt> accept in your main method (and even there if only you really need to return an exit code). Correct way to close a window is <tt>setVisible(false)</tt> or <tt>dispose()</tt>.I have to nitpick. setVisible() does not close the window, it just makes it invisible. The window is still there, using up resources.Of course, this depends on which you want to do ... get rid of the window, or make it invisible so it can be used later.
    ¦{Þ                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Swing vs AWT (which should I learn?)

    I am writting an mp3 player in Java. I am fairly new to Java as all I know is the programming language; I do not know how to make a GUI. I want to make a cross platform mp3 player that should run on mac, windows and Linux. I also want to use some custom buttons made in Photoshop.
    Should I invest time in learning Swing or AWT?
    Thank you for your help.

    Hello,
    this depends on how far You intend to go with "customizing". Swing leaves a few things to the Operating System e.g. Windows or Linux. My swing apps look different under Linux than they do under Windows, because the Frame in which these apps are are drawn is administered by the OP System. On the other hand if customizing means for example changing the java cup icon upper left or changing the Title of the frame, then You will have no problems. More generally spoken: nearly everything can be done as long as You stay with the possibilities You have (Buttons, TextField, Bars ... have a look at the Swing Platfrom !).

  • Learn AWT before Swing?

    I have zero practical knowledge of Java GUI programming.
    Swing sits on top of AWT. Swing is easier than AWT. Yet, so as to understand Swing, and to be able to do things Swing might not be able to do, I am inclined to first only use AWT. Build a base on which to learn Swing.
    A counter argument would be, in my opinion, C vs. C++. While C++ sits on top of C, I don't see any benefit to learning pure C before C++. Further, I don't want things to be too difficult before making them easier regarding GUIs.
    Should the progression be: AWT then Swing? Swing then AWT then Swing? just Swing, and learn AWT if ever needed?

    I agree with the others, just learn swing and the parts of awt you need will just come along.
    But I want to add that using a GUI generator to create swing for you is very tempting, especially at first, but is the worst thing you can do to handicap yourself. I know you didn't mention them, so this is sort of comming from left field, but just saying avoid them until you really know swing.
    Also, how can you not see a benefit in learning C before C++? True C++ (even if not always practiced) is object oriented whereas true C is procedural. While OO programming is generally better, it is beneficial to understand procedural programming as well, and knowing both will only make you better as a programmer. But even more important is by never learning true C one never has a chance to learn just how powerful pointers are. Pointers are difficult to get your head around, but they are extreemly usefull, if you are one of the few rare people who can use them correctly and unlock their true power.
    Just Saying.
    JSG

  • IDE STUDIO CREATOR OR SWING

    I am new to development and started on VB where they had a GUI that was easy for me to learn. I was worried when I switched to JAVA, although I enjoy it I was worried about the GUI, until I found Studio Creator. Can you use Studio Creator for programming where you use it with patterns and such in the development of software programs? It seems to be able to take the code (my cursory view of the manual).
    I downloaded the manual and it seems just for web use, is there something similar in JAVA that I can use for software development that is as user friendly? Thank you for you help I know that this is a novice question but figured this might be the right forum.
    Thank you in advance for your time and help.

    It is not Studio Creator or Swing.
    Studio Creator is an IDE. And IDE is a nice tool to can speed up and improve the development of code. However, if it is generating code (especially GUI code), and you don't know how to do it by hand, then I would recommend you learn Swing by hand first before you use and IDE to generate it for you. It will save you headaches in the future. Here is a good Swing tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/index.html

  • NetBean Swing or Swing without NetBean

    In previous posts I have mentioned about me using BlueJ. Ive tried NetBeans IDE and find it better than BlueJ so I am using NetBeans now. One area of NetBeans uses Swing GUI components which allows you to build GUIs and creates the source code for you. There seems to be alot of information in the Oracle tutorials on Swing outside Netbeans. and at the moment I am still learning the Java programming language and do not know how important learning Swing is. This leads me to the question: Is using Swing in NetBeans enough to get by in creating GUIs or what aspects in Swing are the most important to use in conjunction with Swing in NetBeans?

    You can do desktop or web application development (there are others). I suggest you do web application development instead of desktop since I believe there are more employment opportunites there. If you decide to go that route, I suggest you dump Swing and go with JSF. Its part of the recommended JEE technology stack (http://www.oracle.com//technetwork/java/javaee/tech/index.html). I also suggest you use either Netbeans IDE or Eclipse IDE since they are the most popular with experienced developers. You'll also need a (free) database. I suggest Oracle Express. For a server: Tomcat or Glassfish.
    I suggest the first book you read is on Java, then on Servlets, then on  JSF. I suggest you keep away from JSP, its older technology. However, you will eventually need to read up on it since so many web applications are written with it. You will probably need to maintain those types of web applications when employed. Which other technologies to study and in which order in the above mentioned link is a subject for another day.

  • Actionlistener in swing won't let me play with my variables!

    I am sort of new to java, having done some scripting before, but not much programming experiance. OOP was, until I learned java, something I didn't use that much. All this static and public stuff was hard at first, but I finally think I understand it all.
    I am still learning java, and for one of my projects, I am trying to make a small quiz game to learn swing. I am having problems. My button actionlistener complains about my variables, and I have tried many things, like wrapping them in a container and moving them, but I cannot make it compile. Any help would be appriciated. Thanks in advance!
    //The program is a quiz thingy.
    //the error is down in the GUI section, where I make the button respond to commands
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;//for later use, download files to read off net
    import java.io.*;
    import java.math.*;
    import java.util.Random;
    public class Main {
    public static void main(String args[]) { 
      File file = new File("problems.txt");
      int probcount=5;
      int answercount=0;
      boolean onproblem = true;
      String[] Problems={"","","","","","","","","","","",""};//I find if I don't init, I get nullpointer errors
      String[] Answers={"","","","","","","","","","","",""};//sorry for the oddness
      String[] thetext=new String[100];
      int i=0;
      int t=0;
      if ( !file.exists(  ) || !file.canRead(  ) ) {
                    System.out.println( "Can't read " + file );
                    return;
                    try {
                        FileReader fr = new FileReader ( file );
                        BufferedReader in = new BufferedReader( fr );
                        String line;
                        while ((line = in.readLine(  )) != null ){
                            thetext=line;
    i++;
    catch ( FileNotFoundException e ) {
    System.out.println( "File Disappeared" );
    catch ( IOException e ) {
    System.out.println( "Error During File Reading" );
    boolean writetoprob = true;
    for(int y=0;y<i;y++)
    System.out.println(thetext[y]);
    for(int y=0;y<i;y++){
    if(thetext[y].equals("-")){
    if(writetoprob==true)
    writetoprob=false;
    else{
    writetoprob=true;
    t++;
    else{
    if(writetoprob==true)
    Problems[t]=Problems[t].concat("\n").concat(thetext[y]);
    else
    Answers[t]=Answers[t].concat("\n").concat(thetext[y]);
    System.out.println(Problems[0]);
    System.out.println(Problems[1]);
    //TODO:Randomize problems and display them, then answers when button clicked
    boolean answerbutton=true;
    int probindex=0;
    Random rnums = new Random();
    probindex=rnums.nextInt()%(t+1);
    if(probindex<0)
    probindex=-probindex;
    System.out.println(probindex);
    System.out.println(Problems[probindex]);
    JButton action = new JButton("Click for Answer!");
    JTextArea tp = new JTextArea(Problems[probindex]);
    JFrame jf = new JFrame();
    boolean onanswer = false;
    action.addActionListener( new ActionListener( ) {
    public void actionPerformed(ActionEvent theaction) {
    System.out.println(answerbutton);
    if(answerbutton==false){
    answerbutton=true;
    probindex=rnums.nextInt()%(t+1);
    if(probindex<0)
    probindex=-probindex;
    tp.setText(Problems[probindex]);
    else{
    answerbutton=false;
    tp.setText(Answers[probindex]);
    Container content = jf.getContentPane( );
    content.setLayout(new FlowLayout( ));
    content.add(tp);
    content.add(action);
    jf.pack();
    jf.setVisible(true);

    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\Patrick\FirstCup\build\classes
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:91: local variable answerbutton is accessed from within inner class; needs to be declared final
    System.out.println(answerbutton);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:92: local variable answerbutton is accessed from within inner class; needs to be declared final
    if(answerbutton==false){
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:93: local variable answerbutton is accessed from within inner class; needs to be declared final
    answerbutton=true;
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:94: local variable probindex is accessed from within inner class; needs to be declared final
    probindex=rnums.nextInt()%(t+1);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:94: local variable rnums is accessed from within inner class; needs to be declared final
    probindex=rnums.nextInt()%(t+1);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:94: local variable t is accessed from within inner class; needs to be declared final
    probindex=rnums.nextInt()%(t+1);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:95: local variable probindex is accessed from within inner class; needs to be declared final
    if(probindex<0)
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:96: local variable probindex is accessed from within inner class; needs to be declared final
    probindex=-probindex;
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:96: local variable probindex is accessed from within inner class; needs to be declared final
    probindex=-probindex;
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:97: local variable Problems is accessed from within inner class; needs to be declared final
    tp.setText(Problems[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:97: local variable probindex is accessed from within inner class; needs to be declared final
    tp.setText(Problems[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:97: local variable tp is accessed from within inner class; needs to be declared final
    tp.setText(Problems[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:100: local variable answerbutton is accessed from within inner class; needs to be declared final
    answerbutton=false;
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:101: local variable Answers is accessed from within inner class; needs to be declared final
    tp.setText(Answers[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:101: local variable probindex is accessed from within inner class; needs to be declared final
    tp.setText(Answers[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:101: local variable tp is accessed from within inner class; needs to be declared final
    tp.setText(Answers[probindex]);
    16 errors
    BUILD FAILED (total time: 3 seconds)

  • Facing problem in Java Swing

    Hi Sir,
    I am using a java GUI Object for taking user name and password (in fields of user name and password) and would like to send the information to a server (in the form of Xml file) on the click of 'Ok' button. The database of registered user is stored on server. If the entered users name or passwords are not correct, the server will send a failure notification to the client (terminal where we typed user name and password). If this is successful, it gives a success notification.
    I am doing this using Swings. Also I want all the communication taking place between the server and the client in the form of XML files. being a new to Swings I am facing certain difficulty.
    I will appreciate your suggestions and help in this regard.
    Thanks and regards,
    Sarib

    817439 wrote:
    Could you please tell me under which category I should post this query. I could not find JAVA Swing section anywhetre in forum home.Steps
    1. Determine what it is that you want the database to do and what you want your code to do. This does NOT involve writing code.
    2. Learn JDBC
    3. Write JDBC classes that does ONLY the database functionality from 1. If it has GUI (swing) code then it is wrong.
    4. Unit test it.
    5. Learn Swing
    6. Write GUI (swing) code that uses the code from 3.
    7. Test it.
    There is a forum for JDBC - steps 2,3,4.
    There is a forum for Swing - steps 5, 6, 7.

  • JDBC-ODBC Bridge, Swing Components

    This program displays information from the Access database Autos.mdb.
    Uses the JDBC-ODBC Bridge.
    Requires a DSN called Autos pointing to Auto.mdb
    I am using the swing components and can't seem to set up my combobox to pull the right data which doesn't display any of the data from the database. I am able to do it using AWT but would like a sleeker look so I am trying to convert. I have made the text bold where I am having the problem. Any insight would be greatful! I am very new to JDBC-ODBC so please go easy on me...
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class JDBCApp extends Frame implements ItemListener
         //Declare database variables
         Connection conVehicle;
         Statement cmdVehicle;
         ResultSet rsVehicle;
         boolean blnSuccessfulOpen = false;
         //Declare components
         JComboBox lstManuf   = new JComboBox();
         JLabel lblModel  = new JLabel("                          ");
         JLabel lblYear        = new JLabel("                          ");
         JLabel lblCost      = new JLabel("                          ");
         JLabel lblID      = new JLabel("                              ");
         JLabel lblInstructions = new JLabel("Select Manufacturer to Display Record");
         public static void main(String args[])
              //Declare an instance of this application
              JDBCApp thisApp = new JDBCApp();
              thisApp.createInterface();
         public void createInterface()
              //Load the database and set up the frame
              loadDatabase();
              if (blnSuccessfulOpen)
                   setTitle("Display Auto's Database");
                   addWindowListener(new WindowAdapter()
                             public void windowClosing(WindowEvent event)
                                  stop();
                                  System.exit(0);
                   setLayout(new FlowLayout());
                   add(new JLabel("Manufacturer"));
                   add(lstManuf);
                   lstManuf.addItemListener(this);
                   add(lblInstructions);
                   add(new JLabel("Model"));
                   add(lblModel);
                   add(new JLabel("Year"));
                   add(lblYear);
                   add(new JLabel("Cost"));
                   add(lblCost);
                   add(new JLabel("Vehicle Identification"));
                   add(lblID);
                   setSize(300,300);
                   setVisible(true);
              else
                   stop();             //Close any open connection
                   System.exit(-1);    //Exit with error status
              public void loadDatabase()
                   try
                        //Load the MicroSoft drivers
                        Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
                   catch (ClassNotFoundException err)
                             //No drivers found
                             System.err.println("Driver did not load properly");
                   try
                        //Connect to the database
                        conVehicle = DriverManager.getConnection("jdbc:odbc:Auto");
                        //Create a ResultSet
                        cmdVehicle = conVehicle.createStatement();
                        rsVehicle = cmdVehicle.executeQuery(
                                            "Select * from Vehicle;");
                        loadNames(rsVehicle);
                        blnSuccessfulOpen = true;
                   catch(SQLException error)
                        System.err.println("Error: " + error.toString());
         public void loadNames(ResultSet rsVehicle)
              try
                   //Fill last name list box
                   while(rsVehicle.next())
                   lstManuf.addItem(rsVehicle.getString("Manufacturer"));
              catch (SQLException error)
                   System.err.println("Error in display record");
         public void itemStateChanged(ItemEvent event)
              //Display the selected record
              lblInstructions.setText("");          String strManufName = lstManuf.getText();
              try
                   Statement cmdVehicle = conVehicle.createStatement();
                   ResultSet rsVehicle = cmdVehicle.executeQuery(
                        "Select * from Vehicle where [Manufacturer] = '" + strManufName + "';");
                   DisplayRecord(rsVehicle);
              catch(SQLException error)
                   System.err.println("Error in recordset");
          public void DisplayRecord(ResultSet rsVehicle)
               try
                   //Display information
                   if(rsVehicle.next()) //If more records remain
                        lblModel.setText(rsVehicle.getString("ModelName"));
                        lblYear.setText(rsVehicle.getString("Year"));
                        lblCost.setText(rsVehicle.getString("CostValue"));
                        lblID.setText(rsVehicle.getString("VehicleID"));
                   else
                        System.err.println("No more records");
              catch (SQLException error)
                   System.err.println("Error in display record");
         public void stop()
              try
                   //Terminate the connection
                   if (conVehicle != null)
                        conVehicle.close();
              catch(SQLException error)
                   System.err.println("Unable to disconnect");
    }

    I am going to help you out but first I would like to advise you not to do this.
    Mixing JDBC and Swing (or any GUI for that matter) like this is not the preferred way to proceed. If you want to learn JDBC then command line/shell is fine. If you want to learn Swing learn Swing. When you want to use the two together learn about MVC first.
    I am advising you to do this because nobody writes code like this (mixing GUI and database and business logic all in one class). So if you want real world training MVC should be what you look at next.
    See http://en.wikipedia.org/wiki/Model-view-controller for more
    As near as I can tell your problem is mostly just because you aren't using the combo box correctly. Try
    String strManufName = lstManuf.getSelectedItem().toString();it's a bit of a hack but will work for your purposes. What you need in the eend is to use the methods JComboxBox has like getSelectedItem() or getSelectedIndex().
    See http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html for more.
    Some other comments.
    1) It's nice to see you aren't just swallowing exceptions but some of them are kind of pointless if you just continue on. Like here
    try
      //Load the MicroSoft drivers
      Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
    catch (ClassNotFoundException err)
      //No drivers found
      System.err.println("Driver did not load properly");
    }And then you continue on with the method. What for? There's no point since the driver didn't load.
    2) Please look into the use of PreparedStatements. Very good things those. You can use them in place of your Statements. They are safer but for your purposes help you by you not having to worry about the formatting of data you bind to queries. For example what happens if a manufacturer name contains a ' (single quote) ? Trouble that's what. PreparedStatements make that problem go away.
    3) Don't use SELECT *. It is always good practice to put the names of the columns you are selecting. This prevents your code from breaking if the order of the columns should change in any way.

Maybe you are looking for