Посмотрите на нижнюю часть кода в методе spaghettiFrame. Я хочу, чтобы мой JFrame начал прокручиваться, когда добавляю больше компонентов на панель contentPane. Я знаю, что это связано с тем, что мой макет был установлен в null (абсолютный), но всякий раз, когда я его вынимаю, он устанавливает все мои компоненты в одну горизонтальную линию.
public class SpaghettiFrame extends JFrame{
private static final AutoCompletion AutoCompletion = null;
private AutoCompletion beta;
private JSpinner Quantity_1;
private JComboBox Part_1;
private JPanel contentPane = new JPanel();
private JScrollPane jsp = new JScrollPane(contentPane);
private JTextField Price_1;
private JTextField Total;
private JLabel lblTotal;
private JTextField Building_1;
private String value = "0";
private String totalvalue = "0";
private int loc = 1;
private static String[] pricedatabase;
private static String[] partdatabase;
private static File pricefile = new File("DataBase/Price DataBase.txt");
private static File partfile = new File("DataBase/Part DataBase.txt");
private static DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
private static Date date = new Date();
private static File file = new File("Reports/" + (dateFormat.format(date)) + "Report.txt");
private static PrintWriter info;
ArrayList<JComboBox> part;
ArrayList<JSpinner> quantity;
ArrayList<JTextField> price;
ArrayList<JComponent> next;
ArrayList<JTextField> building;
public static void main(String[] args) throws Exception {
scanData();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SpaghettiFrame frame = new SpaghettiFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void scanData() throws Exception{
Scanner sc = new Scanner(partfile);
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
partdatabase = lines.toArray(new String[lines.size()]);
Scanner scc = new Scanner(pricefile);
List<String> numbers = new ArrayList<String>();
while (scc.hasNextLine()) {
numbers.add(scc.nextLine());
}
pricedatabase = numbers.toArray(new String[numbers.size()]);
}
public void addComponent(AutoCompletion beta){
Part_1 = new JComboBox();
Part_1.setBounds(50, 28 + loc*40, 178, 20);
for(int i=0; i <= partdatabase.length -1; i++){
Part_1.addItem(partdatabase[i]);
}
part.add(Part_1);
//AutoCompletion.enable(Part_1);
Part_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
totalvalue = "0";
for(int i=0;i<part.size();i++){
value = String.valueOf(Integer.valueOf(pricedatabase[part.get(i).getSelectedIndex()]) * (Integer)quantity.get(i).getValue());
totalvalue = String.valueOf(Integer.valueOf(totalvalue) + Integer.valueOf(value));
price.get(i).setText(value);
Total.setText(totalvalue);
}
}
});
Quantity_1 = new JSpinner();
Quantity_1.setBounds(287, 28 + loc*40, 41, 20);
quantity.add(Quantity_1);
Quantity_1.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
totalvalue = "0";
for(int i=0;i<part.size();i++){
value = String.valueOf(Integer.valueOf(pricedatabase[part.get(i).getSelectedIndex()]) * (Integer)quantity.get(i).getValue());
totalvalue = String.valueOf(Integer.valueOf(totalvalue) + Integer.valueOf(value));
price.get(i).setText(value);
Total.setText(totalvalue);
}
}
});
Price_1 = new JTextField();
Price_1.setBounds(390, 28 + loc*40, 86, 20);
Price_1.setText("");
Price_1.setEditable(false);
Price_1.setColumns(10);
price.add(Price_1);
Building_1 = new JTextField();
Building_1.setBounds(5, 28 + loc*40, 35, 20);
Building_1.setText("");
Building_1.setEditable(true);
Building_1.setColumns(10);
building.add(Building_1);
Total.setBounds(390, 68 + loc*40, 86, 20);
lblTotal.setBounds(320, 68 + loc*40, 86, 20);
update();
loc++;
}
public void update(){
for(JComponent j: part){
contentPane.add(j);
}
for(JComponent j: quantity){
contentPane.add(j);
}
for(JComponent j: price){
contentPane.add(j);
}
for(JComponent j: building){
contentPane.add(j);
}
contentPane.updateUI();
contentPane.repaint();
}
public SpaghettiFrame() throws Exception {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 492, 651);
setContentPane(jsp);
jsp.setViewportView(contentPane);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
part = new ArrayList<JComboBox>();
quantity = new ArrayList<JSpinner>();
price = new ArrayList<JTextField>();
building = new ArrayList<JTextField>();
JLabel lblBalanceCalculator = new JLabel("Balance Calculator");
lblBalanceCalculator.setFont(new Font("Times New Roman", Font.BOLD, 16));
lblBalanceCalculator.setHorizontalAlignment(SwingConstants.CENTER);
lblBalanceCalculator.setBounds(31, 11, 411, 14);
contentPane.add(lblBalanceCalculator);
Total = new JTextField();
Total.setBounds(390, 68 + loc*40, 86, 20);
Total.setEditable(false);
Total.setColumns(10);
Total.setText(totalvalue);
contentPane.add(Total);
lblTotal = new JLabel("Total:");
lblTotal.setFont(new Font("Times New Roman", Font.BOLD, 12));
lblTotal.setHorizontalAlignment(SwingConstants.CENTER);
lblTotal.setBounds(320, 68 + loc*40, 86, 20);
contentPane.add(lblTotal);
JButton btnPrint = new JButton("Print");
btnPrint.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
info = new PrintWriter(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
file.getParentFile().mkdirs();
info.println("BALANCE CALCULATOR " + (dateFormat.format(date)));
info.println("");
for(int i=0;i<=part.size()-1; i++){
info.println(String.valueOf(part.get(i).getSelectedItem()) + " x " + quantity.get(i).getValue() + " = " + price.get(i).getText());
info.println("");
}
info.print("Total: " + totalvalue);
info.close();
}
});
btnPrint.setBounds(43, 589, 89, 23);
contentPane.add(btnPrint);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
totalvalue = "0";
for(int i=0;i<part.size();i++){
value = String.valueOf(Integer.valueOf(pricedatabase[part.get(i).getSelectedIndex()]) * (Integer)quantity.get(i).getValue());
totalvalue = String.valueOf(Integer.valueOf(totalvalue) + Integer.valueOf(value));
price.get(i).setText(value);
Total.setText(totalvalue);
}
addComponent(AutoCompletion);
}
});
btnNext.setBounds(353, 589, 89, 23);
contentPane.add(btnNext);
addComponent(AutoCompletion);
update();
}
}
JScrollPanes не очень хорошо работает с нулевым макетом с использованием компонентов, но еще одна причина избежать нужных макетов, таких как чума. И если вы не используете нулевой макет, ваш JPanel по умолчанию использует FlowLayout, поэтому все находится на одной линии.
Решение: не используйте, но вместо этого используйте комбинацию вложенных JPanels, каждая из которых использует свои собственные макеты для достижения вашей цели дизайна.
редактировать
Например, просмотрите эти ответы:
И этот учебник:
Изменить 2
В стороне, интересно, то, что вы хотите создать, это JTable, который отображается в JScrollPane. Это будет содержать и отображать табличные данные хорошо, что вам нужно, правильно?