我正在尝试使用扫描程序读取文件,并为文件中的每个新行创建一个JButton。创建按钮后,我将其添加到框架中。但是,一旦我运行该程序,只会出现最新的按钮。我不确定为什么在循环中创建按钮会导致这种情况发生。如果有人解释为什么会发生这种情况,那将非常感谢,谢谢!
import java.awt.FlowLayout;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PointOfSale extends JFrame {
ArrayList<JButton> menuButtons = new ArrayList<>();
public PointOfSale(File menu) throws IOException{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
Scanner sc = new Scanner(menu);
while (sc.hasNextLine()){
String name = sc.nextLine();
JButton menuButton = new JButton(name);
frame.add(menuButton);
menuButtons.add(menuButton);
}
sc.close();
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:1)
您的代码不尊重布局管理器,因为JFrame使用的BorderLayout只显示一个按钮。阅读布局管理器教程,使用不同的教程,这里可能是GridLayout,你可能会解决你的问题。
答案 1 :(得分:0)
//public class PointOfSale extends JFrame {
public class PointOfSale {
由于您在类中创建了JFrame,因此您的类无需扩展JFrame。
然后你需要使用:
frame.setLayout(new FlowLayout());
因为这是你添加按钮的框架。