Прочитать из файла и добавить в jframeJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Прочитать из файла и добавить в jframe

Сообщение Anonymous »

Я пытался отобразить входные данные моего txt-файла (изображение и текст) в jframe, но все еще не могу. у меня уже есть jpanel как место для отображения этого. может быть, мне нужно что-то отредактировать в свойствах? мой макет набора фреймов имеет значение null, и у меня есть 3 jpanel для отображения трех данных с соответствующим изображением.

Код: Выделить всё

private void loadCandidates() {
// Open the candidates file
File file = new File("C:\\Users\\nurul\\Desktop\\votingjava\\prescandidate.txt");
if (!file.exists()) {
System.out.println("File does not exist: " + file.getAbsolutePath());
return;  // Exit if the file doesn't exist
}

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;

// Using panels for each candidate
int candidateIndex = 0;  // To decide which panel to add to

while ((line = br.readLine()) != null) {
line = line.trim();
String[] parts = line.split("\\s*:\\s*");

if (parts.length == 5) {
// Extract candidate details
String id = parts[0].trim();
String name = parts[1].trim();
String year = parts[2].trim();
String motto = parts[3].trim();
String imgpath = parts[4].trim();

// Debug print to confirm loaded candidate info
System.out.println("Loaded candidate: " + name);

// Image path check
File imageFile = new File(imgpath);
if (!imageFile.exists()) {
System.out.println("Image not found: " + imgpath);
}

// Create candidate panel
JPanel candidatePanel = new JPanel();
candidatePanel.setLayout(new BoxLayout(candidatePanel, BoxLayout.Y_AXIS));
candidatePanel.setBorder(BorderFactory.createTitledBorder("Candidate"));

JLabel nameLabel = new JLabel("Name: " + name);
JLabel yearLabel = new JLabel("Year: " + year);
JLabel mottoLabel = new JLabel("Slogan: " + motto);

// Load and scale the image
ImageIcon candidateImageIcon = new ImageIcon(imgpath);
Image scaledImage = candidateImageIcon.getImage().getScaledInstance(150, 150, Image.SCALE_SMOOTH);
candidateImageIcon = new ImageIcon(scaledImage);

JLabel imageLabel = new JLabel(candidateImageIcon);

// Add components to the candidate panel
candidatePanel.add(imageLabel);
candidatePanel.add(nameLabel);
candidatePanel.add(yearLabel);
candidatePanel.add(mottoLabel);

// Ensure the layout of the panel is refreshed
candidatePanel.revalidate();
candidatePanel.repaint();

// Add the candidate panel to the appropriate panel (panel1, panel2, or panel3)
switch (candidateIndex) {
case 0:
jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
jPanel1.add(candidatePanel);
break;
case 1:
jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.Y_AXIS));
jPanel2.add(candidatePanel);
break;
case 2:
jPanel3.setLayout(new BoxLayout(jPanel3, BoxLayout.Y_AXIS));
jPanel3.add(candidatePanel);
break;
default:
break;
}

// Revalidate and repaint to update the UI
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jPanel1.revalidate();
jPanel1.repaint();
jPanel2.revalidate();
jPanel2.repaint();
jPanel3.revalidate();
jPanel3.repaint();
}
});

// Increment candidate index to assign the next candidate to the next panel
candidateIndex++;
} else {
System.out.println("Invalid line format: "  + line);
}
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error reading prescandidate.txt: " + e.getMessage(),
"File Error", JOptionPane.ERROR_MESSAGE);
}
Сначала я пытался встроить jlabel в фрейм, а затем написать код, но это не сработало. так что теперь я просто пишу код для этой части вручную. я хочу отобразить изображение и данные, считанные из txt-файла. Я попробовал отладку, и все мои пути верны. он просто не будет отображаться в рамке.

Подробнее здесь: https://stackoverflow.com/questions/792 ... -in-jframe
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»