Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Problem with Displaying ListBox (i.e. JList)

Zulfi KhanJul 16 2016 — edited Jul 18 2016

Hi,

I am to store values in a listbox. I have created frame & a panel inside a frame & i am using BorderLayout inside panel. I have created a button & a listBox & added them to the panel. But when i run the application, it displays the button only & when i increase the size of window then it displays the listbox neighboring to the button.

My code is:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

/**  the panel

*/

public class ListBoxEg extends JFrame{

     private JButton button;

     JList<String> listbox;

     DefaultListModel<String> model;

     public ListBoxEg() {

        JFrame frame = new JFrame("Test");

        frame.setVisible(true);

        frame.setSize(500,200);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();

        frame.add(panel);

        panel.setLayout( new BorderLayout() );

        button=new JButton("Hello");

        panel.add(button, BorderLayout.WEST);

       

        String listData = "ABCDE";

       

        // Create a new DefaultListModel

        model = new DefaultListModel<> ( );

        //Adding Elements in the model

        model.addElement(listData);

  listData ="12345";

        model.addElement(listData);

        listData ="!!!!!!";

        model.addElement(listData);

        listData ="@@@@@@";

        model.addElement(listData);

        //Creating a new ListBox

  listbox= new JList<>();

        //Adding Elements in the ListBox

        listbox.setModel(model);

  panel.add( listbox, BorderLayout.CENTER );

        pack();

       

        MyActionListener listener=new MyActionListener();   //added

        button.addActionListener(listener);

    }

    public static void main(String args[ ]) {

       ListBoxEg obj = new ListBoxEg( );

    }

}

   

class MyActionListener implements ActionListener{

        public void actionPerformed (ActionEvent e) {

        System.out.println("pressed button");

        }

}

Some body please guide me.

Zulfi.

This post has been answered by Zulfi Khan on Jul 18 2016
Jump to Answer

Comments

Processing
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Aug 15 2016
Added on Jul 16 2016
2 comments
854 views