I’m trying to make a JFrame appear that reads each line from a text file into a JLabel and places that JLabel into a JScrollPane, that JScrollPane is then added to the Container for my window. The content and labels are loaded, but with one problem, as soon as the window loads my JScrollPane zips up and out of the Container leaving me with a blank window. Any help? here is the code:
import java.awt.Container;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class Helper extends JFrame{
String filepath = "assets/help.txt";
Scanner reader;
Container contentpane;
JScrollPane scrp = new JScrollPane(null);
JLabel line = new JLabel();
int align_x, align_y;
int window_width = 700;
int window_height = 700;
public Helper(){
setSize(window_height,window_width);
setVisible(true);
setTitle("Electric Force Calculator Helper");
scrp.setSize(window_height,window_width);
scrp.setVisible(true);
contentpane = getContentPane();
reader = new Scanner(getClass().getResourceAsStream(filepath));
align_x = 10;
align_y = 10;
while(reader.hasNextLine()){
line = new JLabel(reader.nextLine());
line.setBounds(align_x,align_y,window_width,20);
scrp.add(line);
align_y+=20;
}
contentpane.add(scrp);
}
public static void showHelpFrame(){
Helper newHelper = new Helper();
}
}
line = new JLabel(reader.nextLine());you are creating a new label each time here and then adding that label over the other label in theJScrollPanewithscrp.add(line);A better way to do this would be to use a
JList, wrap theJListin aJScrollPaneand then populate the list’s data model with your lines of text.