Hello,
My first question on SOF. I've got problem with JScrollPane and JList. I've made class for list with getter to get list object
package frontend;
import javax.swing.*;
public class GeneratedList
{
private JList<String> List;
public GeneratedList() {
DefaultListModel<String> listModel = new DefaultListModel<>();
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
listModel.addElement("1");
List = new JList<>(listModel);
}
public JList<String> getList() {
return List;
}}
And got class GUI for make whole frame.
package frontend;
import javax.swing.*;
import java.awt.*;
public class GUI
{
JFrame frame = new JFrame("QR Generator");
BorderLayout borderLayout = new BorderLayout();
public static JFormattedTextField inputField = new JFormattedTextField("XX.XXXX.XX");
JButton generateButtton = new JButton("Generate");
JButton printButton = new JButton("Print");
public GUI()
{
frame.setVisible(true);
frame.setLayout(borderLayout);
frame.setSize(new Dimension(200,200));
frame.add(inputField,BorderLayout.NORTH);
frame.add(generateButtton,BorderLayout.NORTH);
frame.add(printButton,BorderLayout.EAST);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setSize(200,300);
frame.add(scrollPane.add(new GeneratedList().getList()));
}}
In this style of code it works. List is visible but there is no scrollbars
First question is why ? :) And second question is why in this syntax, list isn't visible on frame.
package frontend;
import javax.swing.*;
import java.awt.*;
public class GUI
{
JFrame frame = new JFrame("QR Generator");
BorderLayout borderLayout = new BorderLayout();
public static JFormattedTextField inputField = new JFormattedTextField("XX.XXXX.XX");
JButton generateButtton = new JButton("Generate");
JButton printButton = new JButton("Print");
JScrollPane scrollPane = new JScrollPane();
public GUI()
{
frame.setVisible(true);
frame.setLayout(borderLayout);
frame.setSize(new Dimension(200,200));
frame.add(inputField,BorderLayout.NORTH);
frame.add(generateButtton,BorderLayout.NORTH);
frame.add(printButton,BorderLayout.EAST);
frame.add(scrollPane);
scrollPane.add(new GeneratedList().getList());
}
}
Thanks for help
frame.add(scrollPane.getViewport().add(list.getList())
That is not how you add a component to the viewport.
You use:
frame.add(scrollPane.setViewportView(...);
Or, even easier is to add the component when you create the JScrollPane.
JScrollPane scrollPane = new JScrollPane(...);
Read the section from the Swing tutorial on How to Use Lists for more information and a working example.
Download the example and use it as a starting point. The code from the tutorial will show you how to better structure you class.