我有一个包含名称列表的文本文件。我正在尝试创建一个GUI,然后将文件中的文本读入GUI,并将其显示在textfield/label/anything中。我可以创建GUI并读入代码,但不知道如何在GUI中显示读入的文本。下面是我的代码。当我运行时,它显示GUI,但不显示读入文本。
public class ASSIGNMENT {
private JLabel lbl1;
private JTextField txt1;
private JPanel panel;
private JFrame frame;
public ASSIGNMENT(){
createGUI();
addLabels();
frame.add(panel);
frame.setVisible(true);
}
public void createGUI(){
frame = new JFrame();
frame.setTitle("Books");
frame.setSize(730, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
panel.setBounds(10, 10, 10, 10);
panel.setBorder(BorderFactory.createLineBorder (Color.decode("#1854A2"), 2));
frame.add(panel);
}
public void addLabels(){
lbl1 = new JLabel(" ");
lbl1.setBounds(700, 450, 120, 25);
lbl1.setForeground(Color.white);
panel.add(lbl1);
}
public void books() throws IOException{
String result = "books2.txt";
String line;
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("books2.txt")));
while((line = lnr.readLine()) != null){
result += line;
}
JLabel label1 = new JLabel(result);
panel.add(label1);
}
public static void main(String[] args) throws Exception{
new ASSIGNMENT();
}
}
你好,这是您的代码正在工作。您基本上需要正确设置布局管理器。你有两个选择选项一是使用NULL和布局管理器。在这种情况下,您需要使用setBounds()定位所有组件。
选项二是使用一个更用户友好的布局管理器,它不需要像GridBagLayout那样的功能。Bellow,您可以看到您的代码已针对GridBagLayout进行了更正。我重复一遍,使用null作为管理器是可能的,但您需要在setBounds 的帮助下用坐标定位元素
public class ASSIGNMENT3 {
private JLabel lbl1;
private JTextField txt1;
private JPanel panel;
private JFrame frame;
public ASSIGNMENT3() throws IOException{
createGUI();
addLabels();
books();
frame.add(panel);
frame.setVisible(true);
}
public void createGUI(){
frame = new JFrame();
frame.setTitle("Books");
frame.setSize(730, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBounds(10, 10, 10, 10);
panel.setBorder(BorderFactory.createLineBorder (Color.decode("#1854A2"), 2));
frame.add(panel);
}
public void addLabels(){
lbl1 = new JLabel("Labe 1 ");
lbl1.setBounds(700, 450, 120, 25);
lbl1.setForeground(Color.white);
panel.add(lbl1);
}
public void books() throws IOException{
String result = "books2.txt";
String line;
// LineNumberReader lnr = new LineNumberReader(new FileReader(new File("books2.txt")));
// while((line = lnr.readLine()) != null){
// result += line;
// }
//
txt1 = new JTextField(20);
txt1.setText(result);
JLabel label1 = new JLabel(result);
panel.add(label1);
panel.add(txt1);
}
public static void main(String[] args) throws Exception{
new ASSIGNMENT3();
}
}