27.06.2023, 15:47. Показов 1198. Ответов 0
Всем день добрый, нужна помощь.
По заданию нужно:
Создать класс для хранения данных согласно варианту. Предусмотреть возможность работы с произвольным числом записей, а также реализовать отдельные функции класса:
- конструкторы без параметров и с параметрами;
- добавление информации;
- удаление информации;
- вывод информации на экран;
- редактирование записей.
Предметная область: "Список файлов".
Поля: имя файла, расширение, размер, дата создания, атрибуты.
Также нужно определить все файлы указанного расширения, определить минимальный и максимальный по размеру файл, определить самый старый и новый файл.
Теперь к делу. Все методы должны быть реализованы в классе FileList. По идее я создал их, но не знаю, как правильно применить к кнопкам.
До этого метода вывода как такового не было, он появлялся в DisplayFrame и выводилось всё нормально, но нужно переделать чтобы он был отдельно и лишь вызывался этим классом. Для этого я добавил метод в FileList, но он все равно не выводит список.
Касательно методов Редактирования и Удаления тут вообще сложно, не знаю как их внести в кнопки.
Что можете посоветовать хотя бы для кнопок Редактирования и Удаления.
Вот код:
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
| import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class exercise {
private String file_name;
private String expansion;
private double sizeFile;
private Date date_creation;
private String attributes;
public exercise(String file_name, String expansion, double sizeFile, Date date_creation, String attributes) {
this.file_name = file_name;
this.expansion = expansion;
this.sizeFile = sizeFile;
this.date_creation = date_creation;
this.attributes = attributes;
}
public exercise() {
this.file_name = "";
this.expansion = "";
this.sizeFile = 0;
this.date_creation = null;
this.attributes = "";
}
public String getFile_name() {
return file_name;
}
public void setFileName(String file_name) {
this.file_name = file_name;
}
public String getExpansion() {
return expansion;
}
public void setExpansion(String expansion) {
this.expansion = expansion;
}
public double getSizeFile() {
return sizeFile;
}
public void setSize(double sizeFile) {
this.sizeFile = sizeFile;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public String getAttributes() {
return attributes;
}
public void setAttributes(String attributes) {
this.attributes = attributes;
}
public void cleanExercise() {
this.file_name = "";
this.expansion = "";
this.sizeFile = 0;
this.date_creation = null;
this.attributes = "";
}
}
class FileList {
private List<exercise> file;
// создание пустого списка
public FileList() {
file = new ArrayList<>();
}
// добавление файла в список
public void addFile(exercise files) {
file.add(files);
}
// удаление файла из списка
public void deleteF(int i) {
if (i >= 0 && i < file.size()) {
file.remove(i); // метод remove() - удаляет объект из списка по определённому индексу
}
}
// редактирование ?? пока под вопросом
public void editF(int i, exercise updatedFile) {
if (i >= 0 && i < file.size()) {
file.set(i, updatedFile);
}
}
// возвращает все сохранённые файлы в виде списка
public List<exercise> getFiles() {
return file;
}
// выведение списка файлов
public String displayFilesOnForm() {
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String fileListText = "";
for (int i = 0; i < file.size(); i++) {
exercise files = file.get(i);
fileListText += "File Name: " + files.getFile_name() + "\n";
fileListText += "Expansion: " + files.getExpansion() + "\n";
fileListText += "Size: " + files.getSizeFile() + "\n";
fileListText += "Creation Date: " + files.getDate_creation() + "\n";
fileListText += "Attributes: " + files.getAttributes() + "\n";
fileListText += "----------------------------------\n";
}
return fileListText.toString();
}
// определить все файлы указанного расширения
// возвращает самый маленький файл из списка
public exercise minFile() {
if (file.isEmpty()) {
return null;
}
exercise minFile = file.get(0);
for (int i = 1; i < file.size(); i++) {
exercise files = file.get(i);
if (files.getSizeFile() < minFile.getSizeFile()) {
minFile = files;
}
}
return minFile;
}
// возвращает самый большой файл из списка
public exercise maxFile() {
if (file.isEmpty()) {
return null;
}
exercise maxFile = file.get(0);
for (int i = 0; i < file.size(); i++) {
exercise files = file.get(i);
if (files.getSizeFile() > maxFile.getSizeFile()) {
maxFile = files;
}
}
return maxFile;
}
// возвращает самый старый файл из списка
public exercise oldFile() {
if (file.isEmpty()) {
return null;
}
exercise oldFile = file.get(0);
for (int i = 0; i < file.size(); i++) {
exercise files = file.get(i);
if(files.getDate_creation().before(oldFile. getDate_creation())) {
oldFile = files;
}
}
return oldFile;
}
// возвращает самый новый файл из списка
public exercise newFile() {
if (file.isEmpty()) {
return null;
}
exercise newFile = file.get(0);
for (int i = 1; i < file.size(); i++) {
exercise files = file.get(i);
if (files.getDate_creation().after(newFile.getDate_creation())) {
newFile = files;
}
}
return newFile;
}
}
// ФОРМА НА КОТОРОЙ ПРОИСХОДИТ ДОБАВЛЕНИЕ
class AddFile extends JFrame {
private JTextField file_nameField;
private JTextField expansionField;
private JTextField sizeField;
private JTextField date_creationField;
private JTextField attributesField;
private JButton saveButton;
private FileList fileList;
public AddFile(FileList fileList) {
setSize(500, 500);
setVisible(true);
setLocation(50, 300);
JPanel nPanel = new JPanel();
add(nPanel);
JPanel mPanel = new JPanel();
add(mPanel, BorderLayout.SOUTH);
JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String file_name = file_nameField.getText();
String expansion = expansionField.getText();
double size = Double.parseDouble(sizeField.getText());
String attributes = attributesField.getText();
String date_CreationString = date_creationField.getText();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date creation_date;
try {
creation_date = dateFormat.parse(date_CreationString);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Invalid date format!");
return;
}
exercise file = new exercise(file_name, expansion, size, creation_date, attributes);
fileList.addFile(file);
JOptionPane.showMessageDialog(null, "File saved successfully!");
// очищает поле после введения
file_nameField.setText("");
expansionField.setText("");
date_creationField.setText("");
sizeField.setText("");
attributesField.setText("");
}
});
mPanel.add(button);
JLabel fileName = new JLabel("File Name:");
file_nameField = new JTextField(7);
JLabel expansion = new JLabel("Expansion:");
expansionField = new JTextField(7);
JLabel size = new JLabel("Size:");
sizeField = new JTextField(7);
JLabel date_Creation = new JLabel("Creation Date (dd/MM/yyyy):");
date_creationField = new JTextField(7);
JLabel attributesLabel = new JLabel("Attributes:");
attributesField = new JTextField(7);
nPanel.add(fileName);
nPanel.add(file_nameField);
nPanel.add(expansion);
nPanel.add(expansionField);
nPanel.add(size);
nPanel.add(sizeField);
nPanel.add(date_Creation);
nPanel.add(date_creationField);
nPanel.add(attributesLabel);
nPanel.add(attributesField);
}
}
// ФОРМА НА КОТОРОЙ ПРОИСХОДИТ ВЫВОД
class DisplayFrame extends JFrame {
private JTextArea fileListArea;
private FileList fileList;
public DisplayFrame(FileList fileList) {
setTitle("File List");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
fileListArea = new JTextArea();
fileListArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(fileListArea);
add(scrollPane, BorderLayout.CENTER);
this.fileList = fileList;
//fileListArea.setText(fileList.displayFile());
/*String fileListText = "";
List<exercise> files = fileList.getFiles();
for (int i = 0; i < files.size(); i++) {
exercise file = files.get(i);
fileListText += "File Name: " + file.getFile_name() + "\n";
fileListText += "Expansion: " + file.getExpansion() + "\n";
fileListText += "Size: " + file.getSizeFile() + "\n";
fileListText += "Creation Date: " + file.getDate_creation() + "\n";
fileListText += "Attributes: " + file.getAttributes() + "\n";
fileListText += "----------------------------------\n";
fileListArea.setText(fileListText.toString());*/
pack();
setLocationRelativeTo(null);
}
public void displayFilesOnForm() {
String fileListText = fileList.displayFilesOnForm();
fileListArea.setText(fileListText);
}
}
// ГЛАВНАЯ ФОРМА
class Form_M extends JFrame {
private JTextArea textArea;
private FileList fileList;
// створення форми
public Form_M() {
fileList = new FileList();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(300, 300);
// Создаем текстовую область с полосой прокрутки
textArea = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
JMenuBar mb = new JMenuBar();
setJMenuBar(mb);
JMenu expansion = new JMenu("expansion");
expansion.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String a = "a";
List<exercise> files = fileList.getFiles();
for (int i = 0; i < files.size(); i++) {
exercise file = files.get(i);
if (file.getFile_name().equals(a)) {
String message = "File Name: " + file.getFile_name() + "\n"
+ "Expansion: " + file.getExpansion() + "\n"
+ "Size: " + file.getSizeFile() + "\n"
+ "Creation Date: " + file.getDate_creation() + "\n"
+ "Attributes: " + file.getAttributes();
JOptionPane.showMessageDialog(null, message, "File Information", JOptionPane.INFORMATION_MESSAGE);
}
}
}
});
JMenu size = new JMenu("size");
JMenuItem minFile = new JMenuItem("min");
minFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exercise minFile = fileList.minFile();
if (minFile != null) {
JOptionPane.showMessageDialog(null, "Smallest File:\n" +
"Name: " + minFile.getFile_name() + "\n" +
"Expansion: " + minFile.getExpansion() + "\n" +
"Size: " + minFile.getSizeFile() + "\n" +
"Creation Date: " + minFile.getDate_creation() + "\n" +
"Attributes: " + minFile.getAttributes());
} else {
JOptionPane.showMessageDialog(null, "No files found!");
}
}
});
JMenuItem maxFile = new JMenuItem("max");
maxFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exercise maxFile = fileList.maxFile();
if (maxFile != null) {
JOptionPane.showMessageDialog(null, "Largest File:\n" +
"Name: " + maxFile.getFile_name() + "\n" +
"Expansion: " + maxFile.getExpansion() + "\n" +
"Size: " + maxFile.getSizeFile() + "\n" +
"Creation Date: " + maxFile.getDate_creation() + "\n" +
"Attributes: " + maxFile.getAttributes());
} else {
JOptionPane.showMessageDialog(null, "No files found!");
}
}
});
size.add(minFile);
size.addSeparator();
size.add(maxFile);
JMenu date = new JMenu("date");
JMenuItem newFile = new JMenuItem("new");
newFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exercise newFile = fileList.newFile();
if (newFile != null) {
JOptionPane.showMessageDialog(null, "Newest File:\n" +
"Name: " + newFile.getFile_name() + "\n" +
"Expansion: " + newFile.getExpansion() + "\n" +
"Size: " + newFile.getSizeFile() + "\n" +
"Creation Date: " + newFile.getDate_creation() + "\n" +
"Attributes: " + newFile.getAttributes());
} else {
JOptionPane.showMessageDialog(null, "No files found!");
}
}
});
JMenuItem oldFile = new JMenuItem("old");
oldFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exercise oldFile = fileList.oldFile();
if (oldFile != null) {
JOptionPane.showMessageDialog(null, "Oldest File:\n" +
"Name: " + oldFile.getFile_name() + "\n" +
"Expansion: " + oldFile.getExpansion() + "\n" +
"Size: " + oldFile.getSizeFile() + "\n" +
"Creation Date: " + oldFile.getDate_creation() + "\n" +
"Attributes: " + oldFile.getAttributes());
} else {
JOptionPane.showMessageDialog(null, "No files found!");
}
}
});
date.add(newFile);
date.addSeparator();
date.add(oldFile);
mb.add(expansion);
mb.add(size);
mb.add(date);
// панель с кнопками добавления и выведения
JPanel bPanel = new JPanel();
add(bPanel, BorderLayout.SOUTH);
JButton addButton = new JButton("Додавання");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddFile addFileForm = new AddFile(fileList);
addFileForm.setVisible(true);
}
});
bPanel.add(addButton);
JButton displayButton = new JButton("Виведення");
displayButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DisplayFrame displayFrame = new DisplayFrame(fileList);
displayFrame.setVisible(true);
}
});
bPanel.add(displayButton);
JButton deleteButton = new JButton("Видалення");
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
bPanel.add(deleteButton);
JButton editButton = new JButton("Редагування");
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/*List<StorageItem> storageF =
if (storageItems.isEmpty()) {
JOptionPane.showMessageDialog(null, "Немає предметів для редагування.", "Редагувати предмет", JOptionPane.INFORMATION_MESSAGE);
return;
}
JComboBox<String> comboBox = new JComboBox<>();
for (int i = 0; i < storageItems.size(); i++) {
StorageItem item = storageItems.get(i);
comboBox.addItem((i + 1) + ". " + item.getItemName());
}
int option = JOptionPane.showOptionDialog(null, comboBox, "Редагувати предмет", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
if (option == JOptionPane.OK_OPTION) {
int selecteIndex = comboBox.getSelectedIndex();
editSelectedItem(selectedIndex);
}
}*/
}
});
bPanel.add(editButton);
}
}
public class Program {
public static void main(String[] args) {
Form_M mainForm = new Form_M();
mainForm.setVisible(true);
}
} |
|