Positioning JLabels

Hey,
I'm trying to learn Swing applications and I've run into a bit of trouble positioning my "Hello World" label on the screen. I've created a JFrame that is 640x480 in size and I want to move my label to a specific x,y within the frame. I've tried using setLocation and setBounds with no luck. The label stays stuck vertically centered on the left side of the screen. How do I move this label around?
Mike

You need to read on the layout managers. For instance JFrame contentPanes use the BorderLayout as the default layout manager while JPanels use FlowLayout as the default managers. There are two ways to work here: 1) work with the the appropriate layout manager to place your JLabel in a position that will remain correct even if the JFrame is resized, or 2) set the contentPane's layout to null and place your JLabel by absolute positioning (i.e., setBounds or something similar). If you do the latter, you will have to set the size of the jlabel too (setBounds does this). I recommend the former technique over the latter.
For instance this adds a JLabel to a JFrame (via a JPanel) by the first method: the null layout with absolute positioning and sizing of the JLabel by calling its setBounds method:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class HelloWorldFrame
    // the JPanel that will hold our JLabel
    private JPanel mainPanel = new JPanel();
    public HelloWorldFrame()
        mainPanel.setPreferredSize(new Dimension(640, 480));
        mainPanel.setLayout(null); // use no layout manager
        JLabel helloWorldLabel = new JLabel("Hello World");
        // set the bounds: both the location x, y, and the size width, height
        helloWorldLabel.setBounds(20, 400, 100, 24);
        // so we can see the exact size of the JLabel
        helloWorldLabel.setBorder(BorderFactory.createLineBorder(Color.blue, 4));
        mainPanel.add(helloWorldLabel); // add it to the JPanel
    public JPanel getMainPanel()
        return mainPanel;
    private static void createAndShowUI()
        // create a JFrame
        JFrame frame = new JFrame("HelloWorldFrame");
        // add our JPanel to this JFrame
        frame.getContentPane().add(new HelloWorldFrame().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    // call swing in a thread-safe manner
    public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
            public void run()
                createAndShowUI();
}And here I add the JLabel using the second technique: layout managers:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class HelloWorldFrame2
    // the JPanel that will hold our JLabel
    private JPanel mainPanel = new JPanel();
    public HelloWorldFrame2()
        mainPanel.setPreferredSize(new Dimension(640, 480));
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 56, 0));
        JLabel helloWorldLabel = new JLabel("Hello World");
        // so we can see the exact size of the JLabel
        helloWorldLabel.setBorder(BorderFactory.createLineBorder(Color.blue, 4));
        JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        labelPanel.add(helloWorldLabel);
        mainPanel.add(labelPanel, BorderLayout.SOUTH); // add it to the JPanel
    public JPanel getMainPanel()
        return mainPanel;
    private static void createAndShowUI()
        // create a JFrame
        JFrame frame = new JFrame("HelloWorldFrame2");
        // add our JPanel to this JFrame
        frame.getContentPane().add(new HelloWorldFrame2().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    // call swing in a thread-safe manner
    public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
            public void run()
                createAndShowUI();
}Edited by: Encephalopathic on Feb 18, 2008 7:58 PM

Similar Messages

  • Help with a simple GUI.

    I am totally new to building GUI's. Everything I have picked up I did so online. From what I have learned this should work, but it throws all sorts of exceptions when I run it.
    package com.shadowconcept.mcdougal;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class NavSystemGUI extends JApplet implements ActionListener
          String citylist[] = {"Birmingham", "Tuscaloosa", "Atlanta", "Montgomery", "Macon", "Mobile", "Tallahassee", "Ashburn", "Lake City", "Ocala", "Orlando", "Daytona Beach", "Jacksonville", "Savannah"};
          NavigationSystem N1 = new NavigationSystem();
       JLabel startposition = new JLabel("Starting Position");
       JLabel endposition = new JLabel("Ending Posiiton");
       JLabel choice = new JLabel("Make a Choice");
       JComboBox startselection = new JComboBox(citylist);
       JComboBox endselection = new JComboBox(citylist);
       ButtonGroup choices = new ButtonGroup();
       JRadioButton DFS = new JRadioButton("Depth-First Search");
       JRadioButton BFS = new JRadioButton("Breadth-First Search");
       JRadioButton shortestpath = new JRadioButton("Find the Shortest Path");
       JButton button = new JButton("Execute");
       String Start, End;
        public void init()
          Container con = getContentPane();
          con.setLayout(new FlowLayout());
          choices.add(DFS);
          DFS.setSelected(true);
          choices.add(BFS);
          choices.add(shortestpath);
          con.add(startposition);
          //startposition.setLocation(10, 20);
          con.add(startselection);
          //startselection.setLocation(50, 20);
          startselection.addActionListener(this);
          con.add(endposition);
          //endposition.setLocation(10, 40);
          con.add(endselection);
          //endselection.setLocation(50, 40);
          endselection.addActionListener(this);
          con.add(choice);
          //choice.setLocation(10, 60);
          con.add(DFS);
          DFS.addActionListener(this);
          con.add(BFS);
          BFS.addActionListener(this);
          con.add(shortestpath);
          shortestpath.addActionListener(this);
          con.add(button);
          button.addActionListener(this);
          startselection.requestFocus();
          Start = startselection.getName();
          End = endselection.getName();
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == button){
                 if(DFS.isSelected()){
                      N1.DFS(Start, End);
                 if(BFS.isSelected()){
                      N1.BFS(Start, End);
                 if(shortestpath.isSelected()){
                      N1.shortestpath(Start, End);
    }

    rhm54 wrote:
    I am totally new to building GUI's. Everything I have picked up I did so online. From what I have learned this should work, but it throws all sorts of exceptions when I run it.It compiles and runs fine for me. Perhaps your problems are with the NavigationSystem class? But I agree with Hunter: show your error messages and somehow indicate the lines in your code that cause the errors. I often find that reposting the code with comments indicating the offending lines works best. Good luck.

  • How to align JLabels and set them to the rightmost position before the JTextField?

    I don't know if this is the right group to ask in.
    I am using the miglayout,
    and I want every JLabels to locate at
    the rightmost position next to the JTextField after it
    so that there won't be any gaps between
    the JLabels and the JTextFields
    Any example to show
    Thanks
    Jack

    Mod: moved from JP.

  • JLabel icon position question

    I want to have a JLabel with text and an icon. I want the text to be positioned on the left and I want the icon on the right. My question is: Is this possible and if so how?

    RTFM
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JLabel.html#setHorizontalTextPosition(int)

  • Illegal component position when add JLabel to JtextPane

    Hi all,
    I want to add a JLabel to a JTextPane, the label shoud be put in the lines of text just like the normal text. I have some questions:
    1. How can I put the label in the position we want, when I use the method add(label, textPane.getStyledDocument().getLength()), it generates exception :"illegal component position"
    2. How can I set the width and the height of the label so that user cannot know that I used the label. I mean the text on label and the normal text on JTextPane must look the same. Of course I know the length of the caption of the label
    Thank you very much

    How can I put the label in the position we want, I'm not sure you can add a component using that method. I think there is an insertComponent(...) method to use. Also you may need to make the text pane uneditable first if I remember correctly. Something like:
    textPane.setEditable(false);
    textPane.insertComponent(...);
    textPane.setEditable(true);
    How can I put the label in the position we want, label.setFont(textPane.getFont());

  • How to define the position of a JLabel in a JPanel?

    Could anybody help me for my problem ?
    - I added two JLabel into a JPanle using the folowwing code, but the two labels are displayed over each other. JLabel.setBounds() doesn't help.
    questionL1 = new JLabel("question1");
    questionL1.setBounds(50, 200, 700, 50);
    questionL2 = new JLabel("question2");
    questionL2.setBounds(50, 250, 700, 50);
    graphicPanel = new JPanel();
    graphicPanel.setPreferredSize(new Dimension(850, 450));
    graphicPanel.setLayout(new BorderLayout());
    graphicPanel.setBackground(Color.white);
    graphicPanel.add(questionL1);
    graphicPanel.add(questionL2);
    Thanks in advance

    By default components get added to the 'center' of a BorderLayout, so questionL2 replaces questionL1 in the panel.
    Here is a link to the Swing tutorial on "Using Layout Managers":
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

  • Compilation error for JLabel - trying to position text & icon

    Hi,
    I'm still a Jnewbie & having difficulty understanding how this works.
    the error:
    C:\biz>javac -classpath C:\ Welcome.java
    Welcome.java:54: '.class' expected
    Member.setVerticalTextPosition(int BOTTOM );
    ^
    Welcome.java:54: ')' expected
    Member.setVerticalTextPosition(int BOTTOM);
    ^
    Welcome.java:54: unexpected type
    required: value
    found : class
    Member.setVerticalTextPosition(int BOTTOM);
    ^
    3 errors
    ======================================================================
    the code:
    Member = new JLabel(" Designed for Engineers in association with members.",
    new ImageIcon("images/members.gif"),
    JLabel.LEFT);
    Member.setVerticalTextPosition(int BOTTOM);
    Member.setHorizontalTextPosition(int CENTER);

    Hopefully you have declared 'Member' to be a JLabel somewher in your code, if not then do this:
    JLabel Member = new JLabel("....");
    The constructor parameters are correct by the way.
    Your mistake is the
    Member.setVerticalTextPosition(int BOTTOM);
    Member.setHorizontalTextPosition(int CENTER);
    You have to call these methods with an int parameter, you are
    actually defining an int variable!
    But you are close to that want you want to do it has to be:
    Member.setVerticalTextPosition(SwingConstats.BOTTOM);
    Member.setHorizontalTextPosition(SwingConstants.CENTER);
    SwingConstants.BOTTOM is a final static int variable defined in
    the SwingConstants class.

  • Need help with animated JLabel

    I've created an animated extension of the JLabel which imitates a "typewriter" effect. It works smoothly for single-line labels.
    Here is a basic pseudo-code outline of how I went about doing it:
    constructor(String fullText, int delay) {
      create swing timer
      start timer
    //called by timer
    actionPerformed() {
      if (all chars are printed)
        stop timer
      else {
        labelStr += fullText.charAt(pos);
        this.setText(labelStr);
        pos++;
    }The problem is, whenever It recognises an HTML line break (to make it a multi-line label), all of the text gets bumped up. Here's a rough animation showing my animated label and a regular jlabel...
    http://img223.imageshack.us/img223/8459/typewriteranizy1.gif
    As you can see, once the line breaks are added to the animated label's text, all the text is moved up. This creates a choppy scrolling effect, something I'm trying to avoid at the moment.
    Any ideas on how I could keep the animated text in a fixed position, so it doesn't scroll up like this?
    I can provide source code if needed.

    Ah yes, my bad. I tried it now but realised I have tried it before, and it doesn't work. i never increments and so it prints the first character every time the timer fires instead. Here is a SSCCE:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TW extends JFrame implements ActionListener
         JLabel iValue = new JLabel("i = ");
         JTextArea log = new JTextArea(10, 20);
         JButton start = new JButton("Start");
         Timer type;
         public TW()
              setLayout(new BorderLayout(0, 0));
              log.setEditable(false);
              log.setLineWrap(true);
              log.setWrapStyleWord(true);
              add(iValue, BorderLayout.PAGE_START);
              add(log, BorderLayout.CENTER);
              add(start, BorderLayout.PAGE_END);
              start.addActionListener(this);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              ActionListener listen = new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        int i = 0;
                        String msg = "This is a simple typewriter demo.";
                        if (i < msg.length())
                             String str = (String)new Character(msg.charAt(i)).toString();
                             log.append(str);
                             iValue.setText("i = " +i);
                             i++;
                        else
                             type.stop();
              type = new Timer(250, listen);
              type.start();
         public static void main (String[] args)
              new TW();
    }

  • Why do I get Illegal Component position when I say FlowLayout.CENTER

    The code runs fine if you replace the line
    Jp7.add(submitButton, FlowLayout.CENTER);
    with
    Jp7.add(submitButton);
    I know FlowLayout's default location is CENTER. But when I explicitly say to center the button, it crashes during runtime but compiles fine.
    Whats the reason for this? Is this a bug?
    I am using 1.4.0_03.
    I getthe following error.
    Exception in thread "main" java.lang.IllegalArgumentException: illegal component
    position
    at java.awt.Container.addImpl(Container.java:568)
    at java.awt.Container.add(Container.java:327)
    at Mon2.main(Mon2.java:114)
    ALSO CAN I DO THE SAME WITHOUT USING SO MANY JPANELS?????????????????? I AM NOT NEW TO PROGRAMMING BUT I AM NEW TO GUI PROGRAMMING.
    Thanks in advance.
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Mon2 extends JFrame{
    static long i =0;
    static int jobid = 0;
    static String StartTime = "";
    static String LastReport = "";
    static String FinishTime = "";
    static String Description = "";
    static String job_position = "";
    static String desc ="";
    public static String database = "";
    public static String user = "";
    public static String password = "";
    static int counter = 1;
    static boolean valuesEntered = false;
      JButton jButton1 = new JButton();
      JButton jButton2 = new JButton();
      JButton jButton3 = new JButton();
      BorderLayout borderLayout1 = new BorderLayout();
      JLabel jLabel1 = new JLabel();
    JTextPane jTextArea1 = new JTextPane();
    static JTextField userArea = new JTextField();
    static JPasswordField passArea = new JPasswordField();
    static JTextField databaseArea = new JTextField();     
    static JFrame f = new JFrame();
    static JLabel us = new JLabel ("UserName: ");
    static JLabel pa = new JLabel ("Password: ");
    static JLabel da = new JLabel ("Database: ");
      BorderLayout borderLayout2 = new BorderLayout();
      JPanel jPanel1 = new JPanel();
      JLabel jLabel2 = new JLabel();
         public Mon2() {
        try  {
          jbInit();
        catch (Exception e) {
          e.printStackTrace();
         public static void main(String args[]) {
              System.out.println("Starting Mon2...");
        f.setSize(300,200);
        f.setTitle("Login");
        f.setLocation(250,250);
        f.setResizable(false);
        Panel Jp1 = new Panel (new BorderLayout());
        Panel Jp3 = new Panel (new BorderLayout());
        Jp3.add(us, BorderLayout.NORTH);
        Jp3.add(pa, BorderLayout.CENTER);
        Jp3.add(da, BorderLayout.SOUTH);
        userArea.setEditable(true);
        userArea.setSize(20,20);
        passArea.setEditable(true);
        databaseArea.setEditable(true);
        JButton submitButton = new JButton("Submit");
        JPanel Jp2 = new JPanel (new BorderLayout());
        JPanel Jp4 = new JPanel (new FlowLayout());
        userArea.setPreferredSize(new Dimension(200,21));
        Jp4.add(userArea, FlowLayout.LEFT);
        Jp4.add(us, FlowLayout.LEFT);
        JPanel Jp5 = new JPanel (new FlowLayout());
        passArea.setPreferredSize(new Dimension(200,21));
        Jp5.add(passArea,FlowLayout.LEFT);
        Jp5.add(pa, FlowLayout.LEFT);
        JPanel Jp6 = new JPanel (new FlowLayout());
        databaseArea.setPreferredSize(new Dimension(200,21));
        databaseArea.setText("DWPROD");
        Jp6.add(databaseArea,FlowLayout.LEFT);
        Jp6.add(da, FlowLayout.LEFT);
        Jp1.add(Jp4, BorderLayout.NORTH);
        Jp1.add(Jp5, BorderLayout.CENTER);
        Jp2.add(Jp6, BorderLayout.NORTH);
       JPanel Jp7 = new JPanel(new FlowLayout());
    ///////////////////////////This is  the line//////////////////
    //If you remove the ,FlowLayout.CENTER it works fine.
    //If you leave it like as it is, it will compile but then give runtime error
        Jp7.add(submitButton, FlowLayout.CENTER);
        Jp2.add(Jp7, BorderLayout.SOUTH);
        Jp1.add(Jp2, BorderLayout.SOUTH);
        f.getContentPane().add(Jp1);
        Image img = Toolkit.getDefaultToolkit().getImage("c:\\appletHeader.gif");
        f.setIconImage(img);
        f.setDefaultCloseOperation(3);
        f.setVisible(true);
        f.pack();
         submitButton.resize(75, 30);
        submitButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(ActionEvent e) {
        user = userArea.getText();
        password = passArea.getText();
        database = databaseArea.getText();
        if((user.equals(null) || password.equals(null) || database.equals(null) || user.equals("") || password.equals("") || database.equals(""))){
        valuesEntered = false;
        else{
             valuesEntered = true;
        if(valuesEntered == true){
        f.setVisible(false);
              Mon2 mainFrame = new Mon2();
              mainFrame.setSize(600, 400);
              mainFrame.setTitle("Monitor");
        mainFrame.setLocation(100,200);
        mainFrame.setResizable(false);
        desc = "ERROR! or there are no locked jobs.";
              mainFrame.setVisible(true);
        else{
        JOptionPane.showMessageDialog(null,"Must enter values for UserName, Password and Database", "Value Required",JOptionPane.INFORMATION_MESSAGE);
    //    System.exit(0);
      private void jbInit() throws Exception {
        this.setDefaultCloseOperation(3);
        jButton1.setText("Refresh");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
          jButton1_actionPerformed(e);
        jButton2.setText(" Exit ");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            System.exit(0);
        this.getContentPane().setLayout(borderLayout1);
        jButton3.setText("Clear");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jTextArea1.setText("Click on Refresh to update screen.");
        Panel p = new Panel(new FlowLayout());
        Panel p2 = new Panel (new BorderLayout());
        jLabel1.setText("Monitor for current Job");
        jTextArea1.setPreferredSize(new Dimension(8, 50));
        jTextArea1.setContentType("text/html");
        jTextArea1.setText("");
        jTextArea1.setEditable(false);
        f.setResizable(false);
        f.setTitle("Login");
        jLabel2.setHorizontalTextPosition(SwingConstants.LEFT);
        jLabel2.setText("jLabel2");
        jLabel2.setHorizontalAlignment(SwingConstants.LEFT);
        f.getContentPane().setLayout(borderLayout2);
        jTextArea1.setSize(100,10);
        p.add(jButton1);
        p.add(jButton3);
        p.add(jButton2);
        this.getContentPane().add(jLabel1, BorderLayout.NORTH);
        this.getContentPane().add(jTextArea1, BorderLayout.CENTER);
        p2.add(p, BorderLayout.CENTER);
        this.getContentPane().add(p2, BorderLayout.SOUTH);
        pack();
        f.getContentPane().add(jPanel1, BorderLayout.CENTER);
        jPanel1.add(jLabel2, null);
      void jButton1_actionPerformed(ActionEvent e){
            jTextArea1.setText("Refreshing...");
            long i = 0;
         try{
              jTextArea1.setText("In side try block");
                    Thread.sleep(1000);
                   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                   jTextArea1.setText("DriverManager");
                  Connection conn=
                   DriverManager.getConnection("jdbc:oracle:thin:@machine:1234:"+ database, user, password);
                                                                          jTextArea1.setText("Got COnnection");
                   Statement stmt = conn.createStatement();
                   jTextArea1.setText("Statement Created");
                   ResultSet rs =
                   stmt.executeQuery("select 1, sysdate, sysdate, sysdate, sysdate, sysdate from dual ");
                   jTextArea1.setText("Query Executed");
                   while(rs.next()){
          jobid = rs.getInt(1);
          StartTime = rs.getString(2);
          LastReport = rs.getString(3);
          FinishTime = rs.getString(4);
          Description = rs.getString(5);
          job_position = rs.getString(6);
          desc = "<b>Count: </b>" + counter + "" +
                     "<p><table border = '1'><tr><td><b>JOB ID:      </b></td><td>" + jobid + "</td></tr>" +
                 "<tr><td><b>Start Time:  </b></td><td>" + StartTime + "</td></tr>" +
                 "<tr><td><b>Last Report: </b></td><td>" + LastReport + "</td></tr>" +
                 "<tr><td><b>FinishTime:  </b></td><td>" + FinishTime + "</td></tr>" +
                 "<tr><td><b>Description: </b></td><td>" + Description + "</td></tr>" +
                 "<tr><td><b>Position:    </b></td><td>" + job_position + "</td></tr></table>";
                  counter = counter + 1;
                     rs.close();
                   conn.close();
                    jTextArea1.setText("Sleeping");
                    jTextArea1.setText(desc);
                    desc = "";
              catch (SQLException se){
              jTextArea1.setText(desc + se);
           catch(Exception ee){
                jTextArea1.setText("Exception occured\n\n" + ee);
    }

    Get your basics checked.
    Go to:
    http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/shortcourse.html#whatAreLMs
    And find the heading: FlowLayout Variations
    FlowLayout can be customized at construction time by passing the
    constructor an alignment setting:
    FlowLayout.CENTER (the default)
    FlowLayout.RIGHT
    FlowLayout.LEFT

  • Adjust position and size of textField and button...

    Dear All,
    I have the following sample program which has a few textFields and a button, but the positions are not good. How do I make the textField to be at the right of label and not at the bottom of the label ? Also how to adjust the length of textField and button ? The following form design looks ugly. Please advise.
    import javax.swing.*; //This is the final package name.
    //import com.sun.java.swing.*; //Used by JDK 1.2 Beta 4 and all
    //Swing releases before Swing 1.1 Beta 3.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    public class SwingApplication extends JFrame {
    private static String labelPrefix = "Number of button clicks: ";
    private int numClicks = 0;
    String textFieldStringVEHNO = "Vehicle No";
    String textFieldStringDATEOFLOSS = "Date of Loss";
    String textFieldStringIMAGETYPE = "Image Type";
    String textFieldStringIMAGEDESC = "Image Description";
    String textFieldStringCLAIMTYPE = "Claim Type";
    String textFieldStringSCANDATE = "Scan Date";
    String textFieldStringUSERID = "User ID";
    String ImageID;
    public Component createComponents() {
    //Create text field for vehicle no.
    final JTextField textFieldVEHNO = new JTextField(5);
    textFieldVEHNO.setActionCommand(textFieldStringVEHNO);
    //Create text field for date of loss.
    final JTextField textFieldDATEOFLOSS = new JTextField(10);
    textFieldDATEOFLOSS.setActionCommand(textFieldStringDATEOFLOSS);
    //Create text field for image type.
    final JTextField textFieldIMAGETYPE = new JTextField(10);
    textFieldIMAGETYPE.setActionCommand(textFieldStringIMAGETYPE);
    //Create text field for image description.
    final JTextField textFieldIMAGEDESC = new JTextField(10);
    textFieldIMAGEDESC.setActionCommand(textFieldStringIMAGEDESC);
    //Create text field for claim type.
    final JTextField textFieldCLAIMTYPE = new JTextField(10);
    textFieldCLAIMTYPE.setActionCommand(textFieldStringCLAIMTYPE);
    //Create text field for scan date.
    final JTextField textFieldSCANDATE = new JTextField(10);
    textFieldSCANDATE.setActionCommand(textFieldStringSCANDATE);
    //Create text field for user id.
    final JTextField textFieldUSERID = new JTextField(10);
    textFieldUSERID.setActionCommand(textFieldStringUSERID);
    //Create some labels for vehicle no.
    JLabel textFieldLabelVEHNO = new JLabel(textFieldStringVEHNO + ": ");
    textFieldLabelVEHNO.setLabelFor(textFieldVEHNO);
    //Create some labels for date of loss.
    JLabel textFieldLabelDATEOFLOSS = new JLabel(textFieldStringDATEOFLOSS + ": ");
    textFieldLabelDATEOFLOSS.setLabelFor(textFieldDATEOFLOSS);
    //Create some labels for image type.
    JLabel textFieldLabelIMAGETYPE = new JLabel(textFieldStringIMAGETYPE + ": ");
    textFieldLabelIMAGETYPE.setLabelFor(textFieldIMAGETYPE);
    //Create some labels for image description.
    JLabel textFieldLabelIMAGEDESC = new JLabel(textFieldStringIMAGEDESC + ": ");
    textFieldLabelIMAGEDESC.setLabelFor(textFieldIMAGEDESC);
    //Create some labels for claim type.
    JLabel textFieldLabelCLAIMTYPE = new JLabel(textFieldStringCLAIMTYPE + ": ");
    textFieldLabelCLAIMTYPE.setLabelFor(textFieldCLAIMTYPE);
    //Create some labels for scan date.
    JLabel textFieldLabelSCANDATE = new JLabel(textFieldStringSCANDATE + ": ");
    textFieldLabelSCANDATE.setLabelFor(textFieldSCANDATE);
    //Create some labels for user id.
    JLabel textFieldLabelUSERID = new JLabel(textFieldStringUSERID + ": ");
    textFieldLabelUSERID.setLabelFor(textFieldUSERID);
    Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", "Andrews",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    final JLabel label = new JLabel(labelPrefix + "0 ");
    JButton buttonOK = new JButton("OK");
    buttonOK.setMnemonic(KeyEvent.VK_I);
    buttonOK.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
              try {
    numClicks++;
              ImageID = textFieldVEHNO.getText() + textFieldDATEOFLOSS.getText() + textFieldIMAGETYPE.getText();
    label.setText(labelPrefix + ImageID);
              ScanSaveMultipage doScan = new ScanSaveMultipage();
              doScan.start(ImageID);
         catch (Exception ev)
    label.setLabelFor(buttonOK);
    * An easy way to put space between a top-level container
    * and its contents is to put the contents in a JPanel
    * that has an "empty" border.
    JPanel pane = new JPanel();
    pane.setBorder(BorderFactory.createEmptyBorder(
    20, //top
    30, //left
    30, //bottom
    20) //right
    pane.setLayout(new GridLayout(0, 1));
         pane.add(textFieldLabelVEHNO);
         pane.add(textFieldVEHNO);
         pane.add(textFieldLabelDATEOFLOSS);
         pane.add(textFieldDATEOFLOSS);
         pane.add(textFieldLabelIMAGETYPE);
         pane.add(textFieldIMAGETYPE);
         pane.add(textFieldLabelIMAGEDESC);
         pane.add(textFieldIMAGEDESC);
         pane.add(textFieldLabelCLAIMTYPE);
         pane.add(textFieldCLAIMTYPE);
         pane.add(textFieldLabelDATEOFLOSS);
         pane.add(textFieldDATEOFLOSS);
         pane.add(textFieldLabelUSERID);
         pane.add(textFieldUSERID);
    pane.add(buttonOK);
         pane.add(table);
    //pane.add(label);
    return pane;
    public static void main(String[] args) {
    try {
    UIManager.setLookAndFeel(
    UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) { }
    //Create the top-level container and add contents to it.
    JFrame frame = new JFrame("SwingApplication");
    SwingApplication app = new SwingApplication();
    Component contents = app.createComponents();
    frame.getContentPane().add(contents, BorderLayout.CENTER);
    //Finish setting up the frame, and show it.
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);

    Post Author: Ranjit
    CA Forum: Crystal Reports
    Sorry but, i've never seen formula editor for altering position and size. If you know one please navigate me.
    I guess you have updated formula editor beside "Lock size and position" - if yes its not right. There is only one editor beside 4 items and editor is actually for Suppress.
    Anyways, A trick to change size a position is:
    Create 4-5 copies (as many as you expect positions) of the text object. place each at different positions,  right click, Format, Suppress and in formula editor for suppress write the formula: If your condition is true, Suppress=false, else true.
    Position will not change but user will feel; for different conditions -position is changed
    Hope this helps.
    Ranjit

  • "relative" positioning of buttons in a JFrame

    I want to draw an image as a background on a JFrame and then position several buttons in the frame such that when the frame is resized, the background is resized and the buttons remain "over" the same thing in the background image. I've tried to "do the right thing" and use a layout manager to position the buttons, but they just don't seem to behave like I need them to.
    Is there an easy way to get a button to appear at e.g. 70% horizontally across the frame and 40% down the frame? And then when I resize, have the button still be 70% across and 40% down (based on the new size of the frame). Or should I just give up on the layout managers, and calculate my own absolute positions for everything?
    Thanks

    Check this out:
    import javax.swing.*;
    import java.awt.*;
    public class CompassButtons extends JFrame {
      JButton nb = new JButton("North");
      JButton sb = new JButton("South");
      JButton eb = new JButton("East");
      JButton wb = new JButton("West");
      JViewport viewport = new JViewport();
      public CompassButtons() {
        super("SpringLayout Compass Demo");
        setSize(500,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        SpringLayout sl = new SpringLayout();
        Container c = getContentPane();
        c.setLayout(sl);
        int offset = 50;  // gap between buttons and outside edge
        int w      = 80;  // width of buttons
        int h      = 26;  // height of buttons
        int border =  3;  // border around viewport
        Spring offsetS     = Spring.constant(offset);
        Spring borderS     = Spring.constant(border);
        Spring widthS      = Spring.constant(w);
        Spring halfWidthS  = FractionSpring.half(widthS);
        Spring heightS     = Spring.constant(h);
        Spring halfHeightS = FractionSpring.half(heightS);
        Spring leftEdgeS   = sl.getConstraint(SpringLayout.WEST, c);
        Spring topEdgeS    = sl.getConstraint(SpringLayout.NORTH, c);
        Spring rightEdgeS  = sl.getConstraint(SpringLayout.EAST, c);
        Spring bottomEdgeS = sl.getConstraint(SpringLayout.SOUTH, c);
        Spring xCenterS    = FractionSpring.half(rightEdgeS);
        Spring yCenterS    = FractionSpring.half(bottomEdgeS);
        Spring leftBorder  = Spring.sum(leftEdgeS, borderS);
        Spring topBorder   = Spring.sum(topEdgeS, borderS);
        Spring northX = Spring.sum(xCenterS, Spring.minus(halfWidthS));
        Spring southY = Spring.sum(bottomEdgeS, Spring.minus(Spring.sum(heightS,
                                                                        offsetS)));
        Spring eastX = Spring.sum(rightEdgeS, Spring.minus(Spring.sum(widthS,
                                                                      offsetS)));
        Spring eastY = Spring.sum(yCenterS, Spring.minus(halfHeightS));
        c.add(nb, new SpringLayout.Constraints(northX, offsetS, widthS, heightS));
        c.add(sb, new SpringLayout.Constraints(northX, southY, widthS, heightS));
        c.add(wb);
        sl.getConstraints(wb).setX(offsetS);
        sl.getConstraints(wb).setY(eastY);
        sl.getConstraints(wb).setWidth(widthS);
        sl.getConstraints(wb).setHeight(heightS);
        c.add(eb);
        sl.getConstraints(eb).setX(eastX);
        sl.getConstraints(eb).setY(eastY);
        sl.getConstraints(eb).setWidth(widthS);
        sl.getConstraints(eb).setHeight(heightS);
        c.add(viewport); // this sets a bounds of (0,0,pref_width,pref_height)
        // The order here is important...need to have a valid width and height
        // in place before binding the (x,y) location
        sl.putConstraint(SpringLayout.SOUTH, viewport, Spring.minus(borderS),
                         SpringLayout.SOUTH, c);
        sl.putConstraint(SpringLayout.EAST, viewport, Spring.minus(borderS),
                         SpringLayout.EAST, c);
        sl.putConstraint(SpringLayout.NORTH, viewport, topBorder,
                         SpringLayout.NORTH, c);
        sl.putConstraint(SpringLayout.WEST, viewport, leftBorder,
                         SpringLayout.WEST, c);
        ImageIcon icon = new ImageIcon("images/terrain.jpg");
        viewport.setView(new JLabel(icon));
        // Hook up the buttons.  See the CompassScroller class (on-line) for details
        // on controlling the viewport.
        nb.setActionCommand(CompassScroller.NORTH);
        sb.setActionCommand(CompassScroller.SOUTH);
        wb.setActionCommand(CompassScroller.WEST);
        eb.setActionCommand(CompassScroller.EAST);
        CompassScroller scroller = new CompassScroller(viewport);
        nb.addActionListener(scroller);
        sb.addActionListener(scroller);
        eb.addActionListener(scroller);
        wb.addActionListener(scroller);
        setVisible(true);
      public static void main(String args[]) {
        new CompassButtons();
    }Copyright 2003, O'Reilly & Associates
    Provided as example.
    Cheer
    DB

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

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

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

  • JLabel text hidden behind another component in GridBagLayout

    Hi everyone
    I have looked for an answer to this but come up short so here I am.
    I am using GridBagLayout to position some Jlabels and a JScrollPane
    I have a JLabel in gridx = 0 and gridy = 0 which spans 2 columns
    under that in gridx = 0, gridy = 1 I have a JList inside a JScrollPane
    it only spans the 1 column but fills the entire column.
    next to this in gridx = 1, gridy = 1 I have a JLabel which should fill the rest of the row. It does this but the text is hidden behind the JScrollPane.
    I have tried changing the fill to REMAINING but then the label does not fill the required area.
    Any ideas why this is happening and how to fix it
    my code is
    contents = (JPanel) getContentPane();
    tabbedPane = new JTabbedPane();
    panel = new JPanel();
    panel.setLayout(gridbag);
    //left hand side
    label = new JLabel("Video Database System",JLabel.CENTER);
    gridConstraints.gridx = 0;
    gridConstraints.gridy = 0;
    gridConstraints.gridwidth = 2;
    gridConstraints.weightx = panel.getWidth() * 0.3;
    gridConstraints.weighty = 0.03;
    gridConstraints.anchor = GridBagConstraints.NORTH;
    gridConstraints.fill = GridBagConstraints.BOTH;
    gridbag.setConstraints(label,gridConstraints);
    label.setOpaque(true);
    label.setBackground(Color.blue);
    label.setFont(boldFont);
    panel.add(label);
    //scrolling list
    list = new JList(FileAccess.titleDVD);
    scrollPane = new JScrollPane(list);
    gridConstraints.gridx = 0;
    gridConstraints.gridy = 1;
    gridConstraints.weightx = 0.3;
    gridConstraints.weighty = 0.7;
    gridConstraints.gridheight = 7;
    gridConstraints.anchor = GridBagConstraints.WEST;
    gridConstraints.fill = GridBagConstraints.VERTICAL;
    gridbag.setConstraints(scrollPane,gridConstraints);
    panel.add(scrollPane);
    //labels in the right hand side, this is the label where the text becomes hidden
    label = new JLabel("TITLE",JLabel.LEFT);
    gridConstraints.gridx = 1;
    gridConstraints.gridy = 1;
    gridConstraints.weighty = 0.7;
    gridConstraints.weightx = 0.9;
    gridConstraints.anchor = GridBagConstraints.NORTH;
    gridConstraints.fill = GridBagConstraints.HORIZONTAL;
    gridbag.setConstraints(label,gridConstraints);
    label.setOpaque(true);
    label.setBackground(Color.yellow);
    panel.add(label);
    tabbedPane.add(panel,"Video Information");
    Thanks

    import java.awt.*;
    import javax.swing.*;
    public class hugh extends JFrame {
      public hugh() {
        JPanel tabPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        JLabel topLabel = new JLabel("Video Database System", JLabel.CENTER);
        topLabel.setOpaque(true);
        topLabel.setBackground(Color.pink);
        topLabel.setPreferredSize(new Dimension(275,20));
        gbc.gridwidth = 2;
        tabPanel.add(topLabel, gbc);
        JPanel scrollPanel = new JPanel();
        scrollPanel.setBackground(Color.red);
        scrollPanel.setPreferredSize(new Dimension(375,300));
        scrollPanel.add(new JLabel("JList goes here . . ."));
        JScrollPane scrollPane = new JScrollPane(scrollPanel);
        scrollPane.setPreferredSize(new Dimension(200,300));
        gbc.gridy = 1;
        gbc.gridwidth = gbc.RELATIVE;
        tabPanel.add(scrollPane, gbc);
        JLabel sideLabel = new JLabel("TITLE", JLabel.CENTER);
        sideLabel.setOpaque(true);
        sideLabel.setBackground(Color.pink);
        sideLabel.setPreferredSize(new Dimension(75,20));
        gbc.gridwidth = gbc.REMAINDER;
        tabPanel.add(sideLabel, gbc);
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Video Information", tabPanel);
        getContentPane().add(tabbedPane);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400,400);
        setLocation(400,300);
        setVisible(true);
      public static void main(String[] args) {
        new hugh();
    }

  • Positioning objects in a JTabbedPane

    Is the any way to specify the positioning of an object in a JTabbedPane?
    I am placing JPanels which contain JLabels and JTextFields into tabs
    of a JTabbedPane. All the panels are centered in the tab panes.
    This is annoying because one panel contains more labels and fields than
    the others. As result some of the data on the smaller panels isn't visible without scrolling.
    Is there some way to orient all panes NORTHWEST ? So when a user selects a tab the data is visible.
    It seems to me it would be done when adding the tabs (.addTab())
    but I can't figure out how.
    I tried grigBag.setConstraints(jtp, gridBagConstraints) where jtp
    is the tabbed pane. But it did not work.
    Is this just the way the JTabbedPane works ?
    TIA

    Looks to me like you are using FlowLayout - this is the default for JPanels. FlowLayout is a pain in the thingimybob. Try using a more suitable layout manager (e.g. BorderLayout).
    This applies both to to the container you're putting the JTabbedPane into, and the JPanels you're putting within the JTabbedPane.
    You can set the layout when you create a container, for example...
    JPanel panel = new JPanel(new BorderLayout() );
    JTabbedPane tabs = new JTabbedPane();
    panel.add(tabs, "Center");Hope this helps!
    Regards,
    Tim

  • Positioning of objects

    i have a JDialog and want to position the components so that they pass exactly . for example i have a JLabel but only part of it seen ,
    should i give the size of any component maually
    the other problem is that the user should be able to enter data in JTextfield but only figures , how can i forbid entering of figures
    thanks in advance

    Do you know how can i set the size of the objects
    .setSize(new Dimension(x, y))and look at
    .setMinimumSize()
    .setMaximumSize()
    how can i set the JDialog unresizable ?Look at http://java.sun.com/j2se/1.4.1/docs/api/java/awt/Dialog.html#setResizable(boolean)

Maybe you are looking for

  • Segment fault (Core dump)

    Hi when i run the following Pro*c file in Unix Environment im getting the SEGMENTATION FAULT(CORE DUMP) error. I used DBX to debug the code. I couldnt find out the proper reason for this error form the dbx output. This is the output i got from DBX. *

  • Data Manager Packeage and Process chain si not working

    Hi All, I executed a data manager package which contain a process chain to revaluate the one of my Account dimension meneber Say  "Revenue". I am working on BPC NW 7.0 steps I followed: 1. I created a script logic file and created a custom process ch

  • Exchange 2013 MB/CAS integration with legacy Exchange 2007 CAS/MB/Trans server

    Hi All, I have an existing running Exchange 2007 SP3 RU13 server acting as MB,CAS,Transport using a Barracuda SPAM for SMTP (MX Record is assigned to here), and a TMG2010 server performing all ActiveSync, Outlook Anywhere, and OWA connectivity. I hav

  • Mail app crashes when receiving email from a particular sender

    HI All, Here is a problem I'm facing, Mail App crashes while receiving email from a particular sender. I'm testing our new Email Hosting solution "Rackspace" and it works fine with all other Email clients or on deveices (Android, Windows Phone & Blac

  • How to download the datas of ALV tree without passing iternal table

    Hi,   I want to download the values of ALV tree output in an Excel file without using any internal table. Please suggest your thoughts on the same. Regards, Shasiraj.C Edited by: Raj Shasi on Aug 1, 2008 8:44 AM