JDialog, form, GridBagLayout

I am working on a form like shown in the Java tutorial: "How to Use SpringLayout", http://java.sun.com/docs/books/tutorial/uiswing/layout/spring.html -> "SpringForm".
I would like to use GridBagLayout. Here is my code:
public class TestDialog extends JDialog {
     private JPanel infoPanel;
     private JLabel infoLabel, nameLabel;
     private JTextField nameField;
     public TestDialog() {
          Dimension dim_dialog = new Dimension(200, 100);
          JPanel pane = new JPanel(new GridBagLayout());
          GridBagConstraints c = new GridBagConstraints();
          c.fill = GridBagConstraints.HORIZONTAL;
          infoPanel = new JPanel();
          c.weightx = 0.5;
          c.gridx = 0;
          c.gridy = 0;
          pane.add(infoPanel, c);
          infoLabel = new JLabel("Some information...");
          infoPanel.add(infoLabel);
          nameLabel = new JLabel("Name:");
          c.weightx = 0.5;
          c.gridx = 0;
          c.gridy = 1;
          pane.add(nameLabel, c);
          nameField = new JTextField(20);
          c.weightx = 0.5;
          c.gridx = 1;
          c.gridy = 1;
          pane.add(nameField, c);
          add(pane);
          setPreferredSize(dim_dialog);       
        setDefaultCloseOperation( DISPOSE_ON_CLOSE );
          pack();
}As you can see, the layout is not correct; I would like to get a layout like in "SpringForm" - plus a JLabel at the top where I can write some informative text...
Can't figure it out at the moment how to use GridBagLayout for that :-/
Thanks!

package com.sun.scjd.edu.gui;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestDialog extends JDialog {
     private JPanel infoPanel;
     private JLabel infoLabel, nameLabel,faxLabel,emailLabel,addressLabel;
     private JTextField nameField,faxField,emailField,addressField;
     public TestDialog() {
          this.setTitle("Gridbag Layout Example");
          Dimension dim_dialog = new Dimension(200, 100);
          JPanel pane = new JPanel(new GridBagLayout());
          GridBagConstraints c = new GridBagConstraints();
//          c.fill = GridBagConstraints.HORIZONTAL;
          infoPanel = new JPanel();
//          c.weightx = 0.5;
          c.gridx = 0;
          c.gridy = 0;
          pane.add(infoPanel, c);
          infoLabel = new JLabel("Some information...");
          c.gridx = 1;
          c.gridy = 1;
          infoPanel.add(infoLabel, c);
          nameLabel = new JLabel("Name:");
//          c.weightx = 0.5;
          c.gridx = 0;
          c.gridy = 1;
          pane.add(nameLabel, c);
          nameField = new JTextField(10);
//          c.weightx = 0.5;
          c.gridx = 1;
          c.gridy = 1;
          pane.add(nameField, c);
          Insets in = new Insets(5,5,5,5);
          faxLabel = new JLabel("Fax:");
          c.gridx = 0;
          c.gridy = 2;
          c.insets = in;
          pane.add(faxLabel, c);
          faxField = new JTextField(10);
          c.gridx = 1;
          c.gridy = 2;
          pane.add(faxField, c);
          emailLabel = new JLabel("Email:");
          c.gridx = 0;
          c.gridy = 3;
          pane.add(emailLabel, c);
          emailField = new JTextField(10);
          c.gridx = 1;
          c.gridy = 3;
          pane.add(emailField, c);
          addressLabel = new JLabel("Address:");
          c.gridx = 0;
          c.gridy = 4;
          pane.add(addressLabel, c);
          addressField = new JTextField(10);
          c.gridx = 1;
          c.gridy = 4;
          pane.add(addressField,c);
          add(pane);
          setPreferredSize(dim_dialog);       
        setDefaultCloseOperation( DISPOSE_ON_CLOSE );
          setSize(600,300);
     public static void main(String[] args) {
          new TestDialog().setVisible(true);
}Did you expect this ?

Similar Messages

  • Btn in JFrame to Open JDialog

    Hi Guys
    In NetBeans GUI Builder I have created and designed a MainGUI (JFrame Form) that has some buttons. I also went ahead and created and designed a SubGUI (JDialog Form).
    What do I need to do to link MainGUI to SubGUI through the press of a button ????
    I have added the ActionPerformed / ActionEvent method to the button, and inside that I have tried:
    SubGUI.setVisible(true);but it doesn't work !!
    I would greatly appreciate any help.
    Thank You.

    Here is the other bit that I think might be relevant:
    private void starterBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            StarterDialog.setVisible(true);
        private void maincourseBtnActionPerformed(java.awt.event.ActionEvent evt) {                                             
            MainCourseDialog.setVisible(true);
        private void dessertBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            DessertDialog.setVisible(true);
        private void adminBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
            AdminDialog.setVisible(true);
        private void starterListMouseClicked(java.awt.event.MouseEvent evt) {                                        
            Starter selectedStarter = (Starter)starterList.getSelectedValue();
            if (selectedStarter != null)
                populateSDialog(selectedStarter);
        private void sOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
        private void sCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            this.dispose();
        private void maincourseListMouseClicked(java.awt.event.MouseEvent evt) {                                           
            MainCourse selectedMC = (MainCourse)maincourseList.getSelectedValue();
            if (selectedMC != null)
                populateMCDialog(selectedMC);
        private void mcOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                       
            // TODO add your handling code here:
        private void mcCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
        private void dessertListMouseClicked(java.awt.event.MouseEvent evt) {                                        
            Dessert selectedDessert = (Dessert)dessertList.getSelectedValue();
            if (selectedDessert != null)
                populateDDialog(selectedDessert);
        private void dOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
        private void dCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            // TODO add your handling code here:
        private void populateSDialog(Starter s1)
            sNameJLi.setText(s1.getName());
            sCalsJLi.setText(String.valueOf(s1.getCalories()));
            sDescTA.setText(s1.getDescription());
            sPriceJLi.setText(String.valueOf(s1.getPrice()));
        private void populateMCDialog(MainCourse mc1)
            mcNameJLi.setText(mc1.getName());
            mcCalsJLi.setText(String.valueOf(mc1.getCalories()));
            mcDescTA.setText(mc1.getDescription());
            mcPriceJLi.setText(String.valueOf(mc1.getPrice()));
        private void populateDDialog(Dessert d1)
            dNameJLi.setText(d1.getName());
            dCalsJLi.setText(String.valueOf(d1.getCalories()));
            dDescTA.setText(d1.getDescription());
            dPriceJLi.setText(String.valueOf(d1.getPrice()));
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainGUI().setVisible(true);
        }

  • Resetting a program internally

    I have a main JFrame through which multiple JDialog forms may be opened by the user. Is there any command I can type within the main frame that will dispose of all the opened forms and reset everything to how it was when the System was started?

    System.exit(0);
    Will get you out and everything that is in your VM will be disposed. This gets you back to where you started your system, but if you are looking to keep your JVM running and get back to the same state as you were when you started, then you cannot totally do that. At best you can kill off all of your references and at some point the garbage collector will get rid of them (probably when you close your VM).

  • How to set old content for a field when cancel?

    Hallo,
    i have a jdialog form where i can change the content of a field.
    when i close the form with cancel i will bring the old content back.
    how can i do that?
    thanks in advance. any help is appreciated.

    Huh? Just don't update the content when the dialog is dismissed by pressing 'Cancel'.
    To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    db

  • Intermediary bean causing NullPointerException

    Hi all,
    I wonder if someone could help me with an issue I'm having.
    I've got a JTable bound to database fields, and when the user selects a field and clicks an "Edit" button, I'm generating an object using ConvertRowIndexToModel() method, and passing the Object to a JDialog form, using an intermediary bean object called currentPigment.
    The currentPigment object is bound to various fields in the JDialog, and the bound properties are showing up correctly in the JTextField boxes. If I try to access the bean properties from the JFrame class where my JTable exists, everything is fine. However If I try to access the intermediary bean from within the JDialog, I'm getting a NullPointerException.
    Here is the code from the JFrame holding the JTable linked to the database:
    @Action(enabledProperty = "recordSelected")
        public void editPigment()
            PigmentEditor pe = new PigmentEditor(this, false);
            pe.setCurrentPigment(pigmentList.get(pigmentTable.convertRowIndexToModel(pigmentTable.getSelectedRow())));
            pe.setVisible(true);and here is the bean code in the JDialog class:
        protected Pigment currentPigment;
        public Pigment getCurrentPigment()
            return currentPigment;
        public void setCurrentPigment(Pigment currentPigment)
            Pigment oldCurrentPigment = this.currentPigment;
            this.currentPigment = currentPigment;
            propertyChangeSupport.firePropertyChange("currentPigment", oldCurrentPigment, currentPigment);
        }I need to access the properties of the currentPigment object so I can automatically select an item from a JTable, however if I try to access the objects getters/setters, I get a NullPointerException.
    If someone could explain why this is, or how I can get round it, I'd be greatful.
    Thanks in Advance.

    Okay I figured out what the problem was / is - When the JTable is bound to the nested entity class, because no item is selected, it's removing the nested entity class creating a null value. I also tried changing to a JList and this does the same thing. However if I use a JComboBox, my item renders correctly and the nested entity class displays the correct value without being erased.
    Is it possible to make a JTable select an item, before the bean binding removes the value making it null?
    Many thanks,

  • How to sent information between JFrames!?

    Hi!
    Im writting the system connecting to MySQL data base. Right now im writting the JDialog form the it responsible for deleting. Im putting extra window just as warning window (delete, cancel); how i can sent String from main window to delete/notDelete window. Im starting the window like that. The string is in
    JTextField A;
    A.getText(); // it is my String That i wanna
                         // sent to DELETEWINDOW
    public void ButtonActionPerformed()
    new DELETEWINDOW(new javax.swing.JFrame(), true).setVisible(true);
    }

    It's story time again.
    Aliens land on Earth and somehow end up at a concert hall, watching
    a conductor lead an orchestra. They are enraptured by what they hear
    and decide to observe with care, so that they can implement this on
    their home planet. They watch and note that when the conductor moves his
    baton so, all the violins' bows go up, and when he moves the baton back,
    the bows go down. How is information about what to play sent from the
    baton to the bow?
    In your case, your warning window is so simple that no matter how you
    approach the problem, if you code it, it will work. But do you think the
    aliens will succeed without realizing that there is a model, the musical
    score, on which the music is built, rather than just through gestures?

  • Saving a file from a form to be display on a table

    Hi i'm having some problems trying to save the filled out on the form to be displayed on the table i don't know how i am going to go about it can you please help me thanks.
    Here is the code for the form.
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;              //for layout managers and more
    import java.awt.event.*;        //for action events
    import java.net.URL;
    import java.text.ParseException;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.swing.JComboBox;
    public class DD extends JPanel
                                 implements ActionListener {
        private String newline = "\n";
        protected static final String textFieldString = "Name"; 
        protected static final String textFieldString1 = "Start Time";
        protected static final String textFieldString2 = "End Time";
        protected static final String textFieldString3 = "Total Time(Minutes)";
        protected static final String ftfString = "Date";
        protected static final String buttonString = "JButton";
        JFormattedTextField startTime;
        JTextField totalTime;
        protected JLabel actionLabel;
        Component[][] rowData;
        private String[] shapeName = { "Meeting", "Lunch", "Holiday", "Sickness",
                 "Preparing report", "Administrative work", "Emails", "Query" };
        public DD() {
            setLayout(new BorderLayout());
            Panel data = new Panel();
              data.setLayout(new GridLayout(7, 4));
            rowData = new Component[7][];
    //      One row
                   for (int row = 0; row < 7; row++)
                        rowData[row] = new Component[5];
                        rowData[row][0] = new TextField(10);
                        rowData[row][1] = new TextField(10);
                        ((TextField) rowData[row][1]).addActionListener(this);
                        rowData[row][2] = new JComboBox(shapeName);
                        ((JComboBox) rowData[row][2]).addActionListener(this);
    //      ((TextField)rowData[ row ][ 2 ]).addActionListener(this);
                        rowData[row][3] = new TextField(10);
                        ((TextField) rowData[row][3]).addActionListener(this);
    //      JComboBox jcboxShapeCombo;
    //      System.out.println(rowData[row][2]);
    //      jcboxShapeCombo[2] = new JComboBox (shapeName);
    //      rowData[ row ][ 3 ] = new TextField(10);
                        rowData[row][4] = new TextField(10);
                        ((TextField) rowData[row][4]).addActionListener(this);
                        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
                        ((TextField) rowData[row][0]).setText(sdf.format(new java.util.Date()));
                        data.add(rowData[row][0]);
                        data.add(rowData[row][1]);
                        data.add(rowData[row][2]);
                        data.add(rowData[row][3]);
                        data.add(rowData[row][4]);
            //Create a regular text field.
            JTextField textField = new JTextField(10);
            textField.setActionCommand(textFieldString);
            textField.addActionListener(this);
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
            startTime = new JFormattedTextField(sdf);
            startTime.setValue(new java.util.Date());
            startTime.setActionCommand(textFieldString1);
            startTime.addActionListener(this);
            JTextField textField2 = new JTextField(10);
            textField2.setActionCommand(textFieldString2);
            textField2.addActionListener(this);
            totalTime = new JTextField(10);
            totalTime.setActionCommand(textFieldString3);
            totalTime.addActionListener(this);
            //Create a formatted text field.
            JFormattedTextField ftf = new JFormattedTextField(
                      //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
                    java.util.Calendar.getInstance().getTime());
            ftf.setActionCommand(textFieldString);
            ftf.addActionListener(this);
            //Create some labels for the fields.
            JLabel textFieldLabel = new JLabel(textFieldString + ": ");
            textFieldLabel.setLabelFor(textField);
            JLabel textFieldLabel1 = new JLabel(textFieldString1 + ": ");
            textFieldLabel1.setLabelFor(startTime);
            JLabel textFieldLabel2 = new JLabel(textFieldString2 + ": ");
            textFieldLabel2.setLabelFor(textField2);
            JLabel textFieldLabel3 = new JLabel(textFieldString3 + ": ");
            textFieldLabel3.setLabelFor(totalTime);
            JLabel ftfLabel = new JLabel(ftfString + ": ");
            ftfLabel.setLabelFor(ftf);
            //Create a label to put messages during an action event.
            actionLabel = new JLabel("Type text in a field and press Enter.");
            actionLabel.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
            //Lay out the text controls and the labels.
            JPanel textControlsPane = new JPanel();
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            textControlsPane.setLayout(gridbag);
            JLabel[]labels = {textFieldLabel, textFieldLabel1,textFieldLabel2, textFieldLabel3, ftfLabel};
            JTextField[] textFields = {textField, startTime,textField2,totalTime, ftf};
            addLabelTextRows(labels, textFields, gridbag, textControlsPane);
            c.gridwidth = GridBagConstraints.REMAINDER; //last
            c.anchor = GridBagConstraints.WEST;
            c.weightx = 1.0;
            textControlsPane.add(actionLabel, c);
            textControlsPane.setBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Text Fields"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)));
            //Create a text area.
            JTextArea textArea = new JTextArea(
            textArea.setFont(new Font("Serif", Font.ITALIC, 16));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            JScrollPane areaScrollPane = new JScrollPane(textArea);
            areaScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            areaScrollPane.setPreferredSize(new Dimension(250, 250));
            areaScrollPane.setBorder(
                BorderFactory.createCompoundBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Comment"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)),
                    areaScrollPane.getBorder()));
            //Create an editor pane.
            JEditorPane editorPane = createEditorPane();
            JScrollPane editorScrollPane = new JScrollPane(editorPane);
            editorScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            editorScrollPane.setPreferredSize(new Dimension(250, 145));
            editorScrollPane.setMinimumSize(new Dimension(10, 10));
            String[] initString =
            { "Meeting", "Lunch", "Holiday", "Sickness",
                     "Preparing report", "Administrative work", "Emails", "Query" };
            JList listCategories = new JList(initString);
            JScrollPane editorScrollPane = new JScrollPane(listCategories);
            editorScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            editorScrollPane.setPreferredSize(new Dimension(250, 145));
            editorScrollPane.setMinimumSize(new Dimension(10, 10));
            //Create a text pane.
            JTextPane textPane = createTextPane();
            JScrollPane paneScrollPane = new JScrollPane(textPane);
            paneScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            paneScrollPane.setPreferredSize(new Dimension(250, 155));
            paneScrollPane.setMinimumSize(new Dimension(10, 10));
            //Put the editor pane and the text pane in a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  editorScrollPane,
                                                  paneScrollPane);
            splitPane.setOneTouchExpandable(true);
            splitPane.setResizeWeight(0.5);
            JPanel rightPane = new JPanel(new GridLayout(1,0));
            rightPane.add(splitPane);
            rightPane.setBorder(BorderFactory.createCompoundBorder(
                            BorderFactory.createTitledBorder("Category of Task"),
                            BorderFactory.createEmptyBorder(5,5,5,5)));
            JPanel rightPane = new JPanel(new GridLayout(1,0));
            rightPane.add(editorScrollPane);
            //Put everything together.
            JPanel leftPane = new JPanel(new BorderLayout());
            leftPane.add(textControlsPane,
                         BorderLayout.PAGE_START);
            leftPane.add(areaScrollPane,
                         BorderLayout.CENTER);
            add(leftPane, BorderLayout.LINE_START);
            add(rightPane, BorderLayout.LINE_END);
            JButton button = new JButton("Submit");
            button.setCursor(Cursor.getDefaultCursor());
            //button.setMargin(new Insets(0,0,0,0));
            button.setActionCommand(buttonString);
            button.addActionListener(this);
            add(button, BorderLayout.SOUTH);
            button.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        String toPrint = collectData();
                        newFile(toPrint);
       private String collectData()
              String toPrint = "";
              for (int i = 0; i < rowData.length; i++)
                   Component[] currentRowComps = rowData;
                   for (int j = 0; j < currentRowComps.length; j++)
                        Component currentComp = currentRowComps[j];
                        if (currentComp instanceof TextField)
                             TextField tf = (TextField) currentComp;
                             toPrint += tf.getText() + " - ";
                        else if (currentComp instanceof JComboBox)
                             JComboBox box = (JComboBox) currentComp;
                             Object selection = box.getSelectedItem();
                             if (selection != null)
                                  toPrint += selection.toString() + " - ";
                   toPrint += "\n";
              return toPrint;
         private File newFile(String data)
              File newfile = null;
              try
                   newfile = new File("I:\\ouput.doc");
                   System.out.println("DATA? - " + data);
                   FileOutputStream fos = new FileOutputStream(newfile);
                   fos.write(data.getBytes());
                   fos.close();
                   // JOptionPane.showMessageDialog(null, "Save File");
                   JOptionPane.showMessageDialog(null, "File saved.", "Success",
                   JOptionPane.INFORMATION_MESSAGE);
              catch (IOException ioexc)
                   JOptionPane.showMessageDialog(null, "Error while saving file: " + ioexc,
                   "Error", JOptionPane.ERROR_MESSAGE);
              return null;
    private void addLabelTextRows(JLabel[] labels,
    JTextField[] textFields,
    GridBagLayout gridbag,
    Container container) {
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.EAST;
    int numLabels = labels.length;
    for (int i = 0; i < numLabels; i++) {
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE; //reset to default
    c.weightx = 0.0; //reset to default
    container.add(labels[i], c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    container.add(textFields[i], c);
    public void actionPerformed(ActionEvent e) {
    String prefix = "You typed \"";
    if (textFieldString2.equals(e.getActionCommand()))
    JTextField source = (JTextField)e.getSource();
    actionLabel.setText(prefix + source.getText() + "\"");
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
    try {
                        java.util.Date end = sdf.parse(source.getText());
                        java.util.Date start = sdf.parse(startTime.getText());
                        long difference = (end.getTime() - start.getTime()) / 60000;
                        totalTime.setText(Long.toString(difference));
                   } catch (ParseException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
    if (textFieldString1.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    if (textFieldString2.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    if (textFieldString3.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    else if (textFieldString.equals(e.getActionCommand())) {
    //JPasswordField source = (JPasswordField)e.getSource();
    //actionLabel.setText(prefix + new String(source.getPassword())
    //+ "\"");
    } else if (buttonString.equals(e.getActionCommand())) {
    Toolkit.getDefaultToolkit().beep();
    private JEditorPane createEditorPane() {
    JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);
    java.net.URL helpURL = DD.class.getResource(
    "DailyDairyDemoHelp.html");
    if (helpURL != null) {
    try {
    editorPane.setPage(helpURL);
    } catch (IOException e) {
    System.err.println("Attempted to read a bad URL: " + helpURL);
    } else {
    System.err.println("Couldn't find file: Daily Dairy.html");
    return editorPane;
         private JTextPane createTextPane() {
    String[] initString =
    { "Meeting", "Lunch", "Holiday", "Sickness",
         "Preparing report", "Administrative work", "Emails", "Query" };
    String[] initStyles =
    { "regular", "italic", "bold", "small", "large",
    "regular", "button", "regular", "icon",
    "regular"
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);
    try {
    for (int i=0; i < initString.length; i++) {
    doc.insertString(doc.getLength(), initString[i],
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
    getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);}
    /*s = doc.addStyle("icon", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon pigIcon = createImageIcon("images/Pig.gif",
    "a cute pig");
    if (pigIcon != null) {
    StyleConstants.setIcon(s, pigIcon);
    s = doc.addStyle("button", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon soundIcon = createImageIcon("images/sound.gif",
    "sound icon");
    JButton button = new JButton();
    if (soundIcon != null) {
    button.setIcon(soundIcon);
    } else {
    button.setText("BEEP");
    button.setCursor(Cursor.getDefaultCursor());
    button.setMargin(new Insets(0,0,0,0));
    button.setActionCommand(buttonString);
    button.addActionListener(this);
    StyleConstants.setComponent(s, button);
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path,
    String description) {
    java.net.URL imgURL = DD.class.getResource(path);
    if (imgURL != null) {
    return new ImageIcon(imgURL, description);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event dispatch thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("DailyDairyDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Add content to the window.
    frame.add(new DD());
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event dispatching thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    //Turn off metal's use of bold fonts
              UIManager.put("swing.boldMetal", Boolean.FALSE);
              createAndShowGUI();
    And here is the code for the table.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.util.Date;
    import java.sql.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class DDTable extends JFrame{
         protected JTable m_table;
         protected DDTableData m_data;
         protected JLabel m_title;
         public DDTable(){
              super("DDTABLE");
              setSize(600, 300);
              UIManager.put("Table.focusCellHighlightBorder",new LineBorder(Color.black, 0));
              m_data = new DDTableData();
              m_title = new JLabel(m_data.getTitle(), SwingConstants.CENTER);
              m_title.setFont(new Font("Helvetica", Font.PLAIN, 24));
              getContentPane().add(m_title, BorderLayout.NORTH);
              m_table = new JTable();
              m_table.setAutoCreateColumnsFromModel(false);
              m_table.setModel(m_data);
              for (int k = 0; k < m_data.getColumnCount(); k++) {
                   DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                   renderer.setHorizontalAlignment(DDTableData.m_columns[k].m_alignment);
                   TableColumn column = new TableColumn(k, DDTableData.m_columns[k].m_width, renderer, null);
                   m_table.addColumn(column);
              JTableHeader header = m_table.getTableHeader();
              header.setUpdateTableInRealTime(false);
              setJMenuBar(createMenuBar());
              JScrollPane ps = new JScrollPane();
              ps.getViewport().setBackground(m_table.getBackground());
              ps.getViewport().add(m_table);
              getContentPane().add(ps, BorderLayout.CENTER);
              protected JMenuBar createMenuBar(){
                   JMenuBar menuBar = new JMenuBar();
                   JMenu mFile = new JMenu("File");
                   mFile.setMnemonic('f');
                   Action actionNew = new AbstractAction("New Appointment"){
                        public void actionPerformed(ActionEvent e){
                             if (!promptToSave())
                                  return;
                             newDocument();
                        JMenuItem item = new JMenuItem(actionNew);
                        item.setMnemonic('n');
                        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
                        mFile.add(item);
                        Action actionSave = new AbstractAction("Save Appointment"){
                             public void actionPerformed(ActionEvent e){
                                  boolean m_textChanged = false;
                                  if (!m_textChanged)
                                       return;
                                  saveFile(false);
                              item = new JMenuItem(actionSave);
                             item.setMnemonic('s');
                             item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
                             mFile.add(item);
                   JMenuItem mData = new JMenuItem("Retrieve Data");
                   mData.setMnemonic('r');
                   ActionListener lstData = new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        retrieveData();
                   mData.addActionListener(lstData);
                   mFile.add(mData);
                   mFile.addSeparator();
                   JMenuItem mExit = new JMenuItem("Exit");
                   mExit.setMnemonic('x');
                   ActionListener lstExit = new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             System.exit(0);
                   mExit.addActionListener(lstExit);
                   mFile.add(mExit);
                   menuBar.add(mFile);
                   return menuBar;
              protected void saveFile(boolean b) {
                   // TODO Auto-generated method stub
              protected void newDocument() {
                     //Create and set up the window.
                 JDialog frame = new JDialog();//"DailyDairyDemo");
                 frame.setModal(true);
                 //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Add content to the window.
                 frame.add(new DD());
                 //Display the window.
                 frame.pack();
                 frame.setVisible(true);
                 JOptionPane.showMessageDialog(this, "Done!");
                 //loadFile();
              protected boolean promptToSave() {
                   // TODO Auto-generated method stub
                   return true;
              public void retrieveData(){
                   Runnable updater = new Runnable(){
                        public void run(){
                             SimpleDateFormat frm = new SimpleDateFormat("MM/dd/yyyy");
                             String currentDate = frm.format(m_data.m_date);
                             String result =
                             (String)JOptionPane.showInputDialog(DDTable.this,"Please enter date in form mm/dd/yyyy:", "Input", JOptionPane.INFORMATION_MESSAGE, null, null, currentDate);
                             if (result==null)
                                  return;
                             java.util.Date date = null;
                             try{
                                  date = frm.parse(result);
                             catch (java.text.ParseException ex){
                                  date = null;
                             if (date == null){
                                  JOptionPane.showMessageDialog(DDTable.this, result+" is not a valid date", "Warning", JOptionPane.WARNING_MESSAGE);
                                  return;
                             setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                             try{
                                  m_data.retriveData(date);
                             catch (Exception ex){
                                  JOptionPane.showMessageDialog(DDTable.this,"Error retrieving data:\n"+ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
                             setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                             m_title.setText(m_data.getTitle());
                             m_table.tableChanged(new TableModelEvent(m_data));
                   SwingUtilities.invokeLater(updater);
         public static void main(String argv[]){
              DDTable frame = new DDTable();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
       class DDData{
            public String m_name;
            public String m_date;
            public String m_startTime;
            public String m_endTime;
            public String m_totalTime;
            public String m_comment;
            public String m_category;
            public DDData(String name, String date,String startTime, String endTime, String totalTime, String comment, String category){
                 m_name = name;
                 m_date = date;
                 m_startTime = startTime;
                 m_endTime = endTime;
                 m_totalTime = totalTime;
                 m_comment = comment;
                 m_category = category;
       class ColumnData{
            public String m_title;
            public int m_width;
            public int m_alignment;
            public ColumnData(String title, int width, int alignment) {
                 m_title = title;
                 m_width = width;
                 m_alignment = alignment;
       class DDTableData extends AbstractTableModel{
         private static final long serialVersionUID = 1L;
         static final String QUERY = "SELECT symbols.name,"+"data startTime, data.endTime, data.totalTime, data.comment, data.category FROM DATA INNER JOIN SYMBOLS"
         +"ON DATA.symbol = SYMBOLS.symbol WHERE"+
         "month(data.date1)=? AND day(data.date1)=?"+
         "AND year(data.date1)=?";
         @SuppressWarnings("unchecked")
         public void retriveData(Date date)
         throws SQLException, ClassNotFoundException {
              try {
                   File f = new File("appointments.dat");
                   FileInputStream fis = new FileInputStream(f);
                ObjectInputStream ois = new ObjectInputStream(fis);
                m_vector = (Vector<DDData>) ois.readObject();
                ois.close();
                fis.close();
               } catch(ClassCastException ex) {
               } catch(FileNotFoundException ex) {
               } catch(IOException ex) {
              /*GregorianCalendar calendar = new GregorianCalendar();
              calendar.setTime(date);
              int month = calendar.get(Calendar.MONTH)+1;
              int day = calendar.get(Calendar.DAY_OF_MONTH);
              int year = calendar.get(Calendar.YEAR);
              m_date = date;
              m_vector = new Vector();
              Connection conn = null;
              PreparedStatement pst = null;
              try{
                   //Load the JDBC-ODBC bridge driver
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   conn = DriverManager.getConnection("jdbc:odbc:Market", "admin", "");
                   pst = conn.prepareStatement(QUERY);
                   pst.setInt(1, month);
                   pst.setInt(2, day);
                   pst.setInt(3, year);
                   ResultSet results = pst.executeQuery();
                   while (results.next()){
                        String name = results.getString(1);
                        String startTime = results.getString(2);
                        String endTime = results.getString(3);
                        String totalTime = results.getString(4);
                        String comment = results.getString(5);
                        String category = results.getString(6);
                        m_vector.addElement(new DDData(name, startTime, endTime, totalTime, comment, category, category));
                   sortData();
              finally{
                   if (pst != null )
                        pst.close();
                   if (conn != null)
                        conn.close();
         private void saveData() {
              try {
                   File f = new File("appointments.dat");
                   FileOutputStream fos = new FileOutputStream(f);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(m_vector);
                oos.close();
                fos.close();
               } catch(IOException ex) {
         private void sortData() {
              // TODO Auto-generated method stub
         static final public ColumnData m_columns[] = {
                 new ColumnData("Name", 100, JLabel.LEFT),
                 new ColumnData("Date", 100, JLabel.LEFT),
                 new ColumnData("Start Time", 100, JLabel.RIGHT),
                 new ColumnData("End Time", 100, JLabel.RIGHT),
                 new ColumnData("Total Time", 100, JLabel.RIGHT),
                 new ColumnData("Comment", 200, JLabel.RIGHT),
                 new ColumnData("Category", 100, JLabel.RIGHT),
            protected SimpleDateFormat m_frm;
            protected Vector<DDData> m_vector = new Vector<DDData>();
            protected Date m_date;
            public DDTableData(){
                 m_frm = new SimpleDateFormat("MM/dd/yyyy");
                 setDefaultData();
            public void setDefaultData(){
                 try{
                      m_date = m_frm.parse("07/31/2007");
                 catch (java.text.ParseException ex){
                      m_date = null;
                 m_vector.removeAllElements();
                 m_vector.addElement(new DDData("Jerome", null, "Dan", null, null, null, null));
            public int getRowCount(){
                 return m_vector==null ? 0 : m_vector.size();
            public int getColumnCount(){
                 return m_columns.length;
            public String getColumnName(int column){
                 return m_columns[column].m_title;
            public boolean isCellEditable(int nRow, int nCol){
                 return false;
            public Object getValueAt(int nRow, int nCol){
                 if (nRow < 0 || nRow>=getRowCount())
                      return "";
                 DDData row = m_vector.elementAt(nRow);
                 switch (nCol){
                 case 0: return row.m_name;
                 case 1: return row.m_date;
                 case 2: return row.m_startTime;
                 case 3: return row.m_endTime;
                 case 4: return row.m_totalTime;
                 case 5: return row.m_comment;
                 case 6: return row.m_category;
                 return "";
            public String getTitle(){
                 if (m_date==null)
                      return "Daily Dairy";
                 return "Daily Dairy at "+m_frm.format(m_date);

    here is code to collect the data pls what can i do to get the data on the form display on the JTable in the all categories as on the form pls...
    private String collectData()
              String toPrint = "";
              for (int i = 0; i < rowData.length; i++)
                   Component[] currentRowComps = rowData;
                   for (int j = 0; j < currentRowComps.length; j++)
                        Component currentComp = currentRowComps[j];
                        if (currentComp instanceof TextField)
                             TextField tf = (TextField) currentComp;
                             toPrint += tf.getText() + " - ";
                        else if (currentComp instanceof JComboBox)
                             JComboBox box = (JComboBox) currentComp;
                             Object selection = box.getSelectedItem();
                             if (selection != null)
                                  toPrint += selection.toString() + " - ";
                   toPrint += "\n";
              return toPrint;
         private File newFile(String data)
              File newfile = null;
              try
                   newfile = new File("I:\\ouput.doc");
                   System.out.println("DATA? - " + data);
                   FileOutputStream fos = new FileOutputStream(newfile);
                   fos.write(data.getBytes());
                   fos.close();
                   // JOptionPane.showMessageDialog(null, "Save File");
                   JOptionPane.showMessageDialog(null, "File saved.", "Success",
                   JOptionPane.INFORMATION_MESSAGE);
              catch (IOException ioexc)
                   JOptionPane.showMessageDialog(null, "Error while saving file: " + ioexc,
                   "Error", JOptionPane.ERROR_MESSAGE);
              return null;
    private void addLabelTextRows(JLabel[] labels,
    JTextField[] textFields,
    GridBagLayout gridbag,
    Container container) {
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.EAST;
    int numLabels = labels.length;
    for (int i = 0; i < numLabels; i++) {
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE; //reset to default
    c.weightx = 0.0; //reset to default
    container.add(labels[i], c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    container.add(textFields[i], c);
    Message was edited by:
    desaint
    Message was edited by:
    desaint

  • JOptionPane and JDialog

    Hi guys,
    I've been scooting around the net trying to find an answer to this problem. Basically I have a JDialog that users enter registration details. If they haven't completed all fields or if the password confirmation is wrong then a JOptionPane.showMessageDialog appears telling users what has happened. However if they were to then click ok in the OptionPane it closes both the option pane and the original Dialog window. Have you guys any idea?
    A code snippet below:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class Register extends JDialog implements ActionListener {
         //declare components
         JLabel lblHeading;
         JLabel lblUserName;
         JLabel lblUserPwd;
         JLabel lblCnfUserPwd;
         JLabel lblFrstName;
         JLabel lblLstName;
         JLabel lblAge;
         JLabel lblEmpId;
         JLabel lblSex;
         JLabel lblEmail;
         String usrName;
         String strUsrPwd;
         String strCnfPwd;
         String frstName;
         String lstName;
         String age;
         String empid;
         String email;
         String sex;
         Socket toServer;
         ObjectInputStream streamFromServer;
         PrintStream streamToServer;
         JComboBox listSex;
         JTextField txtUserName;
         JPasswordField txtUsrPwd;
         JPasswordField txtCnfUsrPwd;
         JTextField txtFrstName;
         JTextField txtLstName;
         JTextField txtAge;
         JTextField txtEmpId;
         JTextField txtEmail;
         Font f;
         Color r;
         JButton btnSubmit;
         JButton btnCancel;
         public Register() {
              this.setTitle("Registration Form");
            JPanel panel=new JPanel();
              //apply the layout
               panel.setLayout(new GridBagLayout());
               GridBagConstraints gbCons=new GridBagConstraints();
              //place the components
              gbCons.gridx=0;
              gbCons.gridy=0;
              lblHeading=new JLabel("Please register below");
               Font f = new Font("Monospaced" , Font.BOLD , 12);
              lblHeading.setFont(f);
              Color c=new Color(0,200,0);
              lblHeading.setForeground(new Color(131,25,38));
              lblHeading.setVerticalAlignment(SwingConstants.TOP);
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(lblHeading, gbCons);
              gbCons.gridx = 0;
              gbCons.gridy = 1;
              lblUserName = new JLabel("Enter Username");
              gbCons.anchor=GridBagConstraints.WEST;
              panel.add(lblUserName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=1;
              txtUserName=new JTextField(15);
              panel.add(txtUserName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=2;
              lblUserPwd=new JLabel("Enter Password ");
              panel.add(lblUserPwd, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 2;
              txtUsrPwd = new JPasswordField(15);
              panel.add(txtUsrPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=3;
              lblCnfUserPwd=new JLabel("Confirm Password ");
              panel.add(lblCnfUserPwd, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=3;
              txtCnfUsrPwd=new JPasswordField(15);
              panel.add(txtCnfUsrPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=4;
              lblEmpId=new JLabel("Employee ID");
              panel.add(lblEmpId, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=4;
              txtEmpId=new JTextField(15);
              panel.add(txtEmpId, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=5;
              lblFrstName=new JLabel("First Name");
              panel.add(lblFrstName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=5;
              txtFrstName=new JTextField(15);
              panel.add(txtFrstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=6;
              lblLstName=new JLabel("Last Name");
              panel.add(lblLstName, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 6;
              txtLstName=new JTextField(15);
              panel.add(txtLstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=7;
              lblAge=new JLabel("Age");
              panel.add(lblAge, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=7;
              txtAge=new JTextField(3);
              panel.add(txtAge, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=8;
              lblEmail=new JLabel("Email address");
              panel.add(lblEmail, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=8;
              txtEmail=new JTextField(20);
              panel.add(txtEmail, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=9;
              lblSex=new JLabel("Sex");
              panel.add(lblSex, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy=9;
              String [] sex= {"Male", "Female"};
              listSex = new JComboBox(sex);
              listSex.setSelectedIndex(0);
              panel.add(listSex, gbCons);
              JPanel btnPanel=new JPanel();
              btnSubmit=new JButton("Submit");
              btnPanel.add(btnSubmit);
              btnSubmit.addActionListener(this); //add listener to the Submit button
              btnCancel=new JButton("Cancel");
              btnPanel.add(btnCancel);
              btnCancel.addActionListener(this); //add listener to the Cancel button
              gbCons.gridx=0;
              gbCons.gridy=10;
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(btnPanel, gbCons);
              getContentPane().add(panel);
             setDefaultCloseOperation(DISPOSE_ON_CLOSE); //get rid of this window only on closing
              setVisible(true);
              setSize(450,400);
             }//end Register()
              public void actionPerformed(ActionEvent ae) {
                   Object o = ae.getSource(); //get the source of the event
                   if(o == btnCancel)
                        this.dispose();
                   if(o == btnSubmit){
                        usrName = txtUserName.getText();
                        strUsrPwd = txtUsrPwd.getText();
                        strCnfPwd = txtCnfUsrPwd.getText();
                        frstName = txtFrstName.getText();
                        lstName = txtLstName.getText();
                        age = txtAge.getText();
                        empid = txtEmpId.getText();
                        email = txtEmail.getText();
                        sex = (String)listSex.getItemAt(0);
                        if ((usrName.length() == 0) || (strUsrPwd.length() == 0) ||
                        (strCnfPwd.length() == 0) || (frstName.length() == 0) ||
                        (lstName.length() == 0) || (age.length() == 0) ||
                        (empid.length() == 0) || (email.length() == 0))
                        JOptionPane.showMessageDialog(null,
                        "One or more entry is empty. Please fill out all entries.", "Message", JOptionPane.ERROR_MESSAGE);
                        if ((!strUsrPwd.equals(strCnfPwd))){
                             JOptionPane.showMessageDialog(null,
                             "Passwords do not match. Please try again", "Message", JOptionPane.ERROR_MESSAGE);
                        Thanks,
    Chris

    try something like this:
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ActionListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    public class About extends JDialog {
    /** Creates new form About */
    public About(JFrame parent) {
    super(parent,true);
    initComponents();
    pack();
    Rectangle parentBounds = parent.getBounds();
    Dimension size = getSize();
    // Center in the parent
    int x = Math.max(0, parentBounds.x + (parentBounds.width - size.width) / 2);
    int y = Math.max(0, parentBounds.y + (parentBounds.height - size.height) / 2);
    setLocation(new Point(x, y));
    and from the main dialog:
    new About(this).setVisible(true);

  • The gridBagLayout and the JscrollPanel

    Hi:
    1)GridBagLayout
    When I tried to use the GridBagLayout, I found that I can not change the weight of each component added in the container.
    For example,In the contentPanel of the JDialog, I added two sub panels:leftPanel and rightPanel.However the leftPanel and the rightPanel take the same width of the main dialog,I just want the leftPanel take 60% of the width of the JDialog. I have tried to definte the weightx parameter of leftPanel's GridBagContrains,but it seems not work.
    Also I found that if I add a empty Jpanel in a GridBagLayout managed JFrame,it take a small space ,after I add some compontens in the Jpanel, it is resized,
    In fact I want to control the compontent just as the size I wanted using the releative position.That's to say, even the Jpanel is empty,it should take up its own size I setted.
    So is there any ideas?
    2)The JScrollPanel.
    The leftPanel mentioned above is a JScrollPanel,and I want to show some little vector symbols in this panel,the symbols should changed when a JCombox( has been added to the main frame) changed.
    So I set the view port of the JScrollPanel to a new Jpanel(symbolListPanel:used to display the symbols, and each symbol will be draw in a SymbolPanel which extends the Jpanel and override the paint() method). I set this symbolListPanel use the GridBagLayout. I want there are three symbols displayed in each row, so I use the following codes:
    GridBagConstraints c=new GridBagConstraints();
    c.fill=both;c.weightx=c.weighty=1;
    Symbols[] s=getVectorSymbols();
    for(int i=0;i<s.length();i++) {
      c.gridx=i%3;
      c.gridy=i/3;
      symbolListPanel.add(new SymbolPanel(s),c); //
    symbolListPanel.repaint();-----------------------
    Well, when I run the application, the symbols are displayed,when I add 6 symbols, the symbolListPanel is divided to a 2(rows)x3(columns) grid,it looks well,however when I add 9 symbols, the symbolListPanel is divided to a 3(rows)x3(columns) grid,this is no problem,but the ScrollBar is never displayed,also each SymbolPanel is resized smaller to fit the size of the visible space of the leftPanel(JScrollPanel). In fact what I really need is the size SymbolPanel is never changed, when the visible  of the leftPanel is not large enough to show all the symbols, the scrollBar should display.
    BTW, in the SymbolPanel I have used the following method tried to controll the size :setPreferredSize(////);
    setMaximumSize(getPreferredSize);
    setMinimumSize(getPreferredSize) ;I think use the above three method can absolutely control the size of the Symbolpanel (then it can not be resized).
    But it seems not. why?
    3) When I change the combox, the symbols should chang. however the changed symbols can never be  visible  unless I resize the dialog.
    I thought if it is the repaint problem of the dialog. But I have call the  symbolListPanel.repaint() method,it seems that the repaint method of the sub compontent of the symbolListpanel is not called. At last I have to use the following method to make the changed symbols visible:dialog.setVisible(false);
    dialog.setVisible(true); // Set the main dialog unvisible,then set it visible, so all the compontents will be repainted,and it works.
    // However I know this is a stupid method, is there any normal ways ?
    Edited by: apachemaven on 2010-7-25 ??2:08                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Thanks, I apology for my unpolite.
    The problem is encountered in company, and our working computer is not allowed to communicate with extra hardware such as the portable hardisk.
    So it is not easy to make a simple example... It realated too many other objects which I can not simulate.
    In fact I use the Absolute Positioning to solve the problem(Though it is not a good idea).
    In this form I found another discussion about the GirdBagLayout at [thread.jspa?threadID=5446065&tstart=0|http://forums.sun.com/thread.jspa?threadID=5446065&tstart=0] ,and Sarcommand said:
    A GridBagLayout will try to give every component space according to its preferred size.If so, does it mean I should set the prefered size of each component?
    Here I write a simple test:
    import javax.swing.BorderFactory;
    import javax.swing.JPanel;
    import java.awt.Frame;
    import java.awt.BorderLayout;
    import javax.swing.JDialog;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import javax.swing.JButton;
    import java.awt.Insets;
    public class GridTest extends JDialog {
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JPanel leftPanel = null;
         private JPanel rightPanel = null;
         private JButton okButton = null;
         private JButton cancelButton = null;
         public GridTest(Frame owner) {
              super(owner);
              initialize();
         private void initialize() {
              this.setSize(495, 515);
              this.setContentPane(getJContentPane());
              this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
                   gridBagConstraints1.gridx = 1;
                   gridBagConstraints1.weightx = 0.3;
                   gridBagConstraints1.weighty = 1.0;
                   gridBagConstraints1.gridy = 0;
                   GridBagConstraints gridBagConstraints = new GridBagConstraints();
                   gridBagConstraints.gridx = 0;
                   gridBagConstraints.fill = GridBagConstraints.BOTH;
                   gridBagConstraints.weightx = 0.7;
                   gridBagConstraints.weighty = 1.0;
                   gridBagConstraints.gridy = 0;
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new GridBagLayout());
                   jContentPane.add(getLeftPanel(), gridBagConstraints);
                   jContentPane.add(getRightPanel(), gridBagConstraints1);
              return jContentPane;
         private JPanel getLeftPanel() {
              if (leftPanel == null) {
                   leftPanel = new JPanel();
                   leftPanel.setLayout(new GridBagLayout());
                   leftPanel.setBorder(BorderFactory.createTitledBorder("Left"));
              return leftPanel;
         private JPanel getRightPanel() {
              if (rightPanel == null) {
                   GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
                   gridBagConstraints2.gridx = 1;
                   gridBagConstraints2.fill = GridBagConstraints.BOTH;
                   gridBagConstraints2.insets = new Insets(0, 10, 0, 0);
                   gridBagConstraints2.gridy = 0;
                   rightPanel = new JPanel();
                   rightPanel.setLayout(new GridBagLayout());
                   rightPanel.add(getOkButton(), new GridBagConstraints());
                   rightPanel.add(getCancelButton(), gridBagConstraints2);
              return rightPanel;
         private JButton getOkButton() {
              if (okButton == null) {
                   okButton = new JButton();
                   okButton.setText("OK");
              return okButton;
         private JButton getCancelButton() {
              if (cancelButton == null) {
                   cancelButton = new JButton();
                   cancelButton.setText("Cancel");
              return cancelButton;
         public static void main(String[] args) {
              new GridTest(null).setVisible(true);
    }In this test, I want the left panel take the 70% of the widht of the whole dialog,when the dialog first set up, I found the leftpanel take only about 50%, when I resize(increase) the dialog, it seems that the leftpanel's percentge increase.
    However this is not what I want, I set the size of the whole dialog to (495,515),and I want the left take about 70%X495 always.
    So, is there any way using the GridbagLayout?

  • Please help me in creating a form using Swing.

    (I m sorry if I've posted similar post in some other thread.I am new to this forum..:))
    There are several problems which I am facing while coding a form.
    1. In the form I have one JComboBox
    of Country and other of State. Now I want it in such a way that when
    I select a country from the Country JComboBox ,the corresponding states
    automatically appears in the State JComboBox.
    2. I need to add picture frame in the 6th tab so that the picture shows up when clicked browse and open.
    3.I need to add tables in 1st and 5th tab which shows up the details through database when added through several textboxes and combo boxes.
    so please help me!
    Here's my code
    ==========================================================
    import javax.swing.JFrame;
    import javax.swing.JTabbedPane;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JCheckBox;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.Box;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Design extends JFrame
    public Design()
    super("Tenant Form");
    setLayout(new BorderLayout());
    JTabbedPane tabbedPane=new JTabbedPane(); //creating tabbed buttons
    //<--------coding for first tab--------->
    JPanel panel1=new JPanel();
    tabbedPane.addTab("Detail of Landlord",null,panel1,"first tab"); //here panel1 is created for tab1
    GridBagConstraints gbc=new GridBagConstraints();
    gbc.insets=new Insets(2,2,2,2);
    gbc.anchor=GridBagConstraints.WEST;
    JPanel jp11 = new JPanel(); //1st panel in 1st tab for top labels and buttons
    jp11.setLayout(new GridBagLayout());
    JLabel l241 = new JLabel("Name Of LandLord");
    jp11.add(l241,gbc);
    JComboBox jc01=new JComboBox();
    jc01.addItem("Select");
    jc01.addItem("Mr.");
    jc01.addItem("Mrs.");
    gbc.gridx=1;
    jp11.add(jc01,gbc);
    JTextField f01=new JTextField(10);
    gbc.gridx=2;
    jp11.add(f01,gbc);
    JLabel l251 = new JLabel("Sex");
    gbc.gridx=5;
    gbc.insets=new Insets(2,20,2,2);
    jp11.add(l251,gbc);
    JComboBox jc11=new JComboBox();
    jc11.addItem("Select");
    jc11.addItem("Male");
    jc11.addItem("Female");
    gbc.gridx=6;
    gbc.insets=new Insets(2,2,2,2);
    jp11.add(jc11,gbc);
    JLabel l261 = new JLabel("Age(Yrs)");
    gbc.gridx=8;
    gbc.insets=new Insets(2,20,2,2);
    jp11.add(l261,gbc);
    JTextField f11=new JTextField(3);
    gbc.gridx=9;
    gbc.insets=new Insets(2,2,2,2);
    jp11.add(f11,gbc);
    JLabel l271 = new JLabel("Occupation");
    gbc.gridx= 11;
    gbc.insets=new Insets(2,20,2,2);
    jp11.add(l271,gbc);
    JComboBox jc21=new JComboBox();
    jc21.addItem("Select");
    jc21.addItem("Engineer");
    jc21.addItem("Business");
    gbc.gridx=12;
    gbc.insets=new Insets(2,2,2,2);
    jp11.add(jc21,gbc);
    JButton ab1=new JButton("ADD");
    gbc.gridx=14;
    gbc.insets=new Insets(2,20,2,2);
    jp11.add(ab1,gbc);
    panel1.add(jp11);
    //<--coding for adding table with scroll pane #yet to be coded#-->
    JTable jtab1=new JTable();
    //start of p21 panel. 1st of two titledborder panels in tab 1
    JPanel jp21=new JPanel();
    jp21.setBorder(new TitledBorder("Address Of Landlord Property"));
    jp21.setLayout(new GridBagLayout());
    JLabel l11=new JLabel("Property/House/Building Address");
    gbc.gridx=0;
    gbc.gridy=0;
    jp21.add(l11,gbc);
    JTextArea ta11=new JTextArea(3,15);
    ta11.setLineWrap(true);
    int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
    JScrollPane scroll11=new JScrollPane(ta11,v,h);
    gbc.gridx=1;
    jp21.add(scroll11);
    jp21.add(ta11,gbc);
    JLabel l21=new JLabel("Land Mark");
    gbc.gridx=0;
    gbc.gridy=1;
    gbc.ipady=0;
    gbc.gridheight=1;
    jp21.add(l21,gbc);
    JTextField tf21=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=1;
    jp21.add(tf21,gbc);
    JLabel l31=new JLabel("Country");
    gbc.gridx=0;
    gbc.gridy=2;
    jp21.add(l31,gbc);
    JComboBox c11=new JComboBox();
    c11.addItem("India");
    c11.addItem("US");
    c11.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=2;
    jp21.add(c11,gbc);
    JLabel l41=new JLabel("State");
    gbc.gridx=0;
    gbc.gridy=3;
    jp21.add(l41,gbc);
    JComboBox c21=new JComboBox();
    c21.addItem("Rajasthan");
    c21.addItem("Delhi");
    c21.addItem("Maharastra");
    gbc.gridx=1;
    gbc.gridy=3;
    jp21.add(c21,gbc);
    JLabel l51=new JLabel("District");
    gbc.gridx=0;
    gbc.gridy=4;
    jp21.add(l51,gbc);
    JComboBox c31=new JComboBox();
    c31.addItem("jaipur");
    c31.addItem("ajmer");
    c31.addItem("alwar");
    gbc.gridx=1;
    gbc.gridy=4;
    jp21.add(c31,gbc);
    JLabel l61=new JLabel("City/Town");
    gbc.gridx=0;
    gbc.gridy=5;
    jp21.add(l61,gbc);
    JTextField tf31=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=5;
    jp21.add(tf31,gbc);
    JLabel l71=new JLabel("Police District");
    gbc.gridx=0;
    gbc.gridy=6;
    jp21.add(l71,gbc);
    JComboBox c41=new JComboBox();
    c41.addItem("Jaipur");
    c41.addItem("Alwar");
    c41.addItem("Ajmer");
    gbc.gridx=1;
    gbc.gridy=6;
    jp21.add(c41,gbc);
    JLabel l81=new JLabel("Police Circle");
    gbc.gridx=0;
    gbc.gridy=7;
    jp21.add(l81,gbc);
    JComboBox c51=new JComboBox();
    c51.addItem("India");
    c51.addItem("US");
    c51.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=7;
    jp21.add(c51,gbc);
    JLabel l91=new JLabel("Police station");
    gbc.gridx=0;
    gbc.gridy=8;
    jp21.add(l91,gbc);
    JComboBox c61=new JComboBox();
    c61.addItem("Bani Park");
    c61.addItem("Raja Park");
    c61.addItem("Malviya Nagar");
    gbc.gridx=1;
    gbc.gridy=8;
    jp21.add(c61,gbc);
    JLabel l101=new JLabel("Pin No.");
    gbc.gridx=0;
    gbc.gridy=9;
    jp21.add(l101,gbc);
    JTextField tf41=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=9;
    jp21.add(tf41,gbc);
    JLabel l111=new JLabel("Phone No.(R)");
    gbc.gridx=0;
    gbc.gridy=10;
    jp21.add(l111,gbc);
    JTextField tf51=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=10;
    jp21.add(tf51,gbc);
    //start of p31.2nd of two titledborder panels in tab 1
    JPanel jp31=new JPanel();
    jp31.setBorder(new TitledBorder("Address Of Landlord Office"));
    jp31.setLayout(new GridBagLayout());
    JLabel l121=new JLabel("Office Address");
    gbc.gridx=0;
    gbc.gridy=0;
    jp31.add(l121,gbc);
    JTextArea ta61=new JTextArea(3,15);
    ta61.setLineWrap(true);
    JScrollPane scroll2=new JScrollPane(ta61);
    gbc.gridx=1;
    gbc.gridy=0;
    jp31.add(ta61,gbc);
    JLabel l131=new JLabel("Country");
    gbc.gridx=0;
    gbc.gridy=1;
    gbc.gridheight=1;
    jp31.add(l131,gbc);
    JComboBox c12=new JComboBox();
    c12.addItem("India");
    c12.addItem("US");
    c12.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=1;
    jp31.add(c12,gbc);
    JLabel l141=new JLabel("State");
    gbc.gridx=0;
    gbc.gridy=2;
    jp31.add(l141,gbc);
    JComboBox c22=new JComboBox();
    c22.addItem("Rajasthan");
    c22.addItem("Delhi");
    c22.addItem("Maharastra");
    gbc.gridx=1;
    gbc.gridy=2;
    jp31.add(c22,gbc);
    JLabel l151=new JLabel("District");
    gbc.gridx=0;
    gbc.gridy=3;
    jp31.add(l151,gbc);
    JComboBox c32=new JComboBox();
    c32.addItem("jaipur");
    c32.addItem("ajmer");
    c32.addItem("alwar");
    gbc.gridx=1;
    gbc.gridy=3;
    jp31.add(c32,gbc);
    JLabel l161=new JLabel("City/Town");
    gbc.gridx=0;
    gbc.gridy=4;
    jp31.add(l161,gbc);
    JTextField tf71=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=4;
    jp31.add(tf71,gbc);
    JLabel l171=new JLabel("Police District");
    gbc.gridx=0;
    gbc.gridy=5;
    jp31.add(l171,gbc);
    JComboBox c42=new JComboBox();
    c42.addItem("Jaipur");
    c42.addItem("Alwar");
    c42.addItem("Ajmer");
    gbc.gridx=1;
    gbc.gridy=5;
    jp31.add(c42,gbc);
    JLabel l181=new JLabel("Police Circle");
    gbc.gridx=0;
    gbc.gridy=6;
    jp31.add(l181,gbc);
    JComboBox c52=new JComboBox();
    c52.addItem("India");
    c52.addItem("US");
    c52.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=6;
    jp31.add(c52,gbc);
    JLabel l191=new JLabel("Police station");
    gbc.gridx=0;
    gbc.gridy=7;
    jp31.add(l191,gbc);
    JComboBox c62=new JComboBox();
    c62.addItem("Bani Park");
    c62.addItem("Raja Park");
    c62.addItem("Malviya Nagar");
    gbc.gridx=1;
    gbc.gridy=7;
    jp31.add(c62,gbc);
    JLabel l201=new JLabel("Pin No.");
    gbc.gridx=0;
    gbc.gridy=8;
    jp31.add(l201,gbc);
    JTextField tf81=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=8;
    jp31.add(tf81,gbc);
    JLabel l211=new JLabel("Phone No.(O)");
    gbc.gridx=0;
    gbc.gridy=9;
    jp31.add(l211,gbc);
    JTextField tf91=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=9;
    jp31.add(tf91,gbc);
    JLabel l221=new JLabel("Phone No.(M)");
    gbc.gridx=0;
    gbc.gridy=10;
    gbc.gridheight=1;
    jp31.add(l221,gbc);
    JTextField tf101=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=10;
    jp31.add(tf101,gbc);
    JLabel l231=new JLabel("E-mail");
    gbc.gridx=0;
    gbc.gridy=11;
    gbc.gridheight=1;
    jp31.add(l231,gbc);
    JTextField tf111=new JTextField(15);
    gbc.gridx=1;
    gbc.gridy=11;
    jp31.add(tf111,gbc);
    JPanel jp41=new JPanel(); //adding above two panels p21 and p31 to p41 panel.
    jp41.setLayout(new BoxLayout(jp41,BoxLayout.X_AXIS));
    jp41.add(jp21);
    jp41.add(Box.createHorizontalStrut(50));
    jp41.add(jp31);
    panel1.add(jp41); //adding p41 panel to panel1
    //<--------coding for second tab--------->
    JPanel panel2 = new JPanel();
    tabbedPane.addTab("Id of Landlord",null,panel2,"second tab");
    panel2.setLayout(new FlowLayout());
    //adding radiobutton above TitledBorder panel
    JPanel jp02=new JPanel();
    JLabel l12=new JLabel("Identity Known");
    JRadioButton jrb12=new JRadioButton("Yes");
    JRadioButton jrb22=new JRadioButton("No");
    ButtonGroup bg12=new ButtonGroup();
    bg12.add(jrb12);
    bg12.add(jrb22);
    jp02.add(l12);
    jp02.add(jrb12);
    jp02.add(jrb22);
    //adding TitledBorder panel
    JPanel jp12=new JPanel();
    jp12.setBorder(new TitledBorder("Identity Detail"));
    jp12.setLayout(new GridBagLayout());
    gbc.insets=new Insets(5,5,5,5);
    JLabel l22=new JLabel("Identity Card");
    gbc.gridx=0;
    gbc.gridy=0;
    jp12.add(l22,gbc);
    JTextField jtf12=new JTextField(10);
    gbc.gridx=1;
    jp12.add(jtf12,gbc);
    JLabel l32=new JLabel("Date of Issue");
    gbc.gridx=0;
    gbc.gridy=1;
    jp12.add(l32,gbc);
    JTextField jtf22=new JTextField(10);
    gbc.insets=new Insets(5,5,5,25);
    gbc.gridx=1;
    jp12.add(jtf22,gbc);
    JLabel l42=new JLabel("Identity Number");
    gbc.insets=new Insets(5,5,5,5);
    gbc.gridx=2;
    jp12.add(l42,gbc);
    JTextField jtf32=new JTextField(10);
    gbc.gridx=3;
    jp12.add(jtf32,gbc);
    JLabel l52=new JLabel("Name Of Issuer");
    gbc.gridx=0;
    gbc.gridy=2;
    jp12.add(l52,gbc);
    JTextField jtf42=new JTextField(10);
    gbc.insets=new Insets(5,5,5,25);
    gbc.gridx=1;
    jp12.add(jtf42,gbc);
    JLabel l62= new JLabel("Place Of Issuer");
    gbc.insets=new Insets(5,5,5,5);
    gbc.gridx=2;
    jp12.add(l62,gbc);
    JTextField jtf52=new JTextField(10);
    gbc.gridx=3;
    jp12.add(jtf52,gbc);
    gbc.gridx=0;
    gbc.gridy=2;
    Box b12 =Box.createVerticalBox(); //adding both panels to vertica box and adding it to panel2
    b12.add(jp02);
    b12.add(jp12);
    panel2.add(b12);
    //<--------coding for third tab--------->
    JPanel panel3 = new JPanel();
    tabbedPane.addTab("Detail of Tenant",null,panel3,"third tab");
    //adding panel for top data
    JPanel jp13=new JPanel(); //jp13 panel for details above 3 TitledBorder panels
    jp13.setLayout(new GridBagLayout());
    JLabel l13=new JLabel("Name");
    gbc.insets=new Insets(2,2,2,2);
    gbc.gridx=0;
    gbc.gridy=0;
    jp13.add(l13,gbc);
    JComboBox c13=new JComboBox();
    c13.addItem("Select");
    c13.addItem("Mr.");
    c13.addItem("Mrs.");
    gbc.gridx=1;
    jp13.add(c13,gbc);
    JTextField jtf13=new JTextField(16);
    gbc.gridx=2;
    gbc.gridwidth=2;
    jp13.add(jtf13,gbc);
    JLabel l23=new JLabel("Sex");
    gbc.insets=new Insets(2,20,2,2);
    gbc.gridx=4;
    gbc.gridwidth=1;
    jp13.add(l23,gbc);
    JComboBox c23=new JComboBox();
    c23.addItem("Select");
    c23.addItem("Male");
    c23.addItem("Female");
    gbc.insets=new Insets(2,2,2,2);
    gbc.gridx=5;
    jp13.add(c23,gbc);
    JLabel l33=new JLabel("Father/Mother/Husband's Name");
    gbc.gridy=1;
    gbc.gridx=0;
    jp13.add(l33,gbc);
    JComboBox c33=new JComboBox();
    c33.addItem("Select");
    c33.addItem("Mr.");
    c33.addItem("Mrs.");
    gbc.gridx=1;
    jp13.add(c33,gbc);
    JComboBox c43=new JComboBox();
    c43.addItem("Select");
    c43.addItem("Mr.");
    c43.addItem("Mrs.");
    gbc.gridx=2;
    jp13.add(c43,gbc);
    JTextField jtf23=new JTextField(10);
    gbc.gridx=3;
    jp13.add(jtf23,gbc);
    JLabel l43=new JLabel("Age(Yrs)");
    gbc.insets=new Insets(2,20,2,2);
    gbc.gridx=4;
    jp13.add(l43,gbc);
    JTextField jtf33=new JTextField(3);
    gbc.insets=new Insets(2,2,2,2);
    gbc.gridx=5;
    jp13.add(jtf33,gbc);
    JLabel l53=new JLabel("Citizenship");
    gbc.gridy=2;
    gbc.gridx=0;
    jp13.add(l53,gbc);
    JComboBox c53=new JComboBox();
    c53.addItem("Select");
    c53.addItem("Indian");
    c53.addItem("Australian");
    gbc.gridx=1;
    gbc.gridwidth=2;
    jp13.add(c53,gbc);
    JLabel l63=new JLabel("Occupation");
    gbc.insets=new Insets(2,20,2,2);
    gbc.gridx=4;
    gbc.gridwidth=1;
    jp13.add(l63,gbc);
    JComboBox c63=new JComboBox();
    c63.addItem("Select");
    c63.addItem("Engineer");
    c63.addItem("Doctor");
    gbc.insets=new Insets(2,2,2,2);
    gbc.gridx=5;
    jp13.add(c63,gbc);
    panel3.add(jp13);
    JPanel jp23=new JPanel(); //first of 3 TitledBorder panels
    jp23.setBorder(new TitledBorder("Local Address"));
    jp23.setLayout(new GridBagLayout());
    JLabel l73=new JLabel("Local Address");
    gbc.gridx=0;
    gbc.gridy=0;
    jp23.add(l73,gbc);
    JTextArea ta43=new JTextArea(3,10);
    ta43.setLineWrap(true);
    JScrollPane scroll13=new JScrollPane(ta43);
    gbc.gridx=1;
    gbc.gridy=0;
    jp23.add(ta43,gbc);
    JLabel l83=new JLabel("Country");
    gbc.gridx=0;
    gbc.gridy=1;
    gbc.gridheight=1;
    jp23.add(l83,gbc);
    JComboBox c73=new JComboBox();
    c73.addItem("India");
    c73.addItem("US");
    c73.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=1;
    jp23.add(c73,gbc);
    JLabel l93=new JLabel("State");
    gbc.gridx=0;
    gbc.gridy=2;
    jp23.add(l93,gbc);
    JComboBox c83=new JComboBox();
    c83.addItem("Rajasthan");
    c83.addItem("Delhi");
    c83.addItem("Maharastra");
    gbc.gridx=1;
    gbc.gridy=2;
    jp23.add(c83,gbc);
    JLabel l103=new JLabel("District");
    gbc.gridx=0;
    gbc.gridy=3;
    jp23.add(l103,gbc);
    JComboBox c93=new JComboBox();
    c93.addItem("jaipur");
    c93.addItem("ajmer");
    c93.addItem("alwar");
    gbc.gridx=1;
    gbc.gridy=3;
    jp23.add(c93,gbc);
    JLabel l113=new JLabel("City/Town");
    gbc.gridx=0;
    gbc.gridy=4;
    jp23.add(l113,gbc);
    JTextField tf53=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=4;
    jp23.add(tf53,gbc);
    JLabel l123=new JLabel("Police District");
    gbc.gridx=0;
    gbc.gridy=5;
    jp23.add(l123,gbc);
    JComboBox c103=new JComboBox();
    c103.addItem("Jaipur");
    c103.addItem("Alwar");
    c103.addItem("Ajmer");
    gbc.gridx=1;
    gbc.gridy=5;
    jp23.add(c103,gbc);
    JLabel l133=new JLabel("Police Circle");
    gbc.gridx=0;
    gbc.gridy=6;
    jp23.add(l133,gbc);
    JComboBox c113=new JComboBox();
    c113.addItem("India");
    c113.addItem("US");
    c113.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=6;
    jp23.add(c113,gbc);
    JLabel l143=new JLabel("Police station");
    gbc.gridx=0;
    gbc.gridy=7;
    jp23.add(l143,gbc);
    JComboBox c123=new JComboBox();
    c123.addItem("Bani Park");
    c123.addItem("Raja Park");
    c123.addItem("Malviya Nagar");
    gbc.gridx=1;
    gbc.gridy=7;
    jp23.add(c123,gbc);
    JLabel l153=new JLabel("Pin No.");
    gbc.gridx=0;
    gbc.gridy=8;
    jp23.add(l153,gbc);
    JTextField tf63=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=8;
    jp23.add(tf63,gbc);
    JLabel l163=new JLabel("Phone No.(R)");
    gbc.gridx=0;
    gbc.gridy=9;
    jp23.add(l163,gbc);
    JTextField tf73=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=9;
    jp23.add(tf73,gbc);
    JLabel l173=new JLabel("E-mail");
    gbc.gridx=0;
    gbc.gridy=10;
    gbc.gridheight=1;
    jp23.add(l173,gbc);
    JTextField tf83=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=10;
    jp23.add(tf83,gbc);
    JPanel jp33=new JPanel(); //second of 3 TitledBorder panels
    jp33.setBorder(new TitledBorder("Permanent Address"));
    jp33.setLayout(new GridBagLayout());
    JLabel l183=new JLabel("Perm. Address");
    gbc.gridx=0;
    gbc.gridy=0;
    jp33.add(l183,gbc);
    JTextArea ta93=new JTextArea(5,10);
    JScrollPane scroll23=new JScrollPane(ta43);
    ta93.setLineWrap(true);
    gbc.gridx=1;
    gbc.gridy=0;
    jp33.add(ta43,gbc);
    JLabel l193=new JLabel("Country");
    gbc.gridx=0;
    gbc.gridy=1;
    gbc.gridheight=1;
    jp33.add(l193,gbc);
    JComboBox c133=new JComboBox();
    c133.addItem("India");
    c133.addItem("US");
    c133.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=1;
    jp33.add(c133,gbc);
    JLabel l203=new JLabel("State");
    gbc.gridx=0;
    gbc.gridy=2;
    jp33.add(l203,gbc);
    JComboBox c143=new JComboBox();
    c143.addItem("Rajasthan");
    c143.addItem("Delhi");
    c143.addItem("Maharastra");
    gbc.gridx=1;
    gbc.gridy=2;
    jp33.add(c143,gbc);
    JLabel l213=new JLabel("District");
    gbc.gridx=0;
    gbc.gridy=3;
    jp33.add(l213,gbc);
    JComboBox c153=new JComboBox();
    c153.addItem("jaipur");
    c153.addItem("ajmer");
    c153.addItem("alwar");
    gbc.gridx=1;
    gbc.gridy=3;
    jp33.add(c153,gbc);
    JLabel l223=new JLabel("City/Town");
    gbc.gridx=0;
    gbc.gridy=4;
    jp33.add(l223,gbc);
    JTextField tf103=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=4;
    jp33.add(tf103,gbc);
    JLabel l233=new JLabel("Police District");
    gbc.gridx=0;
    gbc.gridy=5;
    jp33.add(l233,gbc);
    JComboBox c163=new JComboBox();
    c163.addItem("Jaipur");
    c163.addItem("Alwar");
    c163.addItem("Ajmer");
    gbc.gridx=1;
    gbc.gridy=5;
    jp33.add(c163,gbc);
    JLabel l243=new JLabel("Police Circle");
    gbc.gridx=0;
    gbc.gridy=6;
    jp33.add(l243,gbc);
    JComboBox c173=new JComboBox();
    c173.addItem("India");
    c173.addItem("US");
    c173.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=6;
    jp33.add(c173,gbc);
    JLabel l253=new JLabel("Police station");
    gbc.gridx=0;
    gbc.gridy=7;
    jp33.add(l253,gbc);
    JComboBox c183=new JComboBox();
    c183.addItem("Bani Park");
    c183.addItem("Raja Park");
    c183.addItem("Malviya Nagar");
    gbc.gridx=1;
    gbc.gridy=7;
    jp33.add(c183,gbc);
    JLabel l263=new JLabel("Pin No.");
    gbc.gridx=0;
    gbc.gridy=8;
    jp33.add(l263,gbc);
    JTextField tf113=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=8;
    jp33.add(tf113,gbc);
    JLabel l273=new JLabel("Phone No.(R)");
    gbc.gridx=0;
    gbc.gridy=9;
    jp33.add(l273,gbc);
    JTextField tf123=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=9;
    jp33.add(tf123,gbc);
    JLabel l283=new JLabel("phone No.(M)");
    gbc.gridx=0;
    gbc.gridy=10;
    gbc.gridheight=1;
    jp33.add(l283,gbc);
    JTextField tf133=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=10;
    jp33.add(tf133,gbc);
    JPanel jp43=new JPanel(); //third of 3 TitledBorder panels
    jp43.setBorder(new TitledBorder("Ex-Home Address"));
    jp43.setLayout(new GridBagLayout());
    JLabel l293=new JLabel("Address");
    gbc.gridx=0;
    gbc.gridy=0;
    jp43.add(l293,gbc);
    JTextArea ta143=new JTextArea(3,10);
    ta143.setLineWrap(true);
    JScrollPane scroll33=new JScrollPane(ta143);
    gbc.gridx=1;
    gbc.gridy=0;
    jp43.add(ta143,gbc);
    JLabel l303=new JLabel("Country");
    gbc.gridx=0;
    gbc.gridy=1;
    gbc.gridheight=1;
    jp43.add(l303,gbc);
    JComboBox c193=new JComboBox();
    c193.addItem("India");
    c193.addItem("US");
    c193.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=1;
    jp43.add(c193,gbc);
    JLabel l313=new JLabel("State");
    gbc.gridx=0;
    gbc.gridy=2;
    jp43.add(l313,gbc);
    JComboBox c203=new JComboBox();
    c203.addItem("Rajasthan");
    c203.addItem("Delhi");
    c203.addItem("Maharastra");
    gbc.gridx=1;
    gbc.gridy=2;
    jp43.add(c203,gbc);
    JLabel l323=new JLabel("District");
    gbc.gridx=0;
    gbc.gridy=3;
    jp43.add(l323,gbc);
    JComboBox c213=new JComboBox();
    c213.addItem("jaipur");
    c213.addItem("ajmer");
    c213.addItem("alwar");
    gbc.gridx=1;
    gbc.gridy=3;
    jp43.add(c213,gbc);
    JLabel l333=new JLabel("City/Town");
    gbc.gridx=0;
    gbc.gridy=4;
    jp43.add(l333,gbc);
    JTextField tf153=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=4;
    jp43.add(tf153,gbc);
    JLabel l343=new JLabel("Police District");
    gbc.gridx=0;
    gbc.gridy=5;
    jp43.add(l343,gbc);
    JComboBox c223=new JComboBox();
    c223.addItem("Jaipur");
    c223.addItem("Alwar");
    c223.addItem("Ajmer");
    gbc.gridx=1;
    gbc.gridy=5;
    jp43.add(c223,gbc);
    JLabel l353=new JLabel("Police Circle");
    gbc.gridx=0;
    gbc.gridy=6;
    jp43.add(l353,gbc);
    JComboBox c233=new JComboBox();
    c233.addItem("India");
    c233.addItem("US");
    c233.addItem("Australia");
    gbc.gridx=1;
    gbc.gridy=6;
    jp43.add(c233,gbc);
    JLabel l363=new JLabel("Police station");
    gbc.gridx=0;
    gbc.gridy=7;
    jp43.add(l363,gbc);
    JComboBox c243=new JComboBox();
    c243.addItem("Bani Park");
    c243.addItem("Raja Park");
    c243.addItem("Malviya Nagar");
    gbc.gridx=1;
    gbc.gridy=7;
    jp43.add(c123,gbc);
    JLabel l373=new JLabel("Pin No.");
    gbc.gridx=0;
    gbc.gridy=8;
    jp43.add(l373,gbc);
    JTextField tf163=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=8;
    jp43.add(tf163,gbc);
    JLabel l383=new JLabel("Phone");
    gbc.gridx=0;
    gbc.gridy=9;
    jp43.add(l383,gbc);
    JTextField tf173=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=9;
    jp43.add(tf173,gbc);
    JLabel l393=new JLabel("Leaving Date");
    gbc.gridx=0;
    gbc.gridy=10;
    gbc.gridheight=1;
    jp43.add(l393,gbc);
    JTextField tf183=new JTextField(10);
    gbc.gridx=1;
    gbc.gridy=10;
    jp43.add(tf183,gbc);
    /*JCheckBox cb13=new JCheckBox("Approx");
    gbc.gridx=2;
    gbc.gridy=10;
    jp43.add(cb13);*/
    JPanel jp53=new JPanel(); //panel for addin all 3 TitledBorder panels
    jp53.setLayout(new BoxLayout(jp53,BoxLayout.X_AXIS));
    jp53.add(jp23);
    jp53.add(Box.createHorizontalStrut(30)); //giving space between each TitledBorder panel
    jp53.add(jp33);
    jp53.add(Box.createHorizontalStrut(30));
    jp53.add(jp43);
    panel3.add(jp53); //adding panel which contains all 3 TitledBorder panels to panel3
    JPanel jp63=new JPanel(); //jp63 panel for bottom data
    jp63.setBorder(new TitledBorder("Tennancy Start/End"));
    JLabel l403=new JLabel("From Date");
    jp63.add(l403);
    JTextField jtf193=new JTextField(12);
    jp63.add(jtf193);
    JCheckBox jcb23=new JCheckBox("Approx");
    jp63.add(jcb23);
    JLabel l413=new JLabel("To Date");
    jp63.add(l413);
    JTextField jtf203=new JTextField(12);
    jp63.add(jtf203);
    JCheckBox jcb33=new JCheckBox("Approx");
    jp63.add(jcb33);
    panel3.add(jp63); //adding bottom details panel jp63 to panel3
    //<--------coding for fourth tab--------->
    JPanel panel4 = new JPanel();
    tabbedPane.addTab("Id of Tenant",null,panel4,"fourth tab");
    panel4.setLayout(new FlowLayout());
    //adding radiobutton above TitledBorder panel jp14
    JPanel jp04=new JPanel();
    JLabel l14=new JLabel("Identity Known");
    JRadioButton jrb14=new JRadioButton("Yes");
    JRadioButton jrb24=new JRadioButton("No");
    ButtonGroup bg14=new ButtonGroup();
    bg14.add(jrb14);
    bg14.add(jrb24);
    jp04.add(l14);
    jp04.add(jrb14);
    jp04.add(jrb24);
    //adding TitledBorder panel jp14
    JPanel jp14=new JPanel();
    jp14.setBorder(new TitledBorder("Identity Detail"));
    jp14.setLayout(new GridBagLayout());
    gbc.insets=new Insets(5,5,5,5);
    JLabel l24=new JLabel("Identity Card");
    gbc.gridx=0;
    gbc.gridy=0;
    jp14.add(l24,gbc);
    JTextField jtf14=new JTextField(10);
    gbc.gridx=1;
    jp14.add(jtf14,gbc);
    JLabel l34=new JLabel("Date of Issue");
    gbc.gridx=0;
    gbc.gridy=1;
    jp14.add(l34,gbc);
    JTextField jtf24=new JTextField(10);
    gbc.insets=new Insets(5,5,5,25);
    gbc.gridx=1;
    jp14.add(jtf24,gbc);
    JLabel l44=new JLabel("Identity Number");
    gbc.insets=new Insets(5,5,5,5);
    gbc.gridx=2;
    jp14.add(l44,gbc);
    JTextField jtf34=new JTextField(10);
    gbc.gridx=3;
    jp14.add(jtf34,gbc);
    JLabel l54=new JLabel("Name Of Issuer");
    gbc.gridx=0;
    gbc.gridy=2;
    jp14.add(l54,gbc);
    JTextField jtf44=new JTextField(10);
    gbc.insets=new Insets(5,5,5,25);
    gbc.gridx=1;
    jp14.add(jtf44,gbc);
    JLabel l64=new JLabel("Place Of Issuer");
    gbc.insets=new Insets(5,5,5,5);
    gbc.gridx=2;
    jp14.add(l64,gbc);
    JTextField jtf54=new JTextField(10);
    gbc.gridx=3;
    jp14.add(jtf54,gbc);
    gbc.gridx=0;
    gbc.gridy=2;
    Box b14=Box.createVerticalBox(); //adding both panels to panel4 in vertical box
    b14.add(jp04);
    b14.add(jp14);
    panel4.add(b14);
    //<--------coding for fifth tab--------->
    JPanel panel5 = new JPanel();
    tabbedPane.addTab("Info Of Other Members",null,panel5,"fifth tab");
    JPanel jp15=new JPanel(); //top panel jp15 for details above add delete buttons
    jp15.setLayout(new GridBagLayout());
    JLabel l15=new JLabel("Name");
    gbc.gridx=0;
    gbc.gridy=0;
    gbc.insets=new Insets(10,10,10,10);
    jp15.add(l15,gbc);
    JTextField jtf15=new JTextField(10);
    gbc.gridx=1;
    jp15.add(jtf15,gbc);
    JLabel l25=new JLabel("Sex");
    gbc.gridx=2;
    gbc.insets=new Insets(10,80,10,10);
    jp15.add(l25,gbc);
    JComboBox jcb15=new JComboBox();
    jcb15.addItem("Male");
    jcb15.addItem("Female");
    gbc.gridx=3;
    gbc.insets=new Insets(10,10,10,10);
    jp15.add(jcb15,gbc);
    JLabel l35=new JLabel("Relation");
    gbc.gridx=0;
    gbc.gridy=1;
    gbc.insets=new Insets(10,10,40,10);
    jp15.add(l35,gbc);
    JTextField jtf25=new JTextField(10);
    gbc.gridx=1;
    jp15.add(jtf25,gbc);
    JLabel l45=new JLabel("Age");
    gbc.gridx=2;
    gbc.insets=new Insets(10,80,40,10);
    jp15.add(l45,gbc);
    JTextField jtf35 =new JTextField(10);
    gbc.gridx=3;
    gbc.insets=new Insets(10,10,40,10);
    jp15.add(jtf35,gbc);
    JPanel jp25=new JPanel(); //middle panel jp25 for adding "add" and "delete" buttons
    JButton jb15=new JButton("Add");
    JButton jb25=new JButton("Delete");
    jp25.add(jb15);
    jp25.add(jb25);
    //adding table #yet to be coded#
    Box b15=Box.createVerticalBox();
    b15.add(jp15);
    b15.add(jp25);
    panel5.add(b15); //adding jp15 and jp25 to panel5 in vertical box
    //<--------coding for sixth tab--------->
    JPanel panel6 = new JPanel();
    tabbedPane.addTab("Related To Office",null,panel6,"sixth tab");
    panel6.setLayout(new GridBagLayout());
    //adding 4 labels and textfields vertically
    JLabel l16=new JLabel("Investigation Officer");
    gbc.gridx=0;
    gbc.gridy=0;
    gbc.insets=new Insets(40,40,20,10);
    panel6.add(l16,gbc);
    JTextField jtf16 =new JTextField(10);
    gbc.gridx=1;
    gbc.insets=new Insets(40,20,20,40);
    panel6.add(jtf16,gbc);
    JLabel l26=new JLabel("S.No.");
    gbc.gridx=0;
    gbc.gridy=1;
    gbc.insets=new Insets(10,40,20,10);
    panel6.add(l26,gbc);
    JTextField jtf26 =new JTextField(10);
    gbc.gridx=1;
    gbc.insets=new Insets(10,20,20,40);
    panel6.add(jtf26,gbc);
    JLabel l36=new JLabel("Page No.");
    gbc.gridx=0;
    gbc.gridy=2;
    gbc.insets=new Insets(10,40,20,10);
    panel6.add(l36,gbc);
    JTextField jtf36 =new JTextField(10);
    gbc.gridx=1;
    gbc.insets=new Insets(10,20,20,40);
    panel6.add(jtf36,gbc);
    JLabel l46=new JLabel("Date");
    gbc.gridx=0;
    gbc.gridy=3;
    gbc.insets=new Insets(10,40,20,10);
    panel6.add(l46,gbc);
    JTextField jtf46=new JTextField(10);
    gbc.gridx=1;
    gbc.insets=new Insets(10,20,20,40);
    panel6.add(jtf46,gbc);
    /* Canvas c16=new Canvas(); //creating a rectangle frame for adding image
    Image i16=c.createImage(200,100);
    gbc.gridx=2;
    gbc.gridy=0;
    gbc.insets=new Insets(40,20,20,40);
    gbc.gridheight=3;
    panel6.add(i16,gbc);*/
    JButton jb16=new JButton("Browse"); //adding "browse" and "save" buttons
    gbc.insets=new Insets(10,20,20,40);
    gbc.gridy=3;
    panel6.add(jb16,gbc);
    JButton jb26=new JButton("Save");
    gbc.insets=new Insets(50,20,20,40);
    gbc.gridy=4;
    panel6.add(jb26,gbc);
    //<-------end of sixth tab------->
    add(tabbedPane);
    //lower panel for cancel button
    JPanel jp1=new JPanel();
    jp1.setLayout(new FlowLayout(FlowLayout.RIGHT));
    JButton can=new JButton("Cancel"); //initialising cancel button
    jp1.add(can);
    add(jp1,BorderLayout.SOUTH);
    class Blistener implements ActionListener // class for action listener
    public void actionPerformed(ActionEvent ae)
    Object obj=ae.getSource();
    try{
    if(obj == can) //condition for cancel button
    System.exit(0);
    }catch(Exception e)
    {System.out.println(e);
    public class Project
    public static void main(String args[]) //main method for the program
    Design tabbedwin= new Design();
    tabbedwin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    tabbedwin.setSize(900,700);
    tab

    First things first. Next time please use the code formating tags when posting your code.
    Secondly, we cant help you do your entire project or more specifically we cant do it for you. We can probably help you with one section at a time.
    Thirdly, do not post your entire code. Create a Short, Self Contained, Compilable Example (SSCCE) that demonstrates the problem section, and that is independent of any third party libraries and can compiled instantly and tested.
    Now, lets see if we can answer one problem here.
    Ques 1. In the form I have one JComboBox of Country and other of State. Now I want it in such a way that whenI select a country from the Country JComboBox ,the corresponding states automatically appears in the State JComboBox.
    Ans 1: Use an ItemListener or an ActionListener (javax.swing.event) for this. Once an item is selected, the event will be fired and then you populate your ComboBox with the requried data.
    Ques 2. I need to add picture frame in the 6th tab so that the picture shows up when clicked browse and open.
    Ans 2: You haven't created the JButton for the browse action, nor have you created the JLabel to show the picture in. Create the JButton, then the JLabel, attach an ActionListener to the button to listen for the button click, open a JFileChooser, select the image file, create an ImageIcon and pass the File object returned to it. Then call the JLabel.setIcon( the ImageIcon) to display the picture. You'll have to store the picture File information some where so can reference it when saving.
    Ques 3.I need to add tables in 1st and 5th tab which shows up the details through database when added through several textboxes and combo boxes.
    You need to do some reading. The Swing Tutorial has everything you need, from How to use Tables to How to connect to databases. There are also some examples in your JDK installation folder, ie, jdk/demos/jfc/tableExample. Here is the link to the swing tutorial on how to use Tables: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html. You find other useful links there.
    ICE

  • Calling A Form From Another One

    hi i am trying to call a form that i have constructed before named "MENU_form" from the "LOGIN" form. I have imported the "MENU_form" but i can't use it as an another frame inside the LOGIN form.
    At Login Form, after the user enters the correct usrname and password, i want to redirect the form to Menu_Form. Need your help...
    Also here is the code...
    package project;
    import java.sql.Connection;
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import project.IConnect;
    import project.MENU_form;
    * @author buro
    public class login extends javax.swing.JFrame {
    /** Creates new form login */
    public login() {
    initComponents();
    private void initializeComponent()
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jButton2 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jLabel1.setText("KULLANICI G\u0130R\u0130S\u0130");
    jButton1.setText("G\u0130R\u0130S");
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    jButton1MouseClicked(evt);
    jLabel2.setText("Kullan\u0131c\u0131 Ad\u0131");
    jLabel3.setText("\u015eifre");
    jLabel4.setForeground(new java.awt.Color(255, 0, 51));
    jLabel4.setText("a");
    jButton2.setText("\u00c7IKI\u015e");
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    jButton2MouseClicked(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(20, 20, 20)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(24, 24, 24)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)))
    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 146, Short.MAX_VALUE)
    .addComponent(jButton2)
    .addGap(23, 23, 23))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(27, 27, 27)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel2))
    .addGap(20, 20, 20)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel3))
    .addGap(15, 15, 15)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE))
    .addGap(20, 20, 20)
    .addComponent(jLabel4)
    .addContainerGap(281, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                     
    // TODO add your handling code here:
    System.out.println("User exited application");
    System.exit(3);
    private void methodName22()
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                     
    // TODO add your handling code here:
    String nul="";
    if( (nul.equals(jTextField1.getText())) || (nul.equals(jTextField2.getText())) )
    jLabel4.setText("Bos Alanlar? Doldurunuz!!!");
    else
    String usr= jTextField1.getText();
    String pwd= jTextField2.getText();
    try {  
    Connect baglan= new Connect();
    Connection connection=baglan.Connect();
    Statement stm = connection.createStatement();
    String sql;
    //SELECT
    ResultSet rs=stm.executeQuery("select * from login where username='"+usr+"' and passwor='"+pwd+"'");
    if(rs.next()==true)
    jLabel4.setText("Success!!!");
    this.setVisible(false);
    // ************* HERE I want to call "MENU_form". HOW ??????
    else
    jLabel4.setText("fault!!!");
    } catch(Exception e)
    {  e.printStackTrace(); }//end of catch
    }//end of else
    private void initialize()
    jLabel4 = new JLabel();
    jLabel4.setText("");
    public static void main(String args[])
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new login().setVisible(true);
    //initialize();
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration

    Hi,
    this is the way i am showing a password dialog: i derive this class from JDialog (not from JFrame).
    In its constructor, i make it a modal dialog.
    public class PasswordDlg extends JDialog {
    private boolean ok; // this flag should indicate whether the User has pressed OK or CANCEL
                                 // i omit the code for OK and CANCEL here...
    public PasswordDlg(JFrame owner, String DisplayText) {
         super(owner,DisplayText,true); // true -> modal!
      public boolean showDialog()
        { ok = false;
          show();
          return ok;}
    } Now in my main frame (this is derived from JFrame) in its constructor, i make an instance of my PasswordDlg, call its showDialog method, ask the password from the dialog (i have omitted this method), and then i decide, whether the program should go on or whether i call System.exit(0) in case the password is wrong.
    regards
    BugBunny

  • File Dialog not appearing in web form after Note:74140.1

    Hello, I have implemented the source given in Note:74140.1 to replace the get_file_name function that displays the file dialog box. However I still am not able to see the dialog that the JavaBean should display. I am relativly new at linking JavaBeans with forms, so there might be something that I am missing.
    I have created the class files for FDialog and FDialogPJC and put them in an ear file. I have also modified the fiels server.xml and default-web-site.xml to include the ear file. The respective code for a button has been added to the button trigger in the form, as well as the code for the JavaBean.
    So far this has been unsuccessful. If you have a suggestion, your help is much appreciated.
    Justin.

    the problem is that when I type JDialogPJC in the implementation class property of the java bean when working in JDeveloper, it cannot locate the java class file JDialogPJC.class. This happens when I put both the JDialogPJC and JDialog classes in the jar file and put the jar file in the forms90/java directory.
    However, if I just put both class files (not contained in a jar file) in the forms90/java directory, and I specify the JDialogPJC in the implementation class property of the java bean, it works fine.
    I would like to be able to use the jar file instead of a whole load of class files sitting in the directory.

  • Problem with a template method in JDialog

    Hi friends,
    I'm experiencing a problem with JDialog. I have a base abstract class ChooseLocationDialog<E> to let a client choose a location for database. This is an abstract class with two abstract methods:
    protected abstract E prepareLocation();
    protected abstract JPanel prepareForm();Method prepareForm is used in the constructor of ChooseLocationDialog to get a JPanel and add it to content pane.
    Method prepareLocation is used to prepare location of a database. I have to options - local file and networking.
    There are two subclasses ChooseRemoteLocationDialog and ChooseLocalFileDialog.
    When I start a local version, ChooseLocalFileDialog with one input field for local file, everything works fine and my local client version starts execution.
    The problem arises when I start a network version of my client. Dialog appears and I can enter host and port into the input fields. But when I click Select, I get NullPointerException. During debugging I noticed that the values I entered into these fields ("localhost" for host and "10999" for port) were not set for corresponding JTextFields and when my code executes getText() method for these input fields it returns empty strings. This happens only for one of these dialogs - for the ChooseRemoteLocationDialog.
    The code for ChooseLocationDialog class:
    public abstract class ChooseLocationDialog<E> extends JDialog {
         private E databaseLocation;
         private static final long serialVersionUID = -1630416811077468527L;
         public ChooseLocationDialog() {
              setTitle("Choose database location");
              setAlwaysOnTop(true);
              setModal(true);
              Container container = getContentPane();
              JPanel mainPanel = new JPanel();
              //retrieving a form of a concrete implementation
              JPanel formPanel = prepareForm();
              mainPanel.add(formPanel, BorderLayout.CENTER);
              JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
              JButton okButton = new JButton(new SelectLocationAction());
              JButton cancelButton = new JButton(new CancelSelectAction());
              buttonPanel.add(okButton);
              buttonPanel.add(cancelButton);
              mainPanel.add(buttonPanel, BorderLayout.SOUTH);
              container.add(mainPanel);
              pack();
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              Dimension screenSize = toolkit.getScreenSize();
              int x = (screenSize.width - getWidth()) / 2;
              int y = (screenSize.height - getHeight()) / 2;
              setLocation(x, y);
              addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        super.windowClosing(e);
                        System.exit(0);
         public E getDatabaseLocation() {
                return databaseLocation;
         protected abstract E prepareLocation();
         protected abstract JPanel prepareForm();
          * Action for selecting location.
          * @author spyboost
         private class SelectLocationAction extends AbstractAction {
              private static final long serialVersionUID = 6242940810223013690L;
              public SelectLocationAction() {
                   putValue(Action.NAME, "Select");
              @Override
              public void actionPerformed(ActionEvent e) {
                   databaseLocation = prepareLocation();
                   setVisible(false);
         private class CancelSelectAction extends AbstractAction {
              private static final long serialVersionUID = -1025433106273231228L;
              public CancelSelectAction() {
                   putValue(Action.NAME, "Cancel");
              @Override
              public void actionPerformed(ActionEvent e) {
                   System.exit(0);
    }Code for ChooseLocalFileDialog
    public class ChooseLocalFileDialog extends ChooseLocationDialog<String> {
         private JTextField fileTextField;
         private static final long serialVersionUID = 2232230394481975840L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel();
              panel.add(new JLabel("File"));
              fileTextField = new JTextField(15);
              panel.add(fileTextField);
              return panel;
         @Override
         protected String prepareLocation() {
              String location = fileTextField.getText();
              return location;
    }Code for ChooseRemoteLocationDialog
    public class ChooseRemoteLocationDialog extends
              ChooseLocationDialog<RemoteLocation> {
         private JTextField hostField;
         private JTextField portField;
         private static final long serialVersionUID = -2282249521568378092L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel(new GridLayout(2, 2));
              panel.add(new JLabel("Host"));
              hostField = new JTextField(15);
              panel.add(hostField);
              panel.add(new JLabel("Port"));
              portField = new JTextField(15);
              panel.add(portField);
              return panel;
         @Override
         protected RemoteLocation prepareLocation() {
              String host = hostField.getText();
              int port = 0;
              try {
                   String portText = portField.getText();
                   port = Integer.getInteger(portText);
              } catch (NumberFormatException e) {
                   e.printStackTrace();
              RemoteLocation location = new RemoteLocation(host, port);
              return location;
    }Code for RemoteLocation:
    public class RemoteLocation {
         private String host;
         private int port;
         public RemoteLocation() {
              super();
         public RemoteLocation(String host, int port) {
              super();
              this.host = host;
              this.port = port;
         public String getHost() {
              return host;
         public void setHost(String host) {
              this.host = host;
         public int getPort() {
              return port;
         public void setPort(int port) {
              this.port = port;
    }Code snippet for dialog usage in local client implementation:
    final ChooseLocationDialog<String> dialog = new ChooseLocalFileDialog();
    dialog.setVisible(true);
    location = dialog.getDatabaseLocation();
    String filePath = location;Code snippet for dialog usage in network client implementation:
    final ChooseLocationDialog<RemoteLocation> dialog = new ChooseRemoteLocationDialog();
    dialog.setVisible(true);
    RemoteLocation location = dialog.getDatabaseLocation();Exception that I'm getting:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:42)
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:1)
         at suncertify.client.gui.dialog.ChooseLocationDialog$SelectLocationAction.actionPerformed(ChooseLocationDialog.java:87)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
         at java.awt.Component.processMouseEvent(Component.java:6134)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
         at java.awt.Component.processEvent(Component.java:5899)
         at java.awt.Container.processEvent(Container.java:2023)
         at java.awt.Component.dispatchEventImpl(Component.java:4501)
         at java.awt.Container.dispatchEventImpl(Container.java:2081)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4301)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3895)
         at java.awt.Container.dispatchEventImpl(Container.java:2067)
         at java.awt.Window.dispatchEventImpl(Window.java:2458)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178)
         at java.awt.Dialog$1.run(Dialog.java:1046)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Client VM (build 1.6.0-b09, mixed mode, sharing)
    OS: Ubuntu 8.04
    Appreciate any help.
    Thanks.
    Edited by: spyboost on Jul 24, 2008 5:38 PM

    What a silly error! I have to call Integer.parseInt instead of getInt. Integer.getInt tries to find a system property. A small misprint, but a huge amount of time to debug. I always use parseInt method and couldn't even notice that silly misprint. Sometimes it's useful to see the trees instead of whole forest :)
    It works perfectly. Sorry for disturbing.

  • Problem with the GridBagLayout Manager

    Hello i am new to Java Swing and i am facing a problem with the GridBagLayout layout manager . the code in question is attached. First compile and run the code. It will execute w/o probs . Then go to the "Console" tab. There the diff components (6 buttons and 1 text area) are haphazardly arranged where as all measures where taken to prevent it in the code. The GridBagLayout manager for this tab is not working properly please help.
    The code in question:-
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MainForm extends JFrame{
         JTabbedPane jtp = new JTabbedPane();
         Container generalContainer; // container for the general pane
         Container consoleContainer; // container for the console pane
         GridBagLayout consoleLayout = new GridBagLayout(); // GridBagLayout for the console
         GridBagConstraints consoleConstraints;// GridBagConstraints for the console
         public MainForm()
              super("Welcome to Grey Griffin -- Network Simulator");
              setSize(700,600);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JPanel generalPane = new JPanel();
              generalPane.setLayout(new BoxLayout(generalPane, BoxLayout.Y_AXIS));
              JPanel consolePane = new JPanel();
              consolePane.setLayout(new BoxLayout(consolePane, BoxLayout.Y_AXIS));
              JPanel designPane = new JPanel();
              designPane.setLayout(new BoxLayout(designPane, BoxLayout.Y_AXIS));
              JPanel outputPane = new JPanel();
              outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
              //Setting up Layout for all the tabs
               //for general tab
               FlowLayout layout= new FlowLayout();
               generalContainer = generalPane;
               layout.setAlignment(FlowLayout.CENTER);
               generalContainer.setLayout( layout );
               //for  console tab
               consoleContainer = consolePane;
               consoleConstraints = new GridBagConstraints();
               // *******Finished********
              //********** All buttons text areas are declared here**********
                //*******for the general tab**********
              JButton generalCreate = new JButton("Create a New Network");
              JButton generalOpen = new JButton("Open an Existing Network");
              JButton generalSave = new JButton("Save the Network");
              JButton generalSaveAs = new JButton("Save As..........");
              JButton generalExit = new JButton("Exit");
              //******END******
             //*******for the console tab
                 //text area          
              JTextArea consoleCode = new JTextArea();
              consoleCode.setEditable(true);
              consoleCode.setMaximumSize(new Dimension(700,400));
              consoleCode.setAlignmentX(0.0f);
                   //text area complete
                 //*******for the Console tab**********
              JButton consoleCompile = new JButton("Compile Code");
              JButton consoleSimulate = new JButton("Simulate Code");
              JButton consoleReset = new JButton("Reset");
              JButton consoleOpen = new JButton("Open script files");
              JButton consoleSave = new JButton("Save script files");
              JButton consoleConvert = new JButton("Convert Script files to graphical form");
              //***************END****************
         //Adding buttons and text areas to there respective tabs
              // for the general tab
              generalContainer.add(generalCreate);
              generalContainer.add(generalOpen);
              generalContainer.add(generalSave);
              generalContainer.add(generalSaveAs);
             generalContainer.add(generalExit);
             //****END****
              // for the console tab          
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleOpen,0,0,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleSave,1,1,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleConvert,1,2,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleCode,1,0,3,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleCompile,2,0,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleSimulate,2,1,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleReset,2,2,1,1);
              //****END****
              // adding the tabs
              jtp.addTab("General",null,generalPane,"Choose General Options");
              jtp.addTab("Design",null,designPane,"Design your own network!!");
              jtp.addTab("Console",null,consolePane,"Type commands in console for designing");
              jtp.addTab("Output",null,outputPane,"View output");
              getContentPane().add(jtp, BorderLayout.CENTER);
              //****END****
         //This method is used to ad the buttons in the GridBagLayout of the Console tab
         private void addComp( Component c,int row,int column,int width,int height)
            // set gridx and gridy
            consoleConstraints.gridx=column;
            consoleConstraints.gridy=row;
            //set gridwidth and grid height
            consoleConstraints.gridwidth=width;
            consoleConstraints.gridheight=height;
            //set constraints
            consoleLayout.setConstraints(c,consoleConstraints);
            consoleContainer.add(c);     
         class TabManager implements ItemListener
              Component tab;
              public TabManager(Component tabToManage)
                   tab = tabToManage;
         public void itemStateChanged(ItemEvent ie)
              int index=jtp.indexOfComponent(tab);
             if (index!=-1)
                  jtp.setEnabledAt(index,ie.getStateChange()== ItemEvent.SELECTED);
             MainForm.this.repaint();
    public static void main(String args[])
         MainForm form = new MainForm();
         form.setVisible(true);
    }

    Thanks for the suggestions. I did away with the GridBagLayout Altogether :-D
    and put all the buttons in a seperate JPanel and added that JPanel into the Console tabs container which was using a BorderLayout this time. Take a look
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MainForm extends JFrame{
         JTabbedPane jtp = new JTabbedPane();
         public MainForm()
              super("Welcome to Grey Griffin -- Network Simulator");
              setSize(800,600);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JPanel generalPane = new JPanel();
              generalPane.setLayout(new BoxLayout(generalPane, BoxLayout.Y_AXIS));
              JPanel consolePane = new JPanel();
              consolePane.setLayout(new BoxLayout(consolePane, BoxLayout.Y_AXIS));
              JPanel designPane = new JPanel();
              designPane.setLayout(new BoxLayout(designPane, BoxLayout.Y_AXIS));
              JPanel outputPane = new JPanel();
              outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
              //Setting up Layout for all the tabs
              //**for the general tab
               Container generalContainer;
               FlowLayout layoutGeneral= new FlowLayout();
               generalContainer = generalPane;
               layoutGeneral.setAlignment(FlowLayout.CENTER);
               generalContainer.setLayout( layoutGeneral );
               //**for the console tab
                Container consoleContainer;
                consoleContainer = consolePane;
                consoleContainer.setLayout(new BorderLayout() );
               //Creating buttonpanel for adding the buttons
                JPanel buttonPanel1 = new JPanel();
                buttonPanel1.setLayout(new GridLayout(1,3));
                JPanel buttonPanel2 = new JPanel();
                buttonPanel2.setLayout(new GridLayout(1,3));
              // All buttons / text areas / images are declared here
              //**Buttons for the general tab**//
              JButton generalCreate = new JButton("Create a New Network");
              JButton generalOpen = new JButton("Open an Existing Network");
              JButton generalSave = new JButton("Save the Network");
              JButton generalSaveAs = new JButton("Save As..........");
              JButton generalExit = new JButton("Exit");
              //declaring the buttons
              JButton consoleCompile = new JButton("Compile");
              JButton consoleRun = new JButton("Run");
              JButton consoleReset = new JButton("Reset");
              JButton consoleOpen = new JButton("Open script files");
              JButton consoleSave = new JButton("Save script files");
              JButton consoleConvert = new JButton("Convert Script files to graphical form");
              //declares the textarea where the code is written
              JTextArea consoleCode = new JTextArea();
              consoleCode.setEditable(true);
              consoleCode.setMaximumSize(new Dimension(500,600));
              consoleCode.setAlignmentX(0.0f);
              //Adding buttons and text areas to there respective tabs     
              //**Buttons and text pads for the general tab**
                   generalContainer.add(generalCreate);
              generalContainer.add(generalOpen);
              generalContainer.add(generalSave);
              generalContainer.add(generalSaveAs);
                 generalContainer.add(generalExit);
              //adding buttons to the button panel 1
              buttonPanel1.add(consoleOpen);
              buttonPanel1.add(consoleSave);
              buttonPanel1.add(consoleConvert);
              //adding buttons to the button panel2          
              buttonPanel2.add(consoleRun);
              buttonPanel2.add(consoleReset);
              buttonPanel2.add(consoleCompile);
              //adding button panels and textarea
              consoleContainer.add(buttonPanel1,BorderLayout.NORTH);
              consoleContainer.add(consoleCode,BorderLayout.CENTER);
              consoleContainer.add(new JScrollPane(consoleCode));
              consoleContainer.add(buttonPanel2,BorderLayout.SOUTH);
              //adding the tabs          
              jtp.addTab("General",null,generalPane,"Choose General Options");
              jtp.addTab("Design",null,designPane,"Design your own network!!");
              jtp.addTab("Console",null,consolePane,"Type commands in console for designing");
              jtp.addTab("Output",null,outputPane,"View output");
              getContentPane().add(jtp, BorderLayout.CENTER);
         class TabManager implements ItemListener
              Component tab;
              public TabManager(Component tabToManage)
                   tab = tabToManage;
         public void itemStateChanged(ItemEvent ie)
              int index=jtp.indexOfComponent(tab);
             if (index!=-1)
                  jtp.setEnabledAt(index,ie.getStateChange()== ItemEvent.SELECTED);
             MainForm.this.repaint();
    public static void main(String args[])
         MainForm form = new MainForm();
         form.setVisible(true);
    }

  • Set minimum size for GridBagLayout

    Hi all,
    I have a dialog which using GridBagLayout. I spent quite a lot of time to test, but still got the following problems. Could anyone give me some solutions?
    1. How do I set the dialog to have a minimum size ?
    Since the dialog is sizeable, so I have to make this limitation to prevent the dialog being too small .
    I tried the following code:
            this.getContentPane().setMinimumSize(new Dimension(686,520));
            this.setMinimumSize(new Dimension(686,520));but it's still not work... , I can still resize it too small.. any other way ?
    2. How do I set its default size when dialog pop up?
    I don't know why the dialog always auto popup in maximum size.
    I have tried to use this.setSize(new Dimension(686, 536)); inside jbInit() function, but still not work...
    Please help ... Thanks a lot.

    Why dont you try this.setResizable(false);?
    Anyway I have given a sample program here using Gridbag layout and this dialog cannot be resized.
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class SunExample28 extends JDialog {
         public SunExample28() {
              setTitle("JDialog with Fixed size");
              JLabel nameLbl = new JLabel("Name:");
              JLabel ageLbl = new JLabel("Age:");
              JTextField nameFld = new JTextField(10);
              JTextField ageFld = new JTextField(10);
              GridBagConstraints gbc = new GridBagConstraints();
              Insets in = new Insets(5,5,5,5);
              JPanel compPanel = new JPanel(new GridBagLayout());
              gbc.gridx = 0;
              gbc.gridy = 0;
              compPanel.add(nameLbl,gbc);
              gbc.insets = in;
              gbc.gridx = 1;
              gbc.gridy = 0;
              compPanel.add(nameFld, gbc);
              gbc.insets = in;
              gbc.gridx = 0;
              gbc.gridy = 1;
              compPanel.add(ageLbl, gbc);
              gbc.insets = in;
              gbc.gridx = 1;
              gbc.gridy = 1;
              compPanel.add(ageFld, gbc);
              JButton okBtn = new JButton("OK");
              JButton cancelBtn = new JButton("Cancel");
              JPanel btnPanel = new JPanel();
              btnPanel.add(okBtn);
              btnPanel.add(cancelBtn);
              getContentPane().add(compPanel, BorderLayout.CENTER);
              getContentPane().add(btnPanel, BorderLayout.PAGE_END);
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              setSize(500,300);
              setResizable(false);
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              new SunExample28().setVisible(true);
    }

Maybe you are looking for

  • VBA XML Ribbon now rendering in Project Client 2013 (version: 15.0.4569.15.04)

    Hi, What I’m trying to do is to add XML ribbon to Project Client 2013 using VBA code. I have a method in my VBA project (mpp file) under “ThisProject”. When this project is open, it passes the xml ribbon to ActiveProject.SetCustomUI (“My XML ribbon c

  • N95 Wifi WPA connection problem

    I recently bought the Nokia N95 and everything is working except the wifi WPA part. I DL the latest firmware (v20.0.015) but that didn't help. Everytime i connect with my home wifi lan it asks for a password. It doesn't matter what password i try it

  • CD importing errors:

    Sorry for cross posting, but I accidentally put this in the Mac forum when it should have clearly been here. I'm hoping that someone has an answer to my little problem. Here's the post: "I have a certain reoccurring problem with a few CDs when I try

  • Human Workflow Notifications Emails - Turn these Off?

    All, We have built an application that uses Oracle BPM and sginificant number of Human Tasks. We have also configured the Email notifications to allow SOA to send emails through our generic fault framework. The issue we have is as a result of this, w

  • Finding and removing uneeded jars

    Hi, I have inherited a fairly large but badly designed and coded web app at my company and am trying to determine if all the jars under WEB-INF/lib are in fact needed by the app. I am betting many are not but I can't tell for sure. Can anyone please