Adding JTextField to JLabel

Hi All,
I already have a JButton and JLabel on the Frame.So when i press the button JTextField need to be added to JLabel.
JLabel.setLabelFor(JComponent c).Does this method work or is there any other way in doing this.??
Thanks in advance for all.
regards,
Viswanadh

Hi Cam,
I am posting now.Is it correct then its ok or else tell me how to do it,because i was not 100% sure of posting SSCCE.
public class VNVGenerator extends JFrame {
static public Hashtable<String, Integer> buffer_no_of_input_params = new Hashtable<String, Integer>();
static public Hashtable<String, Integer> buffer_return_type = new Hashtable<String, Integer>();
static public JComboBox functionbox=new JComboBox();
static Font style=new Font("Palatino Linotype", Font.BOLD | Font.PLAIN,14);
public JPanel settingsPanel;
public JLabel typeLabel,inparam,outparam,returnparam;
public JFrame vnvframe;
static{
           try{
                               File file = null;
                                 FileReader freader = null;
                                 LineNumberReader lnreader = null;
                      String parttoken[]=new String[4];                    
                               String nameidentitiy;
                         StringTokenizer tokenizer;
                               JFileChooser filetypechooser = new JFileChooser();
                                String currentdir = System.getProperty("user.dir");               
                            File dir = new File(currentdir);
            if (dir.isDirectory()) {
                                    File[] files = dir.listFiles();
                        for(int i = 0; i < files.length; i++)
                           nameidentitiy=filetypechooser.getTypeDescription(files);
          if((files[i].getName().toUpperCase().endsWith("TXT"))&&(files[i].getName().toLowerCase().startsWith("tmtv")))
                              freader = new FileReader(files[i].getName());
lnreader = new LineNumberReader(freader);
String line = "";
while ((line = lnreader.readLine()) != null)
tokenizer=new StringTokenizer(line);
                                             int tokens=tokenizer.countTokens();                    
                                             int nooftokens=0;
while ((nooftokens<tokens)&&(tokenizer.hasMoreTokens()))
                                                  parttoken[nooftokens]=tokenizer.nextToken();                                   
                                                       nooftokens++;
               functionbox.addItem(parttoken[1].toString());
               buffer_no_of_input_params.put(parttoken[1],new Integer(parttoken[2]));
               buffer_return_type.put(parttoken[1],new Integer(parttoken[3]));
               Integer value = (Integer) buffer_no_of_input_params.get(parttoken[1]);
               Integer returnvalue = (Integer) buffer_return_type.get(parttoken[1]);
                              catch(Exception e){
     e.getMessage();
public VNVGenerator(){
vnvframe=new JFrame("VNVAPI Test Window");
Border apiborder = BorderFactory.createLineBorder(Color.RED,1);               
          settingsPanel= new JPanel();
          settingsPanel.setBorder(
          BorderFactory.createTitledBorder(apiborder,"VNVAPI Manual Test Settings",TitledBorder.LEFT,TitledBorder.TOP,style,new Color(142,142,56)));
functionbox.addActionListener(new OnCallingRequiredFunction());               
inparam=new JLabel("In Param:");
settingsPanel.add(inparam);
vnvframe.getContentPane().add(settingsPanel, BorderLayout.CENTER);
class OnCallingRequiredFunction implements ActionListener{
     final JSeparator separator = new JSeparator();
public void actionPerformed(ActionEvent selectEvent){
          JComboBox source = (JComboBox) selectEvent.getSource();
                         Object item= source.getSelectedItem();
                         item=item.toString().trim();
OnFetchingValueFromHashTable(item);
     public void OnFetchingValueFromHashTable(Object key){
          OnCreatingInputParametersTextFieldComponent(buffer_no_of_input_params.get(key));
     public void OnCreatingInputParametersTextFieldComponents(int inputparameters)
     GridBagConstraints constraints=new GridBagConstraints();
final int no = new Integer(inputparameters);
System.out.println("No of Parameters are:"+no);
for (int i = 0; i < no; i++) {
               inparam.add(new JTextField(2),constraints.HORIZONTAL );
settingsPanel.revalidate();// you may comment this out because next statement is pack()
public static void main(String args[])
          try {
               UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
               new VNVGenerator();
               }catch(Exception e){
               e.getMessage();
regards,
Viswanadh

Similar Messages

  • Adding JTextFields and JLabels on a window/panel

    Hi everyone,
    i am creating a program that reads information from an XML, it can read the XML without any problem. my problem is i have got an Element viz: serviceOrderElement, and i store its values inside a Combobox. that serviceOrderElement has parameters
    E.g:
    <ServiceOrder name="MPABX_LIST_VPN_MEMBER" description="List enterprise members">
         <parameter>GRPID</parameter>
         <parameter>DEPT</parameter>
         <parameter>POVERDUE</parameter>
         <parameter>STARTDATE</parameter>
         <parameter>ENDDATE</parameter>
         <parameter>ORDER1</parameter>
         <parameter>ORDERTYPE1</parameter>
         <parameter>ORDER2</parameter>
         <parameter>ORDERTYPE2</parameter>
         </ServiceOrder>
         <ServiceOrder name="MPABX_LIST_VPN_HUNTINGNO">
         <parameter>GRPID</parameter>
         <parameter>MAINNUMBER</parameter>
         </ServiceOrder>
    so now what i want to do is, when i select a serviceOrder e.g: MPABX_LIST_VPN_MEMBER, i what the program to automatically create Labels and TextFields on an InternalJFrame, meaning because MPABX_LIST_VPN_MEMBER has 9 parameters 9 Labels("Parameter names") and TextField must be created on an internalJFrame, or because MPABX_LIST_VPN_HUNTINGNO has 2parameters 2 Labels("Parameter names") and TextField must be created on an internalJFrame

    The question is how can i create Labels and TextField Depending on the number of parameters that exist in a serviceOderElement.
    This is my code:
    try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse (new File("ServiceOrderGUIConfig.xml"));
    NodeList serviceOrder = doc.getElementsByTagName("ServiceOrder");
    int totalServiceOrder = serviceOrder.getLength();
    for(int s=0; s<serviceOrder.getLength() ; s++){
    Node anAttributeNode = serviceOrder.item(s);
    if(anAttributeNode.getNodeType() == Node.ELEMENT_NODE){
    Element anAttributeElement = (Element)anAttributeNode;
    NodeList para = anAttributeElement.getElementsByTagName("parameter");
    test=anAttributeElement.getAttribute("name");
    test2=anAttributeElement.getAttribute("description");
    if(menu1.getSelectedItem().equals(test))
    for(int paramCounter = 0; paramCounter <para.getLength();++paramCounter)
    Element parameterElement =(Element)para.item(paramCounter);
    NodeList parameterTextList =parameterElement.getChildNodes();
    String parameterValue =parameterTextList.item(0).getNodeValue().trim();
    System.out.println("\n"+parameterValue);
    }//end of if clause
    }//end of for loop with s var
    for(int counter = 0; counter < serviceOrder.getLength(); ++counter)
    Node anAttributeNode = serviceOrder.item(counter);
    if(menu1.getSelectedItem().equals(test))
    if(anAttributeNode.getNodeType()==Node.ELEMENT_NODE)
    Element anAttributeElement = (Element)anAttributeNode;
    NodeList para =anAttributeElement.getElementsByTagName("parameter");
    for(int paramCounter = 0; paramCounter <para.getLength();++paramCounter)
    Element parameterElement =(Element)para.item(paramCounter);
    NodeList parameterTextList =parameterElement.getChildNodes();
    String parameterValue =parameterTextList.item(0).getNodeValue().trim();
    System.out.println("\n"+parameterValue);
    System.out.println("=============================================");
    //For separating the values
    }catch (SAXParseException err) {
    String msg = "Error on line " + err.getLineNumber () + "\n, URL " + err.getSystemId ()+"\nMessage"+err.getMessage ();
    JOptionPane.showMessageDialog(null,msg,"ERROR!",JOptionPane.ERROR_MESSAGE);
    }catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    }catch (Throwable t) {
    t.printStackTrace ();
    }

  • Scrollbar doesn't show up on the panel while dynamically adding JTextFields

    I have a dynamic user iterface, where the JTextFields are added dynamically to a JPanel within the JFrame upon the click of a JButton. How do I use the JScrollPane so that the Vertical Scroll bar shows up for the JPanel as soon added TextFields go out of range? The Panel has a null layout coz I want the textfields at specific positions on the panel. The problem lies in showing the Vertical scroll bar once the text fields in the JPanel exceeds the Panel's size. The scrolls don't seem to show up. Please help!
    public Scenario() // Constructor
    textPanel = new JPanel();
    textPanel.setLayout(null);
    textPanel.setSize(508, 520);
    textPanel.setLocation(10,10);
    //..........lines of code
    public void addComponent(String text)
    j = j + 30;
    i = i+1;
    String lineno = Integer.toString(i) + ".";
    field = new JLabel(lineno);
    field.setBounds(90,j,20,24);
    textPanel.add(field);
    if (addline){
    content = new JTextField(text);
    content.setBounds(108,j,400,24);
    content.setBackground(new Color(255,255,255));
    textPanel.add(content);
    addline = false;
    invscenario = false;
    else if(invscenario) {
    content = new JTextField(text);
    content.setBounds(108,j,50,24);
    content.setEditable(false);
    textPanel.add(content);
    try{
    if (content.getText().length()!= 0)
    Statement statement1 = conn.createStatement();
    String query1 = "SELECT * FROM scenario " + "WHERE scenario_num LIKE '" + text + "'";
    rs = statement1.executeQuery(query1);
    rs.next();
    int recordNumber = rs.getInt(1);
    if(recordNumber != 0)
    labelcontent = new JLabel(rs.getString(3));
    labelcontent.setBounds(165,j,100,24);
    textPanel.add(labelcontent);
    }// end try
    catch(SQLException e)
    System.out.println(e);
    invscenario = false;
    addline = false;
    scrollPane = new JScrollPane(textPanel);
    scrollPane.add(textPanel);
    contentPane.add(scrollPane);
    contentPane.repaint();
    show();

    I guess since you don't have a layoutmanager you have to set the viewport dimensions of your JScrollPane manually.
    Try something like
    scrollPane.getViewport().reshape(....);
    zk

  • Adding more JButton/JLabel to a frame?

    I have a two frames, one for the meny and one the text. (like a framebuilt website)
    The problem is that the text frame must have diffrent buttons, labels and textareas according to what the user choses in the menu. So it is not only a textarea that is needed to be set .
    Here is the code;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GUI extends JFrame implements ActionListener
         //Konto
         String konto = "konto";
         //Logo
         String logo = "logo";
         //Meny
         String meny = "meny";
         String login = "login";
         //text
         String text = "text";
         int rattigheter = 0; //0 = kund, 1= personal 2=admin
         //Konto
         private JButton GUIkonto = new JButton (konto);
         //Logo
         private JButton GUIlogo = new JButton (logo);
         //meny
         private JButton GUImeny = new JButton (meny);
         private JButton GUIlogin = new JButton (login);
         //text
         private JLabel GUItext = new JLabel (text);
         private JLabel GUIlogintext = new JLabel ("Skriv in ditt anv�ndarnamn och l�senrod nedan");
         private JLabel GUIlogintext2 = new JLabel ("... Fast eftersom systemet fortfarande testas kan du bara skriva in vilka r�ttigheter du vill ha 1=kund, 2=personal 3=admin");
         private JTextField GUIloginfalt = new JTextField ("", 10);
         private JButton GUIloginknapp = new JButton ("login");
         public GUI()
              Container c = getContentPane();
              c.setLayout(new GridLayout(2, 2));
              JPanel konto = new JPanel(new GridLayout(1, 1));
              konto.add(GUIkonto);
              c.add(GUIkonto);
              JPanel logo = new JPanel(new GridLayout(1, 1));
              logo.add(GUIlogo);
              c.add(GUIlogo);
              JPanel meny = new JPanel(new GridLayout(2, 1));
              meny.add(GUImeny);
              meny.add(GUIlogin);
              c.add(meny);
              System.out.println ("ok " + text);
              if (text.equals("login"))
                   JPanel text = new JPanel(new GridLayout(4, 1));
                   text.add(GUIlogintext);
                   text.add(GUIlogintext2);
                   text.add(GUIloginfalt);
                   text.add(GUIloginknapp);
                   c.add(text);
              else
                   JPanel text = new JPanel(new GridLayout(1, 1));
                   text.add(GUItext);
                   c.add(GUItext);
              setTitle("GUI");
              setVisible(true);
              pack();
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              //------------Lyssanre----------------
              //Konto
              GUIkonto.addActionListener(this);
              //logo
              GUIlogo.addActionListener(this);
              //meny
              GUImeny.addActionListener(this);
              GUIlogin.addActionListener(this);
              System.out.println ("ok, start");
         public static void main (String[] arg)
              GUI a = new GUI();
         public void actionPerformed(ActionEvent e)
              //String konto = GUIkonto.getText();
              //----------------Konto---------------
              if (e.getSource() == GUIkonto)
                   System.out.println ("Konto");
                   GUItext.setText("konto");
              //---------------Logo----------------
              if (e.getSource() == GUIlogo)
                   System.out.println ("logo");
                   GUItext.setText("logo");
              //--------------Meny---------------
              //---------Bl�ddra---------
              if (e.getSource() == GUImeny)
                   System.out.println ("meny");
                   GUImeny.setText("meny2");
              //---------login------------
              if (e.getSource() == GUIlogin)
                   System.out.println ("login");
                   text = "login";
                   System.out.println ("text = " + text);
                   GUItext.setText("login");
                   text = "login";

    Thanks for your help, but I don't think it will work with cardLayout.
    As far as I can understand CardLayout can only show one thing at a time one JButton, or one JLabel or ...
    It must be able to show many components.
                   text.add(GUIlogintext);
                   text.add(GUIlogintext2);
                   text.add(GUIloginfalt);
                   text.add(GUIloginknapp);
                   c.add(text);

  • Adding Dynamic JButtons & JLabels on the JTool

    On occerance of certain ActionEvent i need to add dynamic JButtons & JLabels on the JToolBar. Initially JToolBar will be empty.
    Code below is not working properly...
    It is creating buttons dynamiclly but i cant set any property for that one.
    class DeviceAction extends AbstractAction
         public DeviceAction()
         // Add this action to the toolbar resulting
         // in a new button getting added to the
         // toolbar
         JButton jbutton = xmlFilesToolBar.add( this);
         xmlFilesToolBar.addSeparator();
         jbutton.setActionCommand( "Dynamic" );
    I will call " new DeviceAction(); " when ever ActionEvent occurs.
    I need to have controle over the dynamically added JButtons & JLables, bcoz each JButtons shld do some Actions when it is clicked.
    Plz do the needful.
    Reg,
    Bha.

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=725394&tstart=0

  • Adding images to jlabel

    newb question...
    i have an image i'd like to put on a jlabel. i think i know the code but where do i put the image so it can be retrieved...here is the part of the code i use to show image...
    ImageIcon icon = new ImageIcon("whatever.gif");
    JLabel jLabel1 = new JLabel(icon);
    when i run the app with the code like this the image doesnt show. the image is in a folder on my desktop now. do i need to move it somewhere else so that it can be retrieved or do i need to change the code to tell where the image is? thanks.

    Place the gif in your classpath and load it like this:
    URL url= YourClass.class.getClassLoader(
            ).getResource("whatever.gif"); // YourClass is the                                       class name
    if ( url != null ) {
        ImageIcon icon = new ImageIcon(url).getImage();
        JLabel jLabel1 = new JLabel(icon);
    }regds,
    CA

  • Adding KeyListener to JLabel

    Hello,
    I have a JLabel in a JPanel. I wanted to move it using keyboard arrow keys. How to do it?
    Thanks

    some enhancement.
              public void mouseClicked(MouseEvent me)
                   if(me.getClickCount() == 1)
                        label.addFocusListener(new FocusAdapter()
                             public void focusGained(FocusEvent fe)
                                  label.setBorder(new EmptyBorder(1,1,1,1));
                                  System.out.println(label.isRequestFocusEnabled());
                             public void focusLost(FocusEvent fe)
                                  label.setBorder(null);
              }

  • Layout of JLabels and JTextFields

    Hi!
    I am looking for an easy way to layout JLabels and JTextFields side by side like this:
    jlabel             jtextField
    small jlabel       jtextField
    longer jlabel      jtextFieldAny ideas on how to do this?
    Peter

    Read this section from the Swing tutorial on "Using Layout Managers":
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
    The easiest way is to use a GridLayout.
    JPanel panel = new JPanel();
    panel.setLayout( new GridLayout(0, 2) );
    panel.add( new JLabel("...") );
    panel.add( new JTextField(10) );
    panel.add( new JLabel("...") );
    panel.add( new JTextField(10) );
    A more complicated, but more flexible way is to use a GridBagLayout. Something like this:
    public class ActivityPanel extends JPanel
         public ActivityPanel()
              setBorder( new EmptyBorder(5, 5, 5, 5) );
              setLayout( new GridBagLayout() );
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.insets = new Insets(5, 10, 5, 10);
              // add street
              JLabel lStreet = new JLabel("Street");
              JTextField cStreet = new JTextField(32);
              addRow(gbc, lStreet, cStreet);
              // add city
              JLabel lCity = new JLabel("City");
              JTextField cCity = new JTextField(32);
              addRow(gbc, lCity, cCity);
         private void addRow(GridBagConstraints gbc, Component left, Component right)
              gbc.gridx = GridBagConstraints.RELATIVE;
              gbc.gridy = GridBagConstraints.RELATIVE;
              gbc.gridheight = 1;
              gbc.gridwidth = 1;
              gbc.anchor = GridBagConstraints.EAST;
              add(left, gbc);
              gbc.gridwidth = GridBagConstraints.REMAINDER;
              gbc.anchor = GridBagConstraints.WEST;
              add(right, gbc);
    }

  • Align JLabels and JTextFields vertically in different areas

    I like to have 3 TitledBorders for 3 different areas of my frame.
    Each area has its own components - JLabels, JTextField, etc.
    How to align JLabels and JTextFields vertically in different areas?
    e.g. for the following test program, how to configure label1, label2, label3 so that their right sides all align vertically and
    tf1, tf2, tf3 so that their left sides all align vertically?
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.TitledBorder;
    public class TitledBorderDemo extends JFrame {
      public TitledBorderDemo() {
        super("TitledBorderDemo");
        JTextField tf1 = new JTextField("hello", 6);
        JTextField tf2 = new JTextField("hello", 12);
        JTextField tf3 = new JTextField("test");
        JTextField tf4 = new JTextField("test2");
        JLabel label1 = new JLabel("1234567890ertyuiyup label");
        JLabel label2 = new JLabel("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz long label");
        JLabel label3 = new JLabel("short label");
        JLabel label4 = new JLabel("test");
        JPanel panel_tf = new JPanel(new GridBagLayout());
        JPanel panel_pf = new JPanel(new GridBagLayout());
        JPanel panel_ftf = new JPanel(new GridBagLayout());
        GridBagConstraints constraints = new GridBagConstraints(0, 0, 3, 3,
                0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0);
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_tf.add(label1, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_tf.add(tf1, constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_pf.add(label2, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_pf.add(tf2, constraints);
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_ftf.add(label3, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_ftf.add(tf3, constraints);
        constraints.gridx = 3;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.WEST;
        panel_ftf.add(label4, constraints);
        constraints.gridx = 4;
        constraints.anchor = GridBagConstraints.EAST;
        panel_ftf.add(tf4, constraints);
        panel_tf.setBorder(new TitledBorder("JTextField1"));
        panel_pf.setBorder(new TitledBorder("JTextField2"));
        panel_ftf.setBorder(new TitledBorder("JTextField3"));
        JPanel pan = new JPanel(new GridLayout(3, 1, 10, 10));
        pan.add(panel_tf);
        pan.add(panel_pf);
        pan.add(panel_ftf);
        this.add(pan);
      public static void main(String args[]) {
        JFrame frame = new TitledBorderDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 450);
        frame.setVisible(true);
    }

    Thank you! It works!
    I add some labels & components to your demo program.
    Most of the components align vertically.
    How to align the "Country", "Test2" & "Extension" labels on the right sides?
    How to align their corresponding components so that their left sides all align vertically?
    How to make the Cancel button stick to the Save button
    (i.e. eliminate the gap between the Cancel and the Save button)?
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TitledBorderDemoNew extends JFrame {
      public TitledBorderDemoNew() {
        super("TitledBorderDemoNew");
        JLabel nameLabel = new JLabel("Name");
        JTextField nameText = new JTextField(20);
        JLabel addressLabel = new JLabel("Address (City & State)");
        JTextField addressText = new JTextField(40);
        JLabel countryLabel = new JLabel("Country");
        JTextField countryText = new JTextField(30);
        JLabel testLabel = new JLabel("Test");
        JTextField testText = new JTextField(20);   
        JLabel test2Label = new JLabel("Test2");
        JTextField test2Text = new JTextField(20);   
        JLabel phoneLabel = new JLabel("Phone");
        JTextField phoneText = new JTextField(20);
        JLabel extensionLabel = new JLabel("Extension");
        JTextField extensionText = new JTextField(5);
        JLabel postalCodeLabel = new JLabel("Postal Code");
        JTextField postalCodeText = new JTextField(6);
        JButton saveButton = new JButton("Save");
        JButton cancelButton = new JButton("Cancel");
        JButton commentButton = new JButton("Comment");
        int longWidth = addressLabel.getPreferredSize().width;
        GridBagConstraints constraints = new GridBagConstraints();
        JPanel p1 = new JPanel(new GridBagLayout());
        p1.setBorder(createBorder("Name"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p1.add(nameLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p1.add(nameText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p1.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p1.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p2 = new JPanel(new GridBagLayout());
        p2.setBorder(createBorder("Address"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(addressLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p2.add(addressText, constraints);
        // extra label & component
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,36,4,6);
        p2.add(countryLabel, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(countryText, constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(testLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p2.add(testText, constraints);
        // extra label & component
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,36,4,6);
        p2.add(test2Label, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(test2Text, constraints);
        constraints.gridx = 4;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p2.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p2.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p3 = new JPanel(new GridBagLayout());
        p3.setBorder(createBorder("Phone"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p3.add(phoneLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p3.add(phoneText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p3.add(extensionLabel, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        p3.add(extensionText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p3.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p3.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p4 = new JPanel(new GridBagLayout());
        p4.setBorder(createBorder("Postal Code"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p4.add(postalCodeLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p4.add(postalCodeText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p4.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p4.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p5 = new JPanel(new GridBagLayout());
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p5.add(commentButton, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p5.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 2;
        constraints.gridwidth = GridBagConstraints.RELATIVE;
        constraints.fill = GridBagConstraints.NONE;
        constraints.anchor = GridBagConstraints.EAST;
        p5.add(cancelButton, constraints);
        constraints.gridx = 3;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.anchor = GridBagConstraints.EAST;
        p5.add(saveButton, constraints);
        JPanel panel = new JPanel(new GridBagLayout());
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        panel.add(p1, constraints);
        constraints.gridy = 1;
        panel.add(p2, constraints);
        constraints.gridy = 2;
        panel.add(p3, constraints);
        constraints.gridy = 3;
        panel.add(p4, constraints);
        constraints.gridy = 4;
        panel.add(p5, constraints);
        this.add(new JScrollPane(panel));
      private Border createBorder(String title)
        TitledBorder b = new TitledBorder(title);
        b.setTitleColor(Color.RED.darker());
        return b;
      public static void main(String args[]) {
        JFrame frame = new TitledBorderDemoNew();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }Edited by: 833768 on 26-Apr-2011 10:32 AM

  • JTextField does not redraw properly

    Hi,
    I have a JPanel that displays some buttons amongst some textfields and labels. One of my buttons is labeled Add Customer. When the user clicks on Add Customer he is presented with a number of JTextFields and JLabels which are all displayed fine.
    However, when the user clicks on Cancel or closes the InternalFrame in which the JTextFields and JLabels are displayed and then clicks on Add Customer again, then the JTextFields are not redrawn properly. I image of this behavior can be seen at
    http://www.grosslers.com/totals.07.png
    As soon as I start to type text into the textfield then the whole textfield redraws itself as it should, but when it looses focus then the textfield becomes invisible once again.
         // Some textfields
         private     JTextField textField_customerEditCompanyName = new JTextField(10);
         private     JTextField textField_customerEditContactName = new JTextField(10);
          * Panel that will hold all the buttons for the quote request details tabbed panel
         public JPanel createQuoteRequestDetailsButtons() {
              // Panel to act as a container for the buttons
              JPanel panel_quoteRequestDetailsButtons = new JPanel();
              // Create, register action listeners and add buttons to the panel
              JButton button_addCustomer = new JButton("Add Customer");
              button_addCustomer.addActionListener(new ActionListener() {
                   public void actionPerformed (ActionEvent actionEvent) {
                        // Add a new customer
                        addCustomerListener();
              panel_quoteRequestDetailsButtons.add(button_addCustomer);
              return panel_quoteRequestDetailsButtons;
          * Display a new internal frame when the user wants to add a new customer
         public void addCustomerListener() {
              // Master panel for the add customer details
              JPanel panel_addCustomerMaster = new JPanel();
              // Add the customer details panel to the master panel     
              panel_addCustomerMaster.add(customerDetailsPanel());
              // Ensure that all the textfields are blank
              resetCustomerDetailsPanelTextFields();
              // Add the buttons panel to the master panel          
              panel_addCustomerMaster.add(addCustomerButtons());
              // Add the master panel to the internal frame
              internalFrame_addCustomer.add(panel_addCustomerMaster);
              // Add the internal frame to the desktop pane
              JupiterMainGUI.desktopPane.add(internalFrame_addCustomer);
              // Set the size of the internal frame
              internalFrame_addCustomer.setSize(500,420);
              // Set other properties of the internal frame
              internalFrame_addCustomer.setClosable(true);
              internalFrame_addCustomer.setIconifiable(false);
              internalFrame_addCustomer.setMaximizable(false);
              // Set the location of the internal frame to the upper left corner
              // of the current container
              internalFrame_addCustomer.setLocation(0,0);
              // Set the internal frame resizable
              internalFrame_addCustomer.setResizable(false);
              // Show the internal frame
              internalFrame_addCustomer.setVisible(true);
          * Panel that displays the textfields and labels when the user clicks on
          * add or view customer details
         public JPanel customerDetailsPanel() {
              // Create master container for this panel
              JPanel panel_customerDetailsMaster = new JPanel();
              // Create the container that will hold all the textfields/labels for
              // the creation of a new customer          
              JPanel panel_customerDetails = new JPanel(new SpringLayout());
              // Add the details panel to the master panel
              panel_customerDetailsMaster.add(panel_customerDetails);
              // Set the border for the panel
              panel_customerDetails.setBorder(BorderFactory.createTitledBorder("Customer Details"));
              // Create textfields/labels, add them to the internalFrame
              JLabel label_customerCompanyName = new JLabel("Company Name : ");
              JLabel label_customerContactName = new JLabel("Contact Name : ");
              panel_customerDetails.add(label_customerCompanyName);
              panel_customerDetails.add(textField_customerEditCompanyName);
              panel_customerDetails.add(label_customerContactName);
              panel_customerDetails.add(textField_customerEditContactName);
              //Lay out the panel.
              SpringUtilities.makeCompactGrid(panel_customerDetails,
                                    2, 2, //rows, cols
                                    5, 5,        //initX, initY
                                    5, 5);       //xPad, yPad
              return panel_customerDetailsMaster;
          * Panel holding the buttons when the user clicks on add customer
         public JPanel addCustomerButtons() {
              // Container for the buttons
              JPanel panel_addCustomerButtons = new JPanel();
              // Create the buttons for the panel
              JButton button_customerOk = new JButton("Ok");
              JButton button_customerCancel = new JButton("Cancel");
              button_customerOk.addActionListener(new ActionListener() {
                   public void actionPerformed (ActionEvent actionEvent) {
              // Closing the internal frame. When i re-open this internal frame again
                  // the labels are re-drawn properly but not the textfields.
              button_customerCancel.addActionListener(new ActionListener() {
                   public void actionPerformed (ActionEvent actionEvent) {
                        try {
                             // close and remove the internal frame from the desktop pane     
                             internalFrame_addCustomer.setClosed(true);
                        } catch (PropertyVetoException exception) {
                        JupiterMainGUI.desktopPane.remove(internalFrame_addCustomer);
              panel_addCustomerButtons.add(button_customerOk);
              panel_addCustomerButtons.add(button_customerCancel);          
              return panel_addCustomerButtons;
         }So far I have a solution, and that is to use the GTK look and feel, but it is not really an option. Another way that I have managed to get the textfields to display properly is to create them in the same method, where I create the labels. Again, this is not really an option as i need to access the textfields outside the method scope.
    Any help would be greatly appreciated
    -- Pokkie

    I added the following :
         * Panel that displays the textfields and labels when the user clicks on
         * add or view customer details
         public JPanel customerDetailsPanel() {
              // Create master container for this panel
              JPanel panel_customerDetailsMaster = new JPanel();
              // Create the container that will hold all the textfields/labels for
              // the creation of a new customer          
              JPanel panel_customerDetails = new JPanel(new SpringLayout());
              // Add the details panel to the master panel
              panel_customerDetailsMaster.add(panel_customerDetails);
              // Set the border for the panel
              panel_customerDetails.setBorder(BorderFactory.createTitledBorder("Customer Details"));
              // Create textfields/labels, add them to the internalFrame
              JLabel label_customerCompanyName = new JLabel("Company Name : ");
              JLabel label_customerContactName = new JLabel("Contact Name : ");
              panel_customerDetails.add(label_customerCompanyName);
              panel_customerDetails.add(textField_customerEditCompanyName);
              panel_customerDetails.add(label_customerContactName);
              panel_customerDetails.add(textField_customerEditContactName);
    // Added this line , but doesn't seem to make a difference. also called revalidate() on the
    // internalFrame in which this panel is displayed but no luck either. Called revalidate()
    // on panel_customerDetailsMaster but nothing :(
              panel_customerDetails.revalidate();
              //Lay out the panel.
              SpringUtilities.makeCompactGrid(panel_customerDetails,
    2, 2, //rows, cols
    5, 5, //initX, initY
    5, 5); //xPad, yPad
              return panel_customerDetailsMaster;
    Thanks for the response thou, much appreciated

  • ImageIcons in a JLabel get their top-most row of pixels cut off

    Hello. I've added a "Loading..." screen to my application that basically consists of a JWindow with a background image. However, I've noticed something odd when adding an ImageIcon to a JLabel. It seems that any image I add gets its top row of pixels cut off. The small program below illustrates this.
    import javax.swing.*;
    import java.awt.*;
    public class JLabelTest {
       static final String WINDOW_IMAGE = "my_image.jpg";
        * Create and display the loading screen
       private static void displayLoadingScreen()
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                JWindow winLoadingScreen = new JWindow();
                ImageIcon loadingImg = new ImageIcon(WINDOW_IMAGE);
                JLabel lblImage = new JLabel(loadingImg);
                winLoadingScreen.getContentPane().add(lblImage);
                winLoadingScreen.pack();
                System.out.println("label dimensions:      " + lblImage.getSize().width + " x " + lblImage.getSize().height);
                System.out.println("image icon dimensions: " + loadingImg.getIconWidth() + " x " + loadingImg.getIconHeight());
                winLoadingScreen.setLocation(100, 100);
                winLoadingScreen.setVisible(true);
        * Entry point
        * @param args
       public static void main(String[] args)
          SwingUtilities.invokeLater(new Runnable() {
             public void run()
                displayLoadingScreen();
    }(Obviously, replace my_image.jpg with something else if you'd like to run the code on your own machine.)
    When I run the program with, say, an 800 x 600 resolution image, the output I get is:
    label dimensions:      800 x 599
    image icon dimensions: 800 x 600As you can see, the image gets "shortened" by one pixel when added to the JLabel. If you look at the image that is displayed, you can see that it's the top row that gets cut off. I've tried changing the layout of the JWindow that the JLabel is being added to, but that didn't change anything. I've tried using a number of different images in varying formats, and the same thing happens to all of them.
    Any ideas? Thanks in advance.

    Have you tried to set label's preferredSize manually?
    What happens when you add empty border t the label with some insets?
    regards,
    Stas

  • How to limit the number of characters entered in a JTextfield???

    Hello there,
    I have created a Text box using swing component JTextField and I want to limit the number of characters entered to 8 characters..how do i proceed with that?
    Thanks in advance!
    Joe

    Ty out this
    import com.sun.java.swing.text.*;
    //import javax.swing.text.*;
    public class JTextFieldLimit extends PlainDocument {
    private int limit;
    // optional uppercase conversion
    private boolean toUppercase = false;
    JTextFieldLimit(int limit) {
    super();
    this.limit = limit;
    JTextFieldLimit(int limit, boolean upper) {
    super();
    this.limit = limit;
    toUppercase = upper;
    public void insertString
    (int offset, String str, AttributeSet attr)
    throws BadLocationException {
    if (str == null) return;
    if ((getLength() + str.length()) <= limit) {
    if (toUppercase) str = str.toUpperCase();
    super.insertString(offset, str, attr);
    import java.awt.*;
    import com.sun.java.swing.*;
    //import javax.swing.*;
    public class tswing extends JApplet{
    JTextField textfield1;
    JLabel label1;
    public void init() {
    getContentPane().setLayout(new FlowLayout());
    label1 = new JLabel("max 10 chars");
    textfield1 = new JTextField(15);
    getContentPane().add(label1);
    getContentPane().add(textfield1);
    textfield1.setDocument
    (new JTextFieldLimit(10));

  • How to refresh the JLabel

    I have created a gif animated image which i am adding to the JLabel. what happens is that the animation runs only once and next time it does not continues why ? is it necessary to refresh the image and if that so please tell me how ?
    Help me !

    A the gif file is working well in IE there is no looping problem
    tell me some other solution.

  • Using array create JLabel

    i have one problem about using addKeyListener, i'm using array to create JLabel but once i've compile it, it came out a message as i shown, so where is my problem, hope someone can fix it for me and explain it for me, thank you
    ---------- Capture Output ----------
    "C:\Program Files\Java\jdk1.6.0_03\bin\javac.exe" Login.javaLogin.java:78: not a statement
    inputTextName[1]KeyPressed( event );
    ^
    Login.java:78: ';' expected
    inputTextName[1]KeyPressed( event );
    ^
    2 errors
    Terminated with exit code 1.---------- Capture Output ----------
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Login extends JFrame
         //JLabel[] lblName = {"lblName1","lblName2"};
         JLabel[] labelName;
         //JTextField[] txtfldName = {input1,input2};
         JTextField[] inputTextName;
         //JLabel[] array = new JLabel[veryLargeNumber];
         JButton[] btnName = new JButton[3];
    public void userInterface()
         this.setBackground(Color.blue);
         this.setTitle("Log in");
         this.setSize(285,130);
         this.setVisible(true);
         Container contentPane = getContentPane();
         contentPane.setLayout(null);
         labelName[0] = new JLabel();
         labelName[0].setText("ID: ");
         labelName[0].setBounds(16, 16, 130, 21);
         this.add(labelName[0]);     
         inputTextName[0] = new JTextField();
         inputTextName[0].setText(" ");
         inputTextName[0].setBounds(50, 16, 150, 21);
         inputTextName[0].setHorizontalAlignment(JTextField.LEFT);
         this.add(inputTextName[0]);
         labelName[1] = new JLabel();
         labelName[1].setText("Password: ");
         labelName[1].setBounds(16, 48, 104, 21);
         this.add(labelName[1]);
         inputTextName[1] = new JTextField();
         inputTextName[1].setText(" ");
         inputTextName[1].setBounds(50, 48, 150, 21);
         inputTextName[1].setHorizontalAlignment(JTextField.LEFT);
         this.add(inputTextName[1]);
         btnName[0] = new JButton();
         btnName[0].setText("login");
         btnName[0].setBounds(120,80,65,20);
         this.add(btnName[0]);
         btnName[1] = new JButton();
         btnName[1].setText("exit");
         btnName[1].setBounds(190,80,65,20);
         this.add(btnName[1]);
         inputTextName[1].addKeyListener(
             new KeyAdapter() // anonymous inner class
                // method called when user types in cartonsJTextField
                public void keyPressed( KeyEvent event )
                  inputTextName[1]KeyPressed( event );
             } // end anonymous inner class
          ); // end call to addKeyListener
    //call function
         public Login()
              userInterface();          
         public static void main (String args[])
              Login application = new Login();
               application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         }Edited by: slamgundam on Oct 24, 2007 11:48 PM

    slamgundam wrote:
    the purpose is try to get the text in the inputTextField
    inputTextName[1].addKeyListener(
        new KeyAdapter()
             // method called when user types in cartonsJTextField
             public void keyPressed( KeyEvent event )
                   String str = inputTextName[1].getText();
                   System.out.println(str);
    );

  • Two very STRANGE problems with JWindow and JTextField

    I am having some trouble in the program that I am making. It is a Swing based GUI.
    I have a JWindow with a JPanel in it that holds JTextFields and JLabels.
    problem1----I can't see a caret in any of the textfields but I can still enter text.
    problem2----If I control + tab to another window, and control + tab to get back to the JWindow then I can see a caret, but the caret will not change if I click on another textfield and also I can't move to another textfield to enter text. If i do another control tab, then the textfield that i tried to switch to will have focus, but there is now two carets...the first one is where I was but that field does not have focus. I can do this control-tab for as many textfields as I need to fill, but it obviously is not practical.
    I am using a call to super(Frame frame) when calling my JWindow but that didn't seem to fix it.
    Any help would be great!!!!! thanks john

    try checking out this thread :
    http://forum.java.sun.com/thread.jsp?forum=57&thread=153344
    sounds like your problem, kinda. it looks more like a repaint issue, since u get two carets at the same time - as if the screen isn't refreshing enough (u could give it some Spearmint POLO :)

Maybe you are looking for

  • Void and boolean

    public void boolean compute(int n) { if n>5      {return true; }      else    {return false; }   }Is this subroutine possibly correct? Is there any possibility for a subroutine to have void and boolean at the same time (not to mention an if without p

  • In p6 8.2,I can't filter resources or role to resources planning

    in p6 8.2,"resources"section,"planning"page,"filter and group by" ,I open a dialog windows to select portfilos,projects,roles or resources ,but after I click the button"OK",the application have no changes, it also not retrun to the "planning" page an

  • How to read XML using vbscript

    hi friends I have A big XML having following format : <ECSC> <ATTRIBUTES> <ETTOOLNAME>ECATT</ETTOOLNAME> <ETOBJ_GNDT> <VERSION>00000001</VERSION> <TWB_TITLE>TF_FI_FP_FI_0569_MS07_CO_Search_Help_Internal_Orders_vTD0_1_EN.x</TWB_TITLE> <TWB_STATUS>X</T

  • Rac DB 10.2  & Bpel/ OAS 10.1.2.0.0

    bpel installs just fine going to a non-rac dehydration db; bpel/oas v 10.1.2.0.0 to db 10.2; re-ren irca & upgrade scripts on the db; had to insert the vip hostname for the irca script's network adapter; still cannot however, get bpel past the connec

  • Changing DB_NAME after database installation

    Hi, I installed Oracle10g on linux server. now I want to change the database name DB_NAME for security reasons. How can i do this? and where all i need to the changes for the database and EM to come back up successfully. Thanks in advance.