Problem with JLabel width

Well, the subject is quite clear.
I created a JLabel, and when I wanna know what its width is, 0 is returned.
This is the code, which is really simple :
import javax.swing.JLabel;
import javax.swing.JFrame;
public class Essai extends JFrame{
public Essai(){
JLabel j = new JLabel("hello");
this.getContentPane.add(j);
System.out.println(j.getWidth());
this.show();
public static void main(String[] args){
Essai essai1 = new Essai();
Well, I really need the width of the component, so, could somebody help me ?
I thank you all for having read my post.
have a good day

Hi,
You should call getPreferredSize to get the size of the label. PreferredSize is the width and height that the label thinks it should be and is what the layout manager will request of it to perform its' layout. The size is the actual size that the layout manager will assign to the label and is not valid until the layout manager is done managing (after show or pack are called).
Regards,
Manfred.

Similar Messages

  • Having problems with texts width when viewed in Firefox

    I My site is OK when viewed in Chrome and Safari, but in Firefox, the width of paragraphs is becoming very long and all is displayed wrong.
    I need a clue where to look to fix. I have not , or very little knowledge of HTML code. So I rely on the DW CS5 interface.
    Thanks,D.

    Thanks Nancy ,
    I'll try,
    Should I just paste your info between the brackets, I guess.
    I am not so good with this but I need to spent a bit of time to fix this
    old web site while another one is being designed.
    Yes the images are too big, I'll reduce them, and optimize. This was
    done in a rush..
    D.
    Le 14-02-23 18:07, Nancy O. a écrit :
    >
          Re: Having problems with texts width when viewed in Firefox
    created by Nancy O. <http://forums.adobe.com/people/Nancy+O.> in
    /Dreamweaver support forum/ - View the full discussion
    <http://forums.adobe.com/message/6149874#6149874

  • Problem with chart width

    Hi all,
    I have a problem with a chart.
    I show a columnChart at 100% width.
    The dataprovider is hierarchic. So every object in it has a 'children' property which is a new ArrayCollections.
    This way, I'm able to descend in the hierarchy by scripting this:
    targetChart.dataProvider = myClickedItem.children;
    All works perfect except that the larger the dataset is, the narrower my chart displays.
    This is what it looks like (from left to right, the several levels of the chart):
    This is the mxml code I use:
    <mx:ColumnChart id="targetChart" width="100%" height="100%"
                                                      dataProvider="{targetProvider}" showDataTips="true"
                                                      itemClick="targetChart_itemClickHandler(event)"
                                                      type="{statStyle}">
      <mx:horizontalAxis>
                                       <mx:CategoryAxis categoryField="label"/>
      </mx:horizontalAxis>
      <mx:series>
                                  <mx:ColumnSeries yField="total" width="100%"
                                                                           fillFunction="getTotalFill"
                                                                           displayName="Totaal ovsg"
                                                                           showEffect="zoom" hideEffect="zoom"/>
                                  <mx:ColumnSeries yField="count" width="100%"
                                                                           fill="{Config.CHART_COLOR_ARRAY.getItemAt(0) as IFill}"
                                                                           displayName="Telling"
                                                                           showEffect="zoom" hideEffect="zoom"/>
      </mx:series>
      </mx:ColumnChart>
    Any help would be appreciated.
    Dany

    Hi,
    Did you solve this issue?
    I have the same problem, maybe you can help if you got the answer?

  • Apache FOP Problem with column width

    We are using Apache FOP to generate simple pdf documents out of reports.
    My problem is that the table in the pdf is as standard filled in with columns of same length.
    Further on the content of some table fields is to large or sometimes there is to much room.
    is there any possiblity to let fop react like html?
    The smallest table field size should be like the content. I don't want to adjust all my reports, cause there are really many reports with pdf printing.
    anyone an idea how to solve this with FOP?
    i have no BI pubisher or other reporting engines for this problem
    thx so far

    Oliver,
    I think what you're looking for is having your column width automatically adjusted based on the content of your column values. That is not possible with the built-in, generic XSL-FO template. What you can do is manually adjusting the column width to appropriate values on the print attributes page.
    Regards,
    Marc

  • Displaying dynamically changing image: a problem with JLabel.

    Hello! I use NetBeans 5.5 and I develop my GUI with Matisse. I'm rather a beginner in developing GUIs with this editor...
    I'd like to display a dynamically changing image. The idea is: GUI shows the image, that is modified as some computations run in a different thread. App will be run on a single machine.
    I'm trying to display the image as a label's icon. The problem is that my app's frame can be resized - and when it is, the label also resizes. When the label is resized, the image should also be resized - the image should always be of the same size as the label. The problem? I noticed, that it works only when I make my app's bigger. When I try to lower its dimensions, the label's dimensions remain the same. Why the label don't make its size smaller?
    My code works as follows: when app's main frame is resize, the panel (the one, that the label is placed in) is also resized. And, since the label is in the panel, it (should) also be resized. So I wrote all the resize-events handlers (therefore I know that the resize event is sent when my app's frame is resized, and when the panel is resized - but the label is resized only when it grows bigger). In this methods I modify the image displayed in the label (I resize the image).
    Or, perhaps, there is some other way to show a (dynamically changing) image with Swing... I chose JLabel, because I didn't want to write my own JComponent. JLabel can display image and that is all I need. The problem is: when the label grows bigger, I create a new, bigger image (icon). Why my label don't get smaller (the resize event isn't even sent)?

    There is no component that dynamically resizes an image. You need to create your own. Something like this:
    JComponent component = new JComponent()
         protected void paintComponent(Graphics g)
              //  Scale image to size of component
              g.drawImage(yourImage, 0, 0, getWidth(), getHeight(), null);
    };

  • Problem with the WIDTH & HEIGHTS in GetFeatureInfo-Requests

    Hi
    I have a problem regarding the GetFeatureInfo-Requests.
    If I make a GetFeatureInfo-Request with the parameters 'WIDTH=2&HEIGHT=2, then returns the following error massage:
    <?xml version = '1.0' encoding = 'UTF-8'?>
    <!DOCTYPE ServiceExceptionReport SYSTEM
    "http://schemas.opengis.net/wms/1.1.1/WMS_exception_1_1_1.dtd">
    <ServiceExceptionReport version="1.1.1">
    <ServiceException>
    <![CDATA[<oms_error>
    <![CDATA[
    OMS: ORA-00904: "NAN": ungültiger Bezeichner
    ]]>
    </oms_error>]]>
    </ServiceException>
    </ServiceExceptionReport>
    With the following parameters, the call executed correctly, 'WIDTH=3&HEIGHT=3'.
    This fault occurs only at the GetFeatureInfo-Request. The getMap-Request with the same parameter 'WIDTH=2&HEIGHT=2' provides an image and not an error.
    Example:
    MapViewer - GetMap-Request
    http://10.233.97.9/mapviewer/wms?
    REQUEST=getMap&
    Version=1.1.1&
    LAYERS=AT_TN_ACS_SIEDLUNG&
    SRS=EPSG:31468&
    bbox=4420806,5395201,4420838,5395233&
    FORMAT=image/png&
    WIDTH=2&
    HEIGHT=2&
    TRANSPARENT=false&
    STYLES=&
    Datasource=igvert_alkis&
    MapViewer - GetFeatureInfo-Request
    http://10.233.97.9/mapviewer/wms?
    request=GetFeatureInfo&
    Version=1.1.1&
    LAYERS=AT_TN_ACS_SIEDLUNG&
    QUERY_LAYERS=AT_TN_ACS_SIEDLUNG&
    SRS=EPSG:31468&
    bbox=4420806,5395201,4420838,5395233&
    FORMAT=image/png&
    WIDTH=3&
    HEIGHT=3&
    TRANSPARENT=false&
    STYLES=&
    Datasource=igvert_alkis&
    INFO_FORMAT=application/vnd.ogc.gml&
    X=1&
    Y=1&
    FEATURE_COUNT=20&
    MapViewer-Version: Ver11_B100426
    Who can help?
    Best Regards
    Kerstin

    Hi,
    I have filed an SR before I posted it on OTN. Therefore, an SR already exists. But the support has advised me to post the problem here.
    Regards
    Kerstin

  • Problems with line widths smaller that 1 pt in Illustrator CS3 in Spanish

    I am asking this for a friend who doesn't speak English; I don't work in Illustrator and don't even know the program. She is using Illustrator CS3 in Spanish under Windows XP Service Pack 2 also in Spanish in a machine with 4 GB RAM and 500 GB HD. As in many non English speaking countries, the decimal separator in Spanish speaking countries is the comma (,), not the point (.).
    Her problem is related with applying line widths smaller that 1 pt using the dropdown list of values. Values smaller that 1 pt appear in the list with a point, not a comma, as separator: 0.25 pt, 0.50 pt and 0.75 pt instead of the expected 0,25 pt, 0,50 pt and 0,75 pt. This wouldn't matter at all; the problem is that trying to apply any of these values resuls in 1 pt wide lines. She has made a video (less than one minute) that explains the situation much better than I could do:
    http://es.tinypic.com/usermedia.php?uo=AE87RzhYHCdn5HPHtpPkoA%3D%3D
    Curiously, if she introduces values by hand, they are accepted in these two forms: 0,25 pt, and 1/4 pt, and applied correctly, both showing as 0,25 pt (not 0.25 pt).
    Of course she can introduce values by hand every times she needs thin lines, but this is a wokaround, not a solution to her problem. Which is aggravated by the fact that she constantly has to use the thiner lines.
    In desperation, she reinstalled Illustrator CS2, where the problem does not exist and everything works as expected. But she needs the new features in CS3.
    I apologize if this is a known issue with a known solution, but I couldn't find anything about it in the FAQs, and after a couple of searches and wading through several pages of the topic list of this forum.

    Back to report. I suggested to my friend to try Jacob's idea first, as it was the easier and fastest. However, I also suggested a small change, due to the following. As the dropdown list was already showing points as decimal separators, I thought it might be better not to change the language. I suggested instead to customize the settings for numbers in her chosen Spanish, changing the decimal separator from the comma to the point, and the thousands separator from the point to the comma.
    She has just reported that she changed the language from Spanish to English, and then back to Spanish; and then she customized the separators as I had suggested. That did it; with this change, she can apply the smaller widths using the dropdown list, and she is so happy with her success, that she isn't going to try James's suggestion for the time being, although she may do it later on.
    By the way, my friend lives in another country and we are communicating through the Forums in Spanish. This explains why communications have been very slow, and also why I don't know if she shifted from Spanish to English and back to Spainsh because this made no difference, or for some other reason. In any case, she asked me to thank very heartly Jacob and James for their help.

  • Problems with auto widths - Safari, IE

    http://www.spoc-ortho.com/test_jn.html
    What am I doing wrong?
    1. In Safari, all of the submenus except for "Employment"
    have a one-line gap between the main menu bar and submenus.
    2. I followed the directions at
    http://livedocs.adobe.com/en_US/Spry/1.4/help.html?content=WS0BB04E11-1BE3-4a67-BC94-BE7DA 93A0159.html
    to change from fixed-width to auto width, but now in IE 7 the menus
    don't drop down at all but instead are jumbled together with extra
    content on the right side of the page. If IE 7 gets it this badly,
    I don't even want to consider IE6...
    Project is due Thursday end-of-day (4/10/08)... I've spent
    three days messing around with this and am getting nowhere.

    I am sorry, but you have changed the CSS beyound recognition; I do not want to spend my time going through it to correct it.
    One example that has angered me is
    BROWSER HACKS: the hacks below should not be changed unless you are an expert
    /* HACK FOR IE: to make sure the sub menus show above form controls, we underlay each submenu with an iframe */
    ul.MenuBarVertical iframe
        position: absolute;
        z-index: 1010;
        filter:alpha(opacity:0.1);
        margin: 0;
        padding: auto;
        list-style-type: katakana;
        font-size: 100%;
        cursor: default;
        width: 13em;
        border-top-color: #edeeee;
        border-top-style:groove;
        border-bottom-color:#313132;
            border-bottom-style:groove;
        border-left-color:#cbcccd;
            border-left-style:groove;
        border-right-color:#3d3d3e;
        border-right-width: thin;
            border-right-style:groove;
    Changing this has not made you an expert
    Another example on or about line 155 is this line which is sure to upset the browser.
    ul.MenuBarVertical a:focus
    Yet another one
    /* Submenu that is showing with class designation MenuBarSubmenuVisible, we set left to 0 so it comes onto the screen */
    ul.MenuBarVertical ul.MenuBarSubmenuVisible
       left: -11px;
        border-top-color: #edeeee;
        border-top-style:groove;
        border-bottom-color:#313132;
        border-bottom-style:solid;
            border-bottom-style:groove;
        border-left-color:#cbcccd;
            border-left-style:groove;
        border-right-color:#3d3d3e;
        border-right-width: thin;
            border-right-style:groove;
    I suggest you start with a new widget, but before you do, read this http://www.dwcourse.com/dreamweaver/ten-commandments-spry-menubars.php#one
    Gramps

  • Problem with Jlabel

    Dear All,
    Please, is anybody could advise what's wrong with the following code?
    loading.setText("loading...");
    loading.setVisible(true);
    launchProc(fields_array,cp, conn_string, username_, password_);
    loading.setText("completed.");the loading JLabel is not displayed till launchProc method has finished, what could be the reason?
    I wanted to display "loading..." string to show the actual status and then when the actual operation finishes display "completed" as actual status.
    Please, is there any other way to do it?
    Thanks and Regards,
    Tewfik

    Hard to say without knowing the rest of your code, but let me take a guess here... you are probably invoking those commands from the AWTEventThread (you could test that by adding System.out.println(Thread.currentThread().getName()); to your program). What happens is the setVisible(boolean) command is dispatched and added to the AWT queue, however, the thread responsible for actually drawing your JLabel is then trapped in the launchProc method, causing your entire gui to freeze. You will have to launch your process in another Thread if you want to prevent that.

  • Problems with the width of my page created in adobe muse (scrolled)

    I have a little problem I get a small scroll (scrolled) in the page to move sideways and do not know how to remove it and do not know why I get and I spoil that little scroll whole layout of the page. Please watch this short video and live shows.
    Video: http://screencast.com/t/D9Qz4w8bq
    Web: http://pruebabub.net23.net/

    I think this is a bug in the new update. I have made numerous sites since and all of them have gotten the horiztonal scroll. I mentioned it in the bug section and had a staff member help me with my first issue but have not heard anything else since.
    This is a pretty serious bug, you can not launch a website with a horizontal scroll like this.
    on another note, I really like the look of your site, very slick so far!

  • Problem with JLabel mousePressed()

    Hello
    I want to display the name like a html look in the JPanel and acts like a button function. So I have used JLabel and gave mousePressed() but its not providing any action out of it.
    In previous forms, I had seen JLabel is only for display and not for any actions. So how can I get the actionPerformed() functionality.
    Please try to update me soon
    Thanks

    Try this
    import java.awt.FlowLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    * @author Administrator
    public class YourClass extends JFrame{
      /** Creates a new instance of yourClass */
      public YourClass() {
        JLabel myLabel = new JLabel("click me");
        super.setLayout(new FlowLayout());
        super.add(myLabel);
        myLabel.addMouseListener(new MouseAdapter(){
          public void mousePressed(MouseEvent e) {
            System.out.println("clicked!");
      public static void main(String args[]) {
        YourClass test = new YourClass();
        test.pack();
        test.setVisible(true);
    }

  • Problem with width tool in illustrator cc

    hello!
    i used to use illustrator cs5 and had no problems with the width tool. now that i am using adobe CC, the width tool functions very oddly and the cursor points are bizarre. for example, i use to just hover over the exact width point and could easily access handlebars or move it. however, in CC, i have to hover a little further away in order to get the ~ symbol to show. PLEASE HELP. this is driving me bonkers and the rate at which i'm working is quite delayed. THANK YOU!!!

    Without proper system info and other details nobody can tell you anything.
    Mylenium

  • Problem with IE Vertical Menu Bar Widths

    I currently have a Vertical Menu Bar with the width set to
    auto. IE shows all of the top-level menu items as a single
    word-wrapped line.
    When you hover over any submenu item, the border that appears
    on hover only spans the width of that submenu item's text rather
    than the width of the actual submenu.
    Is there a way to use auto widths in IE or will I just have
    to use predetermined widths?
    My URL is
    http://www.plpimports.com/
    Thanks!!

    I changed the layout so that the menu is fixed width. I think
    I like it better this way anyway.

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Problem with a template method in JDialog

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

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

Maybe you are looking for