JFrame or AWT Container Listener

Hi,
i have created a window with below components
1) JComboBox
2) Radio Button Group( it holds two buttons)
3) Date picker
and a JButton
my button will be in disabled state and on change of properties of any of above components like
on change of date
changing the selected radio button
changing the combo box selected item
i need to set the button enabled.
what the best way to do. i tried with action Listeners of both JFrame and Container. but could n't succeeded.
please point me to right way to do the same
Thanks in advance
R

Show us what you have tried and we'll see what's wrong. Post only relevant code, not your entire program.
{color:#0000ff}http://mindprod.com/jgloss/sscce.html{color}
db

Similar Messages

  • Java.awt.Container.add(Container.java:345) how can i handle this

    dear all,
    i want to design an outlook for a chat applet. but this seems to tough as i am getting a run time error
    my code is:
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    * the import that are required for this class
    public class outer extends Frame //implements ActionListener, Runnable
    private TextField txtusername,txtpassword,txtroomname;
    private Label lblusername,lblpassword,lblroomname,lbllistofrooms;
    Button okBtn,exitBut;
    Color backColor=null,btnBackClr=null,btnForeClr=null;
    String[] roomsavailable = {" one ", " two ", " three", " four"};
    private JList rooms = new JList(roomsavailable);
    /** the costructor*/
    public outer()
    { // super(st);
    backColor=new Color(200,200,255);
    btnBackClr=new Color(225,240,255);
    btnForeClr=new Color(205,205,205);
    setBackground(backColor);
    setLayout(null);
    lblusername = new Label("Username");
    lblusername.reshape(insets().left+5,insets().top+10,60,20);
    add(lblusername);
    txtusername=new TextField();
    txtusername.reshape(insets().left+75,insets().top+10,60,20);
    add(txtusername);
    lblpassword = new Label("Password");
    lblpassword.reshape(insets().left+5,insets().top+30,60,20);
    add(lblpassword);
    txtpassword=new TextField();
    txtpassword.reshape(insets().left+75,insets().top+30,60,20);
    add(txtpassword);
    lblroomname = new Label("Select Room");
    lblroomname.reshape(insets().left+5,insets().top+50,60,20);
    add(lblroomname);
    txtroomname=new TextField();
    txtroomname.reshape(insets().left+75,insets().top+50,60,20);
    add(txtroomname);
    okBtn=new Button("Login");
    okBtn.reshape(insets().left+25,insets().top+80,60,20);
    add(okBtn);
    // okBtn.addActionListener(this);
    exitBut=new Button("EXIT");
    exitBut.reshape(insets().left+50,insets().top+80,60,20);
    add(exitBut);
    // exitBut.addActionListener(this);
    public static void main(String[] args)
    // Create a JFrame
    JFrame frame = new JFrame("client side");
    // Create a outer class object
    outer outerobj = new outer();
    // Add the outer to the JFrame
    frame.getContentPane().add(outerobj, BorderLayout.WEST);
    // Set Jframe size
    frame.setSize(800, 400);
    //set resizable true
    frame.setResizable(true);
    // Set JFrame to visible
    frame.setVisible(true);
    // set the close operation so that the Application terminates when closed
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    when i compile it it compiles but gives run time error like this
    RUN TIME error:
    Exception in thread "main" java.lang.IllegalArgumentException: adding a window
    to a container
    at java.awt.Container.addImpl(Container.java:434)
    at java.awt.Container.add(Container.java:345)
    at outer.main(outer.java:75)
    Press any key to continue...
    i know erroe in this line
    frame.getContentPane().add(outerobj, BorderLayout.WEST);
    but how shall i add to get the proper layout by getting benifit of insets method
    reply soon
    please

    You can't add a frame to a frame.
    Try chaing the class definition from
    public class outer extends Frameto
    public class outer extends PanelPlease note to format your code (you'll get a faster response) use [ code]
    Object names should always start with a capital letter. outer --> Outer

  • AWT Event Listener not listening...

    Hi,
    I'm having problems with an AWT Event Listener on a JFrame.
    Basically, im making a tank game, so the first screen to appear is an inventory screen. The when you click start on this screen, you create a GameScreen which extends JFrame. i have an AWT Event Listener added to this frame using this code:
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener(){
    public void eventDispatched(AWTEvent e) {
    if(((KeyEvent)e).getKeyCode() == KeyEvent.VK_DOWN && e.getID() == KeyEvent.KEY_PRESSED)
    It's checking events on the arrow keys and the tab and enter keys.
    So when the this round of the game has finished, i setVisible to false, and make the inventory visible again.
    The problem is, when i set make the GameScreen visible again, the listeners aren't working.
    It seems to be working fine for 'enter', that is VK_ENTER, but not for the arrow keys...
    Any1 have any ideas??
    Any help would be great!
    Thanks,
    D.

    I am willing to bet that your problem lies in that once you return the main game screen from the inventory screen that you need to set the focus back to the main game screen. I believe, as events go, the component that has the focus is the one that will receive the events and process them according to their listener code. As I am not sure where your focus goes once you close the inventory screen and open the main screen, it could be that the wrong component has the focus.
    As far as getting the focus to the correct component is concerned, I remember myself and Malohkan having a discussion as to how to get this to work, and he came up with a work-around. That thread is somewhere in this forum. I'm not sure if it will solve your problem, but it might be something worth looking into.
    -N.

  • How can i display multiple Pictures in a java.awt.Container best?

    hi,
    I just started with a new Project, it works just like a FileManager.
    On entering a directory all the files in it shall be displayed in a scrollable area. Displayed means here a Graphical representation of the file, in case of a picture a small preview version of it.
    I put together a javax.swing.JScrollPane with a java.awt.Container and viewport. The Container has a FlowLayout.
    Now for every image in a Directory I create a Component-class in witch I overwrote the public void paint(Graphics g) to display a scaled version of the image, this scaled version is created in the Constructor of my Component-class.
    this works fine for just a few images, but if i try to open a directory with a lot of pictures it takes a long time at the beginning and sometimes it just kills the application.
    so i changed in a way that only when a Component is in view of the visible rectangle of the scroll pane the scaled image will be created, and when the component gets out of view the image is set to null.
    now it is running without killing the application, but it takes way too long to scroll now, because the images are loaded all the time.
    so i figured i must be doing something wrong, so what is the best way to get small previews for up to a few hundred files and then display them in a scrollable area? (like in Windows Explorer if you activate the miniature preview)
    if anyone can give me some hints, that would be great
    thanks shirasuresh

    This might give you some ideas:
    import java.awt.*;
    import javax.swing.*;
    public abstract class LazyIcon implements Icon {
        private int width;
        private int height;
        private Image image;
        public LazyIcon(int width, int height) {
            this.width = width;
            this.height = height;
        protected abstract Image createImage();
        public int getIconHeight() {
            return width;
        public int getIconWidth() {
            return height;
        public void paintIcon(Component comp, Graphics g,int x, int y) {
            if (image == null)
                image = createImage();
            g.drawImage(image, x, y, comp);
    }You could also do this with a custom component class, but I like the JLabel + Icon combination.
    Any if you want to get fancy, you could load images in another thread, at low priority, so when the user is just sitting there, your code is preparing the panel for scrolling ;-)
    Message was edited by:
    BigDaddyLoveHandles

  • The method add() in java.awt.Container made me in confuse

    Here is my two java code file:
    //MyContainer.java
    package sam.gui;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JApplet;
    import javax.swing.JFrame;
    public class MyContainer extends JApplet {
         private MyButton[] myButton = new MyButton[2];
         private static int counter = 0;
         public MyContainer() {
              myButton[0] = new MyButton(5, 5, 200, 30);
              myButton[1] = new MyButton(5, 40, 200, 30);
              for (int i = 0; i < myButton.length; i++) {
                   add(myButton);
         public void paint(Graphics g) {
              for (int i = 0; i < myButton.length; i++) {
                   System.out.println("MyButton : " + (i+1));
                   myButton[i].draw(g);
         public static void main(String[] args) {
              MyContainer container = new MyContainer();
              JFrame f = new JFrame();
              f.getContentPane().add(container);
              f.pack();
              f.setSize(new Dimension(300, 200));
              f.show();
    //MyButton.java
    package sam.gui;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class MyButton extends Component {
         private Color m_rectColor = new Color(128, 73, 0);
         public MyButton(int x, int y, int width, int height) {
              setBounds(x, y, width, height);     
         public void draw(Graphics g) {
              Graphics2D g2 = (Graphics2D)g;
              g.setColor(m_rectColor);
              g.fillRect(0, 0,
                        getBounds().width, getBounds().height);
              System.out.println("x = " + getBounds().x);
              System.out.println("y = " + getBounds().y);
              System.out.println("width = " + getBounds().width);
              System.out.println("height = " + getBounds().height);          
    I thinked the runned result should be below:
    MyButton : 1
    x = 5
    y = 5
    width = 200
    height = 30
    MyButton : 2
    x = 5
    y = 40
    width = 200
    height = 30But in fact, its result is here:
    MyButton : 1
    x = 5
    y = 5
    width = 200
    height = 30
    MyButton : 2
    x = 0
    y = 0
    width = 292
    height = 173I don't know why the result would like this? I have used add(...) method to add two component MyButton to the container MyContainer, But the bounds of the second component is not I want.
    So this problem made me go into confuse.

    You need to learn how layout managers work. The default layout manager of a JApplet and JFrame is BorderLayout .
    /Kaj

  • Drawing images with transparent background on any AWT container control.

    I have an AWT applet with some background image.
    There is another image say of a size of an icon which
    has a transparent background. This image can be
    dragged anywhere on the applet.
    I am using a panel of a size of an icon and drawing the
    image on it. The whole panel is dragged when the user
    drags the image.
    The problem over here is, though the image has a
    transparent background it is not appearing transparent
    on the applet because the background of its container
    i.e., the panel which is dragged along, itself is not
    transparent.
    My question is : "Is there a way to make a control, like a panel, background transparent in AWT or some other way that can produce a similar effect in AWT ?".
    Please help me out.
    Thanks.

    Maybe the best way is to create your own component ( extending Component ) and then implementing paint() to do what you need.

  • Java Applet - AWT Container Conflicts

    Hello,
    I am currently programming a Java applet, and so far I have been fine aligning the GUI. I added everything to a panel, then added
    the panel to the applet.
    But, I have more then "page" that needs to be accessible. Example: a login screen where you type in your name and pass, once you login a new GUI is loaded and the old one disappears.
    I tried creating a separate panel and adding components to it for a separate "page" but for some reason this affects my first panel, even though it's not yet visible, and I haven't added it to the applet, somehow it affects it and I am unable to get both to line up.
    My question: How can I create totally separate containers that I can make visible/invisible whenever needed, without them affecting each other?
    Any help would be greatly appreciated.

    Blinksys wrote:
    I was just using AWT because it seemed simpler. I'm more then happy to use swing though, Use Swing because it's better.
    can you explain a bit more about how I could about using JDialog?Any of this is a bit much to explain. I can tell you that it is similar to using a JFrame in that you would probably create a JPanel the way with all the components desired, place it in the contentPane of a JDialog and then show the JDialog by calling setVisible(true), but this wouldn't be teaching you anything. I / we are much better at answering direct questions such as "why is this bug occurring". For a general question such as this, I recommend that you to to the Sun Java Swing tutorials and start studying.
    Also, I suspect that you are trying to learn Java by creating a complex program. If so, I strongly advise you to stop and back up. Java and any other subject of similar complexity must be learned in a progressive step-wise fashion usually from a tutorial or book (or both). Otherwise you end up doing what is often called trial-and-error programming, which is a process doomed to failure.
    Edited by: Encephalopathic on Jan 25, 2008 9:11 PM

  • Java.awt.IllegalComponentStateException in JTable

    Hi folks,
    I am trying to write a JTable cell validation. Input data in a cell, if failure, prompt message and set focus & editing back to the cell. I've tried InputVerifier() but it doesn't work since I can easily use the mouse click to shift to other cells in the same table.
    What I am trying to do now is to define my DefaultCellEditor. I record the row & index position when getting focus. In the lost focus event, do the validation and set the focus & editing back if failure. Seems it works fine. However, when I randomly click different cells in the table quickly. It prompts:
    "java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location"
    Here is my stack dump:
         at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1487)
         at java.awt.Component.getLocationOnScreen(Component.java:1461)
         at javax.swing.Autoscroller.mouseDragged(Autoscroller.java:79)
         at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2759)
         at java.awt.Component.processEvent(Component.java:4822)
         at java.awt.Container.processEvent(Container.java:1525)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Container.dispatchEventImpl(Container.java:1582)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.repostEvent(BasicTableUI.java:475)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mouseDragged(BasicTableUI.java:554)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:258)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:257)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:257)
         at java.awt.Component.processMouseMotionEvent(Component.java:5069)
         at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2763)
         at java.awt.Component.processEvent(Component.java:4822)
         at java.awt.Container.processEvent(Container.java:1525)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Container.dispatchEventImpl(Container.java:1582)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3359)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3091)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3004)
         at java.awt.Container.dispatchEventImpl(Container.java:1568)
         at java.awt.Window.dispatchEventImpl(Window.java:1581)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    Also, enclosed is my modified DefaultCellEditor class. Your input will be greatly appreicated. Thanks.
    class NewDefaultCellEditor extends DefaultCellEditor {
    public NewDefaultCellEditor(JTextField jTextField) {
    super(jTextField);
    this.setClickCountToStart(1);
    jTextField.addFocusListener(new FocusAdapter() {
    JTable tbl;
    int row;
    int column;
    public void focusGained(FocusEvent e) {
    tbl = (JTable)((JTextField)e.getSource()).getParent();
    row = tbl.getEditingRow();
    column = tbl.getEditingColumn();
    public void focusLost(FocusEvent e) {
    /*** Put validation here, execute the following if failed ***/
    tbl.editCellAt(row, column);
    ((JTextField)e.getSource()).requestFocus();

    Your use in a JTable isn't too clear to me, but I feel you're overthinking the basic requirement:
    I have an extended JComboBox which is meant to display its information only. Thus it
    - does not allow any selection
    - shows the first item of the list in the TextField only and not once more in the listI don't see the need for duplicating the model and using a popup menu listener.
    import java.awt.Component;
    import javax.swing.*;
    public class DisplayOnlyComboBoxDemo {
      public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new DisplayOnlyComboBoxDemo().makeUI();
      public void makeUI() {
        JFrame frame = new JFrame();
        frame.add(new DisplayOnlyComboBox("One", new String[]{"Two", "Three", "Four", "Five"}));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    class DisplayOnlyComboBox extends JComboBox {
      private String firstItem;
      public DisplayOnlyComboBox(String firstItem, String[] items) {
        super(items);
        this.firstItem = firstItem;
        setRenderer(new DefaultListCellRenderer() {
          @Override
          public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (index == -1) {
              setText(DisplayOnlyComboBox.this.firstItem);
            return this;
    }db

  • Table Model Listener conflict?

    Before I post my problem, please let me admit that I am a fairly new beginner to Java with a problem too big for my knowledge. So please bear with my ignorance.
    I have created a table with a table model that changes size at the action of a button (will create as many rows as a certain user-entered value). This seems to be working fine.
    The table I am creating contains some default values, but the user will need to be able to modify these values. To read these values, I need a Table Model Listener.
    However, when I add the Table Model Listener, the above feature (change the size of the table at the action of the button) stops working. Is the table listener incompatible with a dynamic-sized table? Is there a step a should add in between to let the table listener know that the table data is final and read it? Am I doing things in the wrong order?
    I would appreciate any suggestions, as I am quite clueless.
    Thanks
    maccanena

    No that shouldn't matter, the listener is doing something you don't want, the code posted works for me.
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.EventQueue;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    public class TableTest {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    showUI();
        protected static void showUI() {
            Object [][] ptable = {{"p1", 2.0}};
            String[] colnamesp = { "p name:", "p value:" };
            final DefaultTableModel pTableModel = new DefaultTableModel(ptable,colnamesp);
            JTable jTable1 = new JTable(pTableModel);
            final JTextField nvarsEntry = new JTextField("1");
            JButton updateButton = new JButton("Update table");
            updateButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent updateevt) {       
                    try{
                        int nvars = Integer.parseInt(nvarsEntry.getText());
                        int j;
                        int length = pTableModel.getRowCount();
                        if (length<nvars) {
                            for (j=length;j<nvars;j++) {
                                pTableModel.addRow(new Object[] {"p"+String.valueOf(j+1), 2.0});                                         
                        else if (length>nvars) {
                            for (j=nvars;j<(length+1);j++) {
                                pTableModel.removeRow(nvars);
                    } catch (Exception e) {                 
            jTable1.getModel().addTableModelListener(new TableModelListener() {
                public void tableChanged(TableModelEvent evtable1) {
                    int row = evtable1.getFirstRow();
                    int column = evtable1.getColumn();
                    // Do something with the data...
            JFrame frame = new JFrame();
            Container contentPane = frame.getContentPane();
            contentPane.add(updateButton, BorderLayout.PAGE_START);
            contentPane.add(nvarsEntry, BorderLayout.PAGE_END);
            contentPane.add(new JScrollPane(jTable1), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
    }

  • Mouse class instead of Mouse Listener class?

    In my previous post, I mentioned about the mouse position checking. I would like to have a Mouse class that has a getX() and getY() so I can call anytime to find where the mouse is even the mouse is not moved, instead of having it in all Listener classes. Is there any way for me to get the mouse's x and y? Since if I want to know where is the mouse, I need to use MouseEvent e within any mouseXXXX() methods. Any hints?
    Many thanks,
    Andy

    Hi Andy,
    Here's a starter for ten. It uses listeners but I don't see a way round that as I can't find (nor imagine) any classes that track the mouse position. If there was such another class then it would probably be called a listener as that's what it does - listen to where the mouse pointer is.
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseMotionAdapter;
    import javax.swing.*;
    public class MouseTracker extends JFrame {
         private JLabel mx = new JLabel("xx");
         private JLabel mon = new JLabel("ukn");
         private JLabel my = new JLabel("yy");
         MouseTracker(){
              setTitle("MouseTracker");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setSize(200,200);
              addMouseListener(new MouseAdapter(){
                   public void mouseEntered(MouseEvent evnt){
                        mon.setText("Mouse at home");
                   public void mouseExited(MouseEvent evnt){
                        mon.setText("Oh, sad, mouse has gone.");
              addMouseMotionListener(new MouseMotionAdapter(){
                   public void mouseMoved(MouseEvent evnt){
                        mx.setText(Integer.toString(evnt.getX()));
                        my.setText(Integer.toString(evnt.getY()));
              Container cp = getContentPane();
              cp.add(mx, BorderLayout.NORTH);
              cp.add(mon);
              cp.add(my, BorderLayout.SOUTH);
              show();
         public static void main(String[] a){
              MouseTracker t = new MouseTracker();
    }I've used JLabels to illustrate the ability to determine where the mouse is, even if it's not moving.
    Regards
    sjl

  • Differences between awt and swing

    Ive written the following code, however Ive implemented the gui in awt rather then swing. Ive been told it hs too be in swing. What is the difference between swing and awt what will I need to change in my program so that its done using swing rather then the awt? Heres the code:
    // pp.java
    // Grant Brown
    // 22/02/02
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    // =========================================================
    // Class: pp
    // This class drives the customer manager. It contains the
    // main method which gets called as soon as this application
    // begins to run.
    // =========================================================
    class pp extends Frame implements ActionListener
    // Container of customer objects
    private Vector customers = new Vector (100);
    // List of names component. (Must specify java.awt in
    // front of List to distinguish the List class in the
    // java.awt package from the List class in the java.util
    // package.)
    private java.awt.List names = new java.awt.List ();
    // Delete and update button components.
    private Button delete;
    private Button update;
    // Default constructor.
    public pp ()
    // Assign "Paper Round Manager" to title bar of frame window.
    super ("Paper Round Manager");
    // Add a listener that responds to window closing
    // events. When this event occurs (by clicking on the
    // close box in the title bar), save customers and exit.
    addWindowListener (new WindowAdapter ()
    public void windowClosing
    (WindowEvent e)
    saveCustomers ();
    System.exit (0);
    // Place an empty label in the north part of the frame
    // window. This is done to correct an AWT positioning
    // problem.
    Label l = new Label ();
    add ("North", l);
    // Place the names component in the center part of the
    // frame window.
    add ("Center", names);
    // Create a panel object to hold four buttons.
    Panel p = new Panel ();
    Button b;
    // Add an Insert button to the Panel object and register
    // the current pp object as a listener for button events.
    p.add (b = new Button ("Insert"));
    b.addActionListener (this);
    // Add a Delete button to the Panel object and register
    // the current pp object as a listener for button events.
    p.add (delete = new Button ("Delete"));
    delete.addActionListener (this);
    // The Delete button should be disabled until there is at
    // least one customer to delete.
    delete.setEnabled (false);
    // Add an Update button to the Panel object and register
    // the current pp object as a listener for button events.
    p.add (update = new Button ("Update"));
    update.addActionListener (this);
    // The Update button should be disabled until there is at
    // least one customer to update.
    update.setEnabled (false);
    // Add a Finish button to the Panel object and register
    // the current customer object as a listener for button events.
    p.add (b = new Button ("Finish"));
    b.addActionListener (this);
    // Add the panel object to the frame window container.
    add ("South", p);
    // Set the background of the frame window container to
    // lightGray
    setBackground (Color.lightGray);
    // Set the size of the frame window container to 400
    // pixels horizontally by 200 pixels vertically.
    setSize (400, 200);
    // Allow the user to resize the frame window.
    setResizable (true);
    // Load all contacts.
    loadCustomers ();
    // Make sure that the frame window is visible.
    setVisible (true);
    public void actionPerformed (ActionEvent e)
    if (e.getActionCommand ().equals ("Delete"))
    delete ();
    else
    if (e.getActionCommand ().equals ("Finish"))
    saveCustomers ();
    System.exit (0);
    else
    if (e.getActionCommand ().equals ("Insert"))
    insert ();
    else
    update ();
    public Insets getInsets ()
    // Return an Insets object that describes the number of
    // pixels to reserve as a border around the edges of the
    // frame window.
    return new Insets (10, 10, 10, 10);
    public static void main (String [] args)
    // Create a new pp object and let it do its thing.
    new pp ();
    private void delete ()
    // Obtain index of selected contact item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot update
    // a contact if no contact item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Remove the contact item from the names component.
    names.remove (index);
    // Remove the Customer object from the contacts Vector
    // object.
    customers.remove (index);
    // If there are no more customers ...
    if (customers.size () == 0)
    delete.setEnabled (false);
    update.setEnabled (false);
    else
    // Make sure that the first contact item in the names
    // list is highlighted.
    names.select (0);
    private void insert ()
    // Create an Insert data entry form to enter information
    // for a new customer.
    DataEntryForm def = new DataEntryForm (this, "Insert");
    // If the bOk Boolean flag is set, this indicates the user
    // exited the form by pressing the Ok button.
    if (def.bOk)
    // Create a Contact object and assign information from
    // the form to its fields.
    Customer temp = new Customer ();
    temp.name = new String (def.name.getText ());
    temp.publication = new String (def.publication.getText ());
    temp.round = new String (def.round.getText ());
    temp.address = new String (def.address.getText ());
    temp.phone = new String (def.phone.getText ());
    // Add a new customer item to the names component.
    names.add (temp.name + ", " + temp.publication);
    // Add the Customer object to the contacts Vector
    // object.
    customers.add (temp);
    // Make sure that the Delete and Update buttons are
    // enabled.
    delete.setEnabled (true);
    update.setEnabled (true);
    // Destroy the dialouge box.
    def.dispose ();
    // Make sure that the first customer item in the names list
    // is highlighted.
    names.select (0);
    // ===========================================================
    // Load all contacts from contacts.dat into the contacts
    // Vector object. Also, make sure that the last name/first
    // name from each contact is combined into a String object and
    // inserted into the names component - as a contact item.
    // ===========================================================
    private void loadCustomers ()
    FileInputStream fis = null;
    try
    fis = new FileInputStream ("Customers.dat");
    DataInputStream dis = new DataInputStream (fis);
    int nCustomers = dis.readInt ();
    for (int i = 0; i < nCustomers; i++)
    Customer temp = new Customer ();
    temp.name = dis.readUTF ();
    temp.publication = dis.readUTF ();
    temp.round = dis.readUTF ();
    temp.address = dis.readUTF ();
    temp.phone = dis.readUTF ();
    names.add (temp.name + ", " + temp.publication);
    customers.add (temp);
    if (nCustomers > 0)
    delete.setEnabled (true);
    update.setEnabled (true);
    catch (IOException e)
    finally
    if (fis != null)
    try
    fis.close ();
    catch (IOException e) {}
    // Make sure that the first contact item in the names list
    // is highlighted.
    names.select (0);
    // ========================================================
    // Save all Customer objects from the customer Vector object
    // to customer.dat. The number of customerss are saved as an
    // int to make it easy for loadCustomers () to do its job.
    // ========================================================
    private void saveCustomers ()
    FileOutputStream fos = null;
    try
    fos = new FileOutputStream ("customers.dat");
    DataOutputStream dos = new DataOutputStream (fos);
    dos.writeInt (customers.size ());
    for (int i = 0; i < customers.size (); i++)
    Customer temp = (Customer) customers.elementAt (i);
    dos.writeUTF (temp.name);
    dos.writeUTF (temp.publication);
    dos.writeUTF (temp.round);
    dos.writeUTF (temp.address);
    dos.writeUTF (temp.phone);
    catch (IOException e)
    MsgBox mb = new MsgBox (this, "PP Error",
    e.toString ());
    mb.dispose ();
    finally
    if (fos != null)
    try
    fos.close ();
    catch (IOException e) {}
    private void update ()
    // Obtain index of selected customer item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot update
    // a customer if no customer item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Obtain a reference to the customer object (from the
    // customers Vector object) that is associated with the
    // index.
    Customer temp = (Customer) customers.elementAt (index);
    // Create and display an update entry form.
    DataEntryForm def = new DataEntryForm (this, "Update",
    temp.name,
    temp.publication,
    temp.round,
    temp.address,
    temp.phone);
    // If the user pressed Ok...
    if (def.bOk)
    // Update the customer information in the customers
    // Vector object.
    temp.name = new String (def.name.getText ());
    temp.publication = new String (def.publication.getText ());
    temp.round = new String (def.round.getText ());
    temp.address = new String (def.address.getText ());
    temp.phone = new String (def.phone.getText ());
    // Make sure the screen reflects the update.
    names.replaceItem (temp.name + ", " + temp.publication,
    index);
    // Destroy the dialouge box.
    def.dispose ();
    // Make sure that the first customer item in the names
    // list is highlighted.
    names.select (0);

    Ive doen pretty much what you said burt now my program isnt working at all. The window comes up but instead of doing something when you click the button it just throws shit loads of exceptions. Heres my abridged code
    // pp.java
    // Grant Brown
    // 22/02/02
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    // =========================================================
    // Class:PP
    // This class drives the Paper Round manager. It contains the
    // main method which gets called as soon as this application
    // begins to run.
    // =========================================================
    class pp extends JFrame implements ActionListener
    // Container of customer objects (one object per customer)
    private Vector customers = new Vector (100);
    // List of names component. (Must specify java.awt in
    // front of List to distinguish the List class in the
    // java.awt package from the List class in the java.util
    // package.)
    private java.awt.List names = new java.awt.List ();
    // Delete and update button components.
    private JButton delete;
    private JButton update;
    // Default constructor.
    public pp ()
    // Assign Contact Manager to title bar of frame window.
    super ("Paper Round Manager");
    // Add a listener that responds to window closing
    // events. When this event occurs (by clicking on the
    // close box in the title bar), save contacts and exit.
    addWindowListener (new WindowAdapter ()
    public void windowClosing
    (WindowEvent e)
    saveCustomers ();
    System.exit (0);
    // Place an empty label in the north part of the frame
    // window. This is done to correct an AWT positioning
    // problem. (One thing that you'll come to realize as
    // you work with the AWT is that there are lots of bugs.)
    JLabel l = new JLabel ();
    getContentPane().add ("North", l);
    // Place the names component in the center part of the
    // frame window.
    getContentPane().add ("Center", names);
    // Create a panel object to hold four buttons.
    JPanel p = new JPanel ();
    JButton b;
    // Add an Insert button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (b = new JButton ("Insert"));
    b.addActionListener (this);
    // Add a Delete button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (delete = new JButton ("Delete"));
    delete.addActionListener (this);
    // The Delete button should be disabled until there is at
    // least one contact to delete.
    delete.setEnabled (false);
    // Add an Update button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (update = new JButton ("Update"));
    update.addActionListener (this);
    // The Update button should be disabled until there is at
    // least one contact to update.
    update.setEnabled (false);
    // Add a Finish button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (b = new JButton ("Finish"));
    b.addActionListener (this);
    // Add the panel object to the frame window container.
    getContentPane().add ("South", p);
    // Set the background of the frame window container to
    // lightGray (to give a pleasing effect).
    setBackground (Color.lightGray);
    // Set the size of the frame window container to 400
    // pixels horizontally by 200 pixels vertically.
    setBounds (50, 100, 400, 200);
    // Do not allow the user to resize the frame window.
    loadCustomers ();
    // Load all contacts.
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Make sure that the frame window is visible.
    setVisible (true);
    public void actionPerformed (ActionEvent e)
    if (e.getActionCommand ().equals ("Delete"))
    delete ();
    else
    if (e.getActionCommand ().equals ("Finish"))
    saveCustomers ();
    System.exit (0);
    else
    if (e.getActionCommand ().equals ("Insert"))
    insert ();
    else
    update ();
    public Insets getInsets ()
    // Return an Insets object that describes the number of
    // pixels to reserve as a border around the edges of the
    // frame window.
    return new Insets (10, 10, 10, 10);
    public static void main (String [] args)
    // Create a new cm object and let it do its thing.
    new pp ();
    private void delete ()
    // Obtain index of selected customer item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot update
    // a contact if no contact item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Remove the customer item from the names component.
    names.remove (index);
    // Remove the Customer object from the contacts Vector
    // object.
    customers.remove (index);
    // If there are no more customers ...
    if (customers.size () == 0)
    delete.setEnabled (false);
    update.setEnabled (false);
    else
    // Make sure that the first contact item in the names
    // list is highlighted.
    names.select (0);
    private void insert ()
    // Create an Insert data entry form to enter information
    // for a new contact.
    DataEntryForm def = new DataEntryForm (this, "Insert");
    // If the bOk Boolean flag is set, this indicates the user
    // exited the form by pressing the Ok button.
    if (def.bOk)
    // Create a Customer object and assign information from
    // the form to its fields.
    Customer temp = new Customer ();
    temp.name = new String (def.name.getText ());
    temp.publication = new String (def.publication.getText ());
    temp.address = new String (def.address.getText ());
    temp.round = new String (def.round.getText ());
    temp.phone = new String
              (def.phone.getText ());
    // Add a new customer item to the names component.
    names.add (temp.publication + ", " + temp.address);
    // Add the Customer object to the contacts Vector
    // object.
    customers.add (temp);
    // Make sure that the Delete and Update buttons are
    // enabled.
    delete.setEnabled (true);
    update.setEnabled (true);
    // Destroy the dialog box.
    def.dispose ();
    // Make sure that the first customer item in the names list
    // is highlighted.
    names.select (0);
    // ===========================================================
    // Load all customers from customers.dat into the customers
    // Vector object. Also, make sure that the last name/first
    // name from each contact is combined into a String object and
    // inserted into the names component - as a contact item.
    // ===========================================================
    private void loadCustomers ()
    FileInputStream fis = null;
    try
    fis = new FileInputStream ("customers.dat");
    DataInputStream dis = new DataInputStream (fis);
    int nCustomers = dis.readInt ();
    for (int i = 0; i < nCustomers; i++)
    Customer temp = new Customer ();
    temp.name = dis.readUTF ();
    temp.publication = dis.readUTF ();
    temp.address = dis.readUTF ();
    temp.round = dis.readUTF ();
    temp.phone = dis.readUTF ();
    names.add (temp.publication + ", " + temp.address);
    customers.add (temp);
    if (nCustomers > 0)
    delete.setEnabled (true);
    update.setEnabled (true);
    catch (IOException e)
    finally
    if (fis != null)
    try
    fis.close ();
    catch (IOException e) {}
    // Make sure that the first customer item in the names list
    // is highlighted.
    names.select (0);
    // ========================================================
    // Save all customer objects from the contacts Vector object
    // to customers.dat. The number of contacts are saved as an
    // int to make it easy for loadCustomers () to do its job.
    // ========================================================
    private void saveCustomers ()
    FileOutputStream fos = null;
    try
    fos = new FileOutputStream ("customers.dat");
    DataOutputStream dos = new DataOutputStream (fos);
    dos.writeInt (customers.size ());
    for (int i = 0; i < customers.size (); i++)
    Customer temp = (Customer) customers.elementAt (i);
    dos.writeUTF (temp.name);
    dos.writeUTF (temp.publication);
    dos.writeUTF (temp.address);
    dos.writeUTF (temp.round);
    dos.writeUTF (temp.phone);
    catch (IOException e)
    MsgBox mb = new MsgBox (this, "PP Error",
    e.toString ());
    mb.dispose ();
    finally
    if (fos != null)
    try
    fos.close ();
    catch (IOException e) {}
    private void update ()
    // Obtain index of selected customer item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot update
    // a customer if no customer item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Obtain a reference to the Customer object (from the
    // customer Vector object) that is associated with the
    // index.
    Customer temp = (Customer) customers.elementAt (index);
    // Create and display an update entry form.
    DataEntryForm def = new DataEntryForm (this, "Update",
    temp.name,
    temp.publication,
    temp.address,
    temp.round,
    temp.phone);
    // If the user pressed Ok...
    if (def.bOk)
    // Update the customer information in the customers
    // Vector object.
    temp.name = new String (def.name.getText ());
    temp.publication = new String (def.publication.getText ());
    temp.address = new String (def.address.getText ());
    temp.round = new String (def.round.getText ());
    temp.phone = new String (def.phone.getText ());
    // Make sure the screen reflects the update.
    names.replaceItem (temp.publication + ", " + temp.address,
    index);
    // Destroy the dialog box.
    def.dispose ();
    // Make sure that the first customer item in the names
    // list is highlighted.
    names.select (0);
    // ========================================================
    // Class: Customer
    // This class describes the contents of a business customer.
    // ========================================================
    class Customer
    public String name;
    public String publication;
    public String address;
    public String round;
    public String phone;
    // ==========================================================
    // Class: DataEntryForm
    // This class provides a data entry form for entering customer
    // information.
    // ==========================================================
    class DataEntryForm extends JDialog implements ActionListener
    // bOk is a boolean flag. When true, it indicates that
    // the Ok button was pressed to terminate the dialog box
    // (as opposed to the Cancel button).
    public boolean bOk;
    // The following components hold the text that the user
    // entered into the visible text fields.
    public JTextField name;
    public JTextField publication;
    public JTextField address;
    public JTextField round;
    public JTextField phone;
    public void actionPerformed (ActionEvent e)
    // If the user pressed the Ok button, indicate this
    // by assigning true to bOk.
    if (e.getActionCommand ().equals ("Ok"))
    bOk = true;
    // Destroy the dialog box and return to the point
    // just after the creation of the DataEntryForm object.
    dispose ();
    public DataEntryForm (JFrame parent, String title)
    // Call the other constructor. The current constructor
    // is used for insert operations. The other constructor
    // is used for update operations.
    this (parent, title, "", "", "", "", "");
    public DataEntryForm (JFrame parent, String title,
    String name, String publication,
    String address, String round,
    String phone)
    // Initialize the superclass layer.
    super (parent, title, true);
    // Choose a grid bag layout so that components can be more
    // accurately positioned. (It looks nicer.)
    setLayout (new GridBagLayout ());
    // Add appropriate first name, last name, phone, fax, and
    // email components to the current DataEntryForm container.
    // (Remember, DataEntryForm is a subclass of Dialog.
    // Dialog is a container. Therefore, DataEntryForm
    // inherits the ability to be a container.)
    addComponent (this, new JLabel ("Name: "), 0, 0, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.name = new JTextField (15);
    addComponent (this, this.name, 1, 0, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.name.setText (name);
    addComponent (this, new JLabel ("Publications: "), 0, 1, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.publication = new JTextField (15);
    addComponent (this, this.publication, 1, 1, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.publication.setText (publication);
    addComponent (this, new JLabel ("Address "), 0, 2, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.address = new JTextField (15);
    addComponent (this, this.address, 1, 2, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.address.setText (address);
    addComponent (this, new JLabel ("Round No "), 0, 3, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.round = new JTextField (15);
    addComponent (this, this.round, 1, 3, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.round.setText (round);
    addComponent (this, new JLabel ("Phone Number "), 0, 4, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.phone = new JTextField (15);
    addComponent (this, this.phone, 1, 4, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.phone.setText (phone);
    addComponent (this, new JLabel (""), 0, 5, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    addComponent (this, new JLabel (""), 1, 5, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    JButton b;
    // Add an Ok button to this container.
    addComponent (this, b = new JButton ("Ok"), 0, 6, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    b.addActionListener (this);
    // Add a Cancel button to this container.
    addComponent (this, b = new JButton ("Cancel"), 1, 6, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    b.addActionListener (this);
    // Set the size of the dialog window to 250 pixels
    // horizontally by 200 pixels vertically.
    setSize (250, 200);
    // Do not allow users to resize the dialog window.
    setResizable (false);
    // Make sure that the dialog window is visible.
    setVisible (true);
    private void addComponent (Container con, Component com,
    int gridx, int gridy,
    int gridw, int gridh, int fill,
    int anchor)
    // Get the current layout manager. It is assumed to
    // be a GridBagLayout object.
    LayoutManager lm = con.getLayout ();
    // Create a GridBagConstraints object to make it
    // possible to customize component positioning.
    GridBagConstraints gbc = new GridBagConstraints ();
    // Assign the x and y grid positions.
    gbc.gridx = gridx;
    gbc.gridy = gridy;
    // Assign the number of grid blocks horizontally and
    // vertically that are occupied by the component.
    gbc.gridwidth = gridw;
    gbc.gridheight = gridh;
    // Specify the component's resize policy (fill) and
    // the direction in which the component is positioned
    // when its size is smaller than available space (anchor).
    gbc.fill = fill;
    gbc.anchor = anchor;
    // Set the new constraints that the grid bag layout
    // manager will use.
    ((GridBagLayout) lm).setConstraints (com, gbc);
    // Add the component to the container.
    con.add (com);
    // ===========================================================
    // Class: MsgBox
    // This class displays a message box to the user. The message
    // is usually an error message. The user must press the Ok
    // button to terminate the message box.
    // ===========================================================
    class MsgBox extends JDialog implements ActionListener
    public void actionPerformed (ActionEvent e)
    // Terminate the dialog box in response to the user
    // pressing the Ok button.
    dispose ();
    public MsgBox (JFrame parent, String title, String msg)
    // Initialize the superclass layer.
    super (parent, title, true);
    // Store the msg argument in a Label object and add
    // this object to the center part of the dialog window.
    JLabel l = new JLabel (msg);
    add ("Center", l);
    // Create a Button object and add it to the south part
    // of the dialog window.
    JButton b = new JButton ("Ok");
    add ("South", b);
    // Make the current object a listener to events that
    // occur as a result of the user pressing the Ok
    // button.
    b.addActionListener (this);
    // Make sure that the Ok button has the focus.
    b.requestFocus ();
    // Do not allow users to resize the dialog window.
    setResizable (false);
    // Allow the layout manager to choose an appropriate
    // size for the dialog window.
    pack ();
    // Make sure that the dialog window is visible.
    setVisible (true);
    }

  • Need help:JPanel not being displayed in the JFrame

    Hello,
    I have a class called ConstructRoom.java which extends JFrame and another class called DimensionsPanel.java which extends JPanel. In the ConstructRoom class I use the following theContainer.add(new DimensionsPanel());, so I can display my JPanel. Well I get the JFrame but no JPanel. When the this call is made the DimensionsPanel.java code is cycled through, Where has my JPanel gone to?
    If I change the DimensionPanel.java extend JFrame and add the the JFrame code. Then I get the JFrame and the JPanel.
    Whats going on here?
    Thanks

    I made some of the changes with no luck. Here is some of the code:
    ---------from ConstructRoom.java--------
    //Imports
    public class ConstructRoom extends JFrame
    //----Member objects and varibles
    private static String theTitle; //Varible for title of frame
    private JFrame theFrame; //Object for the JFrame
    // ----------------------------------------------------------- ConstructRoom
    public ConstructRoom(String theTitle)
    super(theTitle); //JFrame super class
    theFrame = new JFrame("My frame");
    Container theContainer = theFrame.getContentPane(); //Frame container
    theContainer.setLayout(new FlowLayout());
    theContainer.add(new DimensionsPanel());
    theFrame.pack();
    theFrame.setBounds(10,10,400, 400);
    theFrame.addWindowListener(new WindowHandler());
    theFrame.setVisible(true);
    }//end ConstructRoom(String theTitle)
    // -------------------------------------------------------------------- main
    public static void main(String args[])
    ConstructRoom theRoom = new ConstructRoom(theTitle);
    }//end main(String args[])
    //----WindowHander
    }//end class ConstructRoom extends JFrame
    --------from DimensionsPanel.java
    //Imports
    public class DimensionsPanel extends JPanel
    //----Member objects and varibles
    private JPanel dimensionsPanel; //The main panel to hold all info
    private Box panelBox; //Box for all boxes which is added to the JPanel
    private Box furnListBox; //Box for all related items of the furnList
    private Box dimensionsBox; //Box for all dimensions (x, y, z)
    private Box xFieldBox; //Box for all related items of the xField
    private Box yFieldBox; //Box for related items of the yField
    private Box zFieldBox; //Box for related items of the zField
    private Box buttonsBox; //Box for all buttons
    private Box clearBox; //Box for related clear button items
    private Box buildBox; //Box for related build button items
    private JLabel furnListLabel; //Label for the furnList comboBox
    private JLabel xFieldLabel; //Label for the xField
    private JLabel yFieldLabel; //Label for yField
    private JLabel zFieldLabel; //Label for zField
    private JTextField xField; //Text field to enter the x dimension
    private JTextField yField; //Text field to enter the y dimension
    private JTextField zField; //Text field to enter the z dimension
    private JComboBox furnList; //List of selectable furniture objects
    private JButton clearButton; //Clear button
    private JButton buildButton; //Build button
    // --------------------------------------------------------- DimensionsPanel
    public DimensionsPanel()
    //----Setting up dimensions panel
    dimensionsPanel = new JPanel();
    dimensionsPanel.setLayout(new BorderLayout());
    dimensionsPanel.setPreferredSize(new Dimension(150,150));
    dimensionsPanel.setBorder(new TitledBorder(new EtchedBorder(),
    "Select Furniture and Enter Dimensions"));
    //----Initializing GUI components
    furnListLabel = new JLabel("Select from list ");
    furnList = new JComboBox();
    xFieldLabel = new JLabel("Enter Width ");
    xField = new JTextField();
    yFieldLabel = new JLabel("Enter Height ");
    yField = new JTextField();
    zFieldLabel = new JLabel("Enter Depth ");
    zField = new JTextField();
    buildButton = new JButton("Build Object");
    clearButton = new JButton("Clear Object");
    //-----Setting up the combo box and adding items
    furnList.addActionListener(new ComboProcessor());
    furnList.addItem(" "); //Default item
    furnList.addItem("Color Cube");
    furnList.setMaximumRowCount(6); //Max number of items before scrolling
    furnList.setSelectedItem(" "); //Set initial to default item
    //--Add the furnList to its box for placement in the JPanel
    furnListBox = Box.createHorizontalBox();
    furnListBox.add(Box.createHorizontalStrut(5));
    furnListBox.add(furnListLabel); //Adding the combo box label
    furnListBox.add(furnList); //Adding the combo box
    furnListBox.add(Box.createHorizontalStrut(5)); //Spacing
    //-------------------------------- Start Dimensions Components
    //----Setting up the xField
    xField.setEnabled(false); //Disabled at start
    xField.setFocusTraversalKeysEnabled(false); //Disabling the Tab Key
    //----Adding the event listeners
    xField.addActionListener(new XTextProcessor()); //Enter Key
    xField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the xField to its box for placement in the dimensionsBox
    xFieldBox = Box.createHorizontalBox();
    xFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    xFieldBox.add(Box.createGlue()); //Take up extra space
    xFieldBox.add(xFieldLabel); //Adding the text field label
    xFieldBox.add(xField); //Adding the text field
    xFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the yfield
    yField.setEnabled(false); //Disabled at start
    yField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    yField.addActionListener(new YTextProcessor()); //Enter Key
    yField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the yField to its box for placement in the dimensionsBox
    yFieldBox = Box.createHorizontalBox();
    yFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    yFieldBox.add(Box.createGlue()); //Take up extra space
    yFieldBox.add(yFieldLabel); //Adding the text field label
    yFieldBox.add(yField); //Adding the text field
    yFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the zfield
    zField.setEnabled(false); //Disabled at start
    zField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    zField.addActionListener(new ZTextProcessor()); //Enter Key
    zField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the zField to its box for placement in the dimensionsBox
    zFieldBox = Box.createHorizontalBox();
    zFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    zFieldBox.add(Box.createGlue()); //Take up extra space
    zFieldBox.add(zFieldLabel); //Adding the text field label
    zFieldBox.add(zField); //Adding the text field
    zFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Adding all dimension components to the dimensionsBox
    dimensionsBox = Box.createVerticalBox();
    dimensionsBox.add(xFieldBox); //Adding the xFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(yFieldBox); //Adding the yFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(zFieldBox); //Adding the zFieldBox
    //-------------------------------- End Dimension Components
    //----Setting up the clearButton
    clearButton.setEnabled(false); //Disabled at start
    //----Adding the event listener
    clearButton.addActionListener(new ClearProcessor());
    //--Add the clear button to its box for placement
    clearBox = Box.createHorizontalBox();
    clearBox.add(Box.createHorizontalStrut(5)); //Spacing
    clearBox.add(clearButton); //Adding the clearButton
    //----Setting up the buildButton
    buildButton.setEnabled(false); //Disabled at start
    //--Add the action listener here
    buildBox = Box.createHorizontalBox();
    buildBox.add(buildButton); //Adding the buildButton
    buildBox.add(Box.createHorizontalStrut(5)); //Spacing
    //----Adding both buttons the buttonsBox
    buttonsBox = Box.createHorizontalBox();
    buttonsBox.add(clearBox); //Adding the clearBox
    buttonsBox.add(Box.createHorizontalStrut(10)); //Spacing
    buttonsBox.add(buildBox); //Adding the buildBox
    //----Create the JPanel (dimensionsPanel)
    //--Creating the main box to be added to the JPanel
    panelBox = Box.createVerticalBox();
    panelBox.add(furnListBox); //Adding the furnListBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(dimensionsBox); //Adding the dimensionBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(buttonsBox); //Adding the buttonsBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsPanel.add(panelBox); //Adding all components to the JPanel
    System.out.println("end dimensionpanel");
    }//end DimensionsPanel()
    //------ActionListeners
    }//end class DimensionsPanel extends JPanel

  • Java.awt.Image getWidth() and getHeight() not working!

    Right- this is want I want to do.
    I have a background image which is added as a background image to a third party API class which extends Java.awt.Container. Such container is then added to the Content Pane of MyClass (which extends JFrame)
    I want to read the width and height of the image and resize MyClass accordingly.
    Problem is calling theImage.getWidth(MyClass.this) or theImage.getWidth(theThirdPartyAPIContainer) always return -1 and -1 denoting that no information is available.
    What do I need to do to obtain the height and width?

    Post here, cos don't know your email.
    Anyway
    - Can't use setPreferredSize because the Conatiner which is added to the ContentPane is a Awt Component not a Swing JComponent!
    - Also, the background is added AFTER the this.pack()and this.show().
    -I figured out that I could access Insets.top, Insets.left, Insets.right, Insets.bottom.
    I have basically the following
    |JMenuBar |
    L____________________________________________|
    | |
    | |
    | |
    | Third Party Class extending java.awt.Container |
    | containing an image of known size |
    | |
    L____________________________________________|
    I am fine for the width I do
    Insets frameInsets = this.getInsets();
    width = image.getWidth() + frameInsets.left + frameInsets.right;
    Height is the problem
    After some Trial an error it LOOKS on Solaris as if the following is right-
    height = image.getHeight()+frameInsets.top+ myJMenuBar.getSize()+getHeight+ myJMenuBar.getInsets().top + myJMenuBar.getInsets().bottom
    I cannot comprehend whether this is just a coincidence or not as I don't know why frameInsets.bottom should in any case be excluded.
    Here are the dimensions-
    frameInsets.left = 6
    frameInsets.right= 6
    frameInsets.top =28
    frameInsets.bottom = 6
    JMenuBar height = 23
    JMenuBar's Insets.top = 1
    JMenuBar's Insets.bottom = 1
    What should be the 'correct' calculations and does the Insets for the JMenuBar and the JFrame overlaps?

  • Problem with JFrame code

    Can anyone say the problem with the attached code. When I run the program, only, maximize, minimize and close options are viewable and nothing else.
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.LineBorder;
    * Created on Mar 24, 2008
    * @author Anand
    public class JBackGroundImageDemo extends JFrame
        Container con = null;
        JPanel panelBgImg;
        public JBackGroundImageDemo()
            setTitle("JBackGroundImageDemo");
            con = getContentPane();
            con.setLayout(null);
            ImageIcon imh = new ImageIcon("aditi.jpg");
            setSize(imh.getIconWidth(), imh.getIconHeight());
            panelBgImg = new JPanel()
                public void paintComponent(Graphics g)
                    Image img = new ImageIcon("aditi.jpg").getImage();
                    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                    setPreferredSize(size);
                    setMinimumSize(size);
                    setMaximumSize(size);
                    setSize(size);
                    setLayout(null);
                    g.drawImage(img, 0, 0, null);
            con.add(panelBgImg);
            panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());
            GridBagLayout layout = new GridBagLayout();
            JPanel panelContent = new JPanel(layout);
            GridBagConstraints gc = new GridBagConstraints();
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 1;
            JLabel label = new JLabel("UserName: ", JLabel.LEFT);                       
            panelContent.add(label, gc);
            gc.gridx = 2;
            gc.gridy = 1;
            JTextField txtName = new JTextField(10);
            panelContent.add(txtName, gc);
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 2;
            gc.gridwidth = 2;
            JButton btn = new JButton("Login");
            panelContent.add(btn, gc);
            panelContent.setBackground(Color.GRAY);
            panelContent.setBorder(new LineBorder(Color.WHITE));
            panelBgImg.add(panelContent);
            panelBgImg.setLayout(new FlowLayout(FlowLayout.CENTER, 150, 200));
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args)
            new JBackGroundImageDemo().setVisible(true);
         Please help.
    Regards,
    Anees

    Here's you a little code example, it works, so take a look at it.
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Junk{
      public Junk(){
      public void makeFrame(){
        JFrame j = new JFrame("Junk");
        Toolkit t = Toolkit.getDefaultToolkit();
        MediaTracker mt = new MediaTracker(j);
        Image img = t.getImage("junk.jpg");
        mt.addImage(img, 0);
        try{
          mt.waitForID(0);
        }catch(InterruptedException e){
          System.out.println("Hey, we were too impatient!");
        myPanel p = new myPanel(img);
        p.setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
        j.add(p);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.pack();
        j.setVisible(true);
      public static void main(String[] args){
        new Junk().makeFrame();
      class myPanel extends JPanel{
        Image img;
        myPanel(Image img){
          this.img = img;
        public void paintComponent(Graphics g){
          g.drawImage(img, 0, 0, this);
    }BTW: your image should be in your project folder.

  • Is there a problem with JFrame and window listeners?

    As the subject implies, i'm having a problem with my JFrame window and the window listeners. I believe i have implemented it properly (i copied it from another class that works). Anyway, none of the events are caught and i'm not sure why. Here's the code
    package gcas.gui.plan;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.util.Hashtable;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import gcas.plandata.TaskData;
    import gcas.util.GCASProperties;
    import gcas.gui.planlist.MainPanel;
    * MainFrame extends JPanel and is the main class for the plan details window
    public class MainFrame extends JFrame implements WindowListener
         * the container for this window
        private Container contentPane;
         * a string value containing the name of the plan being viewed
        private String labelText;
         * a string value containing the name of the window (GCAS - plan list)
        private static String title;
         * an instance of JDialog class
        private static MainFrame dialog;
         * hashTable that correlates the task name to its id as found in the
         * plan
        private Hashtable taskNameToId = new Hashtable();
         * an instance of taskSetPane.  This is the current instance of taskSetPane
         * being viewed
        private PlanTaskSet currentPane;
         * instance of TaskData class.  Each instance will hold information on
         * an individual task
        private TaskData taskData;
         * hashTable containing instances of the taskSetPane class
        private Hashtable taskSetPanes = new Hashtable();
         * an instance of the OuterPanel class
        OuterPanel mainPanel;
         * an instance of the ButtonPanel class
        ButtonPanel buttonsPanel;
         * an instance of the LeftPanel class
        LeftPanel leftPanel;
         * an instance of the the GCASProperties class
        GCASProperties gcasProps;
        private static MainFrame thisPlanMain = null;
        private MainPanel planListMain;
         * constructor for MainFrame
         * @param frame the parent frame calling this class
         * @param locationComp the location of the component that initiated the opening of the dialog
         * @param labelText the name of the plan that is being viewed
         * @param title title of window
        private MainFrame(JFrame frame, Component locationComp, String labelText,
                String title)
            super(title);
            gcasProps = GCASProperties.getInstance();
            mainPanel = new OuterPanel(labelText, currentPane,
                    taskNameToId, taskSetPanes);
            leftPanel = mainPanel.getLeftPanel();
            System.out.println("LABLE: " + labelText);
            leftPanel.setMainPanelContents();
            buttonsPanel = new ButtonPanel(labelText, taskSetPanes,
                    taskNameToId, leftPanel);
            contentPane = getContentPane();
            contentPane.add(mainPanel, BorderLayout.CENTER);
            contentPane.add(buttonsPanel, BorderLayout.PAGE_END);
            this.addWindowListener(this);
            this.labelText = labelText;
            pack();
            setLocationRelativeTo(locationComp);
            this.setVisible(true);
            planListMain = MainPanel.getInstance();
            planListMain.setVisible(false);
        public static MainFrame getInstance(JFrame frame, Component locationComp, String labelText,
                String title)
            if (thisPlanMain == null)
                thisPlanMain = new MainFrame(frame, locationComp, labelText,
                        title);
            return thisPlanMain;
        public static MainFrame getDialogObject()
        {   //from the location this is called (ButtonPanel), this will never
            //be null
            return thisPlanMain;
        public static void setABMDDialogNull()
            thisPlanMain = null;
         * returns an instance of MainFrame
         * @return MainFrame instance
        public static MainFrame getDialog()
            return dialog;
         * setter for MainFrame
         * @param aDialog a MainFrame instance
        public static void setDialog(MainFrame aDialog)
            dialog = aDialog;
         * window opened event
         * @param windowEvent the window event passed to this method
        public void windowOpened(WindowEvent windowEvent)
         * The window event when a window is closing
         * @param windowEvent the window event passed to this method
        public void windowClosing(WindowEvent windowEvent)
            gcasProps.storeProperties("PlanList");
            MainPanel abmd = MainPanel.getInstance();
    //        planMain = this.getDialogObject();
    //        if(planMain != null)
    //            planMain.setVisible(false);
    //            abmd.setVisible(true);
    //            planMain.setABMDDialogNull();
            if(this.getDialogObject()!= null)
                abmd.setVisible(true);
                setVisible(false);
                setABMDDialogNull(); 
         * Invoked when the Window is set to be the active Window
         * @param windowEvent the window event passed to this method
        public void windowActivated(WindowEvent windowEvent)
         * Invoked when a window has been closed as the result of calling dispose on the window
         * @param windowEvent the window event passed to this method
        public void windowClosed(WindowEvent windowEvent)
         * Invoked when a Window is no longer the active Window
         * @param windowEvent the window event passed to this method
        public void windowDeactivated(WindowEvent windowEvent)
            System.out.println("HI");
         * Invoked when a window is changed from a minimized to a normal state
         * @param windowEvent the window event passed to this method
        public  void windowDeiconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
           System.out.println("Invoked when a window is changed from a minimized to a normal state.");
         * Invoked when a window is changed from a normal to a minimized state
         * @param windowEvent the window event passed to this method
        public  void windowIconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
    //        System.out.println("Invoked when a window is changed from a normal to a minimized state.");
    }anyone know whats wrong?

    It turned out that my ide was running the old jar and not updating it, so no matter what code i added, it wasn't being seen. Everything should be fine now.

Maybe you are looking for