Search code examples
javaswingjscrollpanejlistnull-layout-manager

JScrollPane in Jlist


hello goodevening to all i have a problem on my program with the ScrollPane in my JList i cant put an JScrollPane in my list because i am using a panel instead of Container this is my code so far its all runnable the problem is if you enter a high number in the number of times the some output will not be able to see because of the size of my list . so this is the code

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MultCen extends JFrame implements ActionListener
{
    public static void main(String args [])
    {
        MultCen e = new MultCen();
        e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        e.setVisible(true);
        e.setSize(300,450);
    }

    JTextField t1 = new JTextField();
    JTextField t2 = new JTextField();
    JButton b = new JButton("Okay");
    JButton c = new JButton("Clear");
    JList list = new JList();
    JLabel lab = new JLabel();
    DefaultListModel m = new DefaultListModel();

    public MultCen()
    {
        JPanel panel = new JPanel();
        panel.setLayout(null);



        JLabel l = new JLabel("Enter a number :");
        JLabel l1 = new JLabel("How many times :");



        l.setBounds(10,10,130,30);
        l1.setBounds(10,40,130,30);
        t1.setBounds(140,10,130,25);
        t2.setBounds(140,40,130,25);
        b.setBounds(60,90,75,30);
        c.setBounds(150,90,75,30);
        list.setBounds(30,140,220,220);

        panel.add(t1);
        panel.add(t2);
        panel.add(l);
        panel.add(l1);
        panel.add(list);
        panel.add(b);
        panel.add(c);

        getContentPane().add(panel);


        b.addActionListener(this);
        c.addActionListener(this);


    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == b)
        {
            int t3 = Integer.parseInt(t1.getText());
            int t4 = Integer.parseInt(t2.getText());
            m.addElement("The multiplication Table of "+t3);
            for (int cc =1 ; cc <=t4; cc++ )
            {

                lab.setText(t3+"*"+cc+" = "+(t3*cc));
                m.addElement(lab.getText());
                list.setModel(m);


            }



        }

        if(e.getSource() == c)
        {
            t1.setText("");
            t2.setText("");
            m.removeAllElements();
        }
    }

}

Solution

  • JScrollPane does not work with null Layout. Use BoxLayout or any other resizeable layout instead. This is the limitation of setLayout(null).