我正在做一项任务,我有点坚持。我有这些要求:
我将从我的临时文件夹中的两个文件中获取输入并将其读入 屏幕中间的文本字段。
我无法弄清楚为什么两个按钮都不会出现。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class P_Supplemental_11 extends JFrame {
JPanel jpnl1 = new JPanel();
JButton jbtReadFile1 = new JButton("Get Student Names");
JButton jbtReadFile2 = new JButton("Get Student Grades");
JTextField jtxtFilePath = new JTextField();
JLabel jlblDesc = new JLabel("Enter the file name here:");
JTextArea jtxtAfileContents = new JTextArea();
P_Supplemental_11() {
this.setLayout(new BorderLayout(5, 10));
jpnl1.setLayout(new GridLayout(2, 2));
jpnl1.add(jlblDesc);
jpnl1.add(jtxtFilePath);
add(jpnl1, BorderLayout.NORTH);
add(jtxtAfileContents, BorderLayout.CENTER);
add(jbtReadFile1, BorderLayout.SOUTH);
jbtReadFile1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jbtReadFileActionPerformed(evt);
}
});
add(jbtReadFile2, BorderLayout.SOUTH);
jbtReadFile2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jbtReadFileActionPerformed2(evt);
}
});
} // end constructor
private void jbtReadFileActionPerformed(ActionEvent evt) {
try {
File inFile = new File("c:/temp/studentnames.txt");
Scanner input = new Scanner(inFile);
String fileContents = "";
while(input.hasNext()) {
fileContents+= input.nextLine() + "\n";
} // end while
jtxtAfileContents.setText(fileContents);
input.close();
} // end action method for jbtReadFile button
catch (FileNotFoundException ex) {
Logger.getLogger(P_Supplemental_11.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jbtReadFileActionPerformed2(ActionEvent evt) {
try {
File inFile = new File("c:/temp/studentscores.txt");
Scanner input = new Scanner(inFile);
String fileContents = "";
while(input.hasNext()) {
fileContents+= input.nextLine() + "\n";
} // end while
input.close();
jtxtAfileContents.setText(fileContents);
} // end action method for jbtReadFile button
catch (FileNotFoundException ex) {
Logger.getLogger(P_Supplemental_11.class.getName()).log(Level.SEVERE, null,
ex);
}
}
public static void main(String[] args) {
P_Supplemental_11 frame = new P_Supplemental_11();
frame.setTitle("P_Supplemenetal_10");
frame.setSize(410, 520);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
答案 0 :(得分:2)
您没有在分配中指定的GridLayout
位置使用BorderLayout.SOUTH
的小组。
2个按钮无法在BorderLayout
中共享同一位置,而同时可以看到:
add(jbtReadFile1, BorderLayout.SOUTH);
add(jbtReadFile2, BorderLayout.SOUTH);