tags:

views:

25

answers:

1

When i input a name to the Jlist, the name gets outputted to the lower section of the list, how do i make it to where the name is set to the top of the window

package Gui;

//import java.awt.BorderLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class GUI implements ActionListener {

    JButton button;
    JTextField field;
    JList list;
    JTextField name1;
    DefaultListModel listModel;
    String name;

    public GUI(){
        listModel = new DefaultListModel();
        listModel.addElement(null);
        listModel.setSize(1);

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        field = new JTextField("Enter Name", 10);
        button = new JButton("Click");
        list = new JList(listModel);        

        list.setBorder(BorderFactory.createEmptyBorder(120, 20, 20, 120));


        JScrollPane listScrollPane = new JScrollPane(list);

        panel.add(listScrollPane);
        listScrollPane.setWheelScrollingEnabled(true);

        panel.add(button);
        panel.add(field);

        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);

        button.addActionListener(this);

        }


    public void actionPerformed(ActionEvent arg0) {
        if(arg0.getSource() == button)
            name = field.getText();
        listModel.addElement(name);
    }
}
+2  A: 

You can simply use the add(0, object) method.

Instead of listModel.addElement(name), listModel.add(0, name) will add the name at the top of the List.

For the size of the JList you shouldn't use this border but instead select a preferredSize for your JSCrollPane :

package Gui;
...    
import java.awt.Dimension;

public class GUI implements ActionListener {

    ...    
    public GUI(){
        ...
        list = new JList(listModel);

        JScrollPane listScrollPane = new JScrollPane(list);
        listScrollPane.setPreferredSize(new Dimension(100, 240));

        panel.add(listScrollPane);
        ...
    }

    public void actionPerformed(ActionEvent arg0) {
        if(arg0.getSource() == button)
            name = field.getText();
        listModel.add(0, name);
    }
}

Resources :

Colin Hebert
it made it better, but still not at the top
Ethan
@Ethan, Isn't the element at the top of the list ? Or did you mean something else ?
Colin Hebert
no, like when i run this program, the name that i input gets sent to the very bottom of the window
Ethan
ok, that made it still better, but when you ran this, when u enter a name, where did ur name show up? mine is sitting directly middle
Ethan
Did you remove the `list.setBorder()`?
Colin Hebert
that was it, thank you so much
Ethan