【发布时间】:2011-05-04 01:46:05
【问题描述】:
所以我有一个简单的 GUI,它只能打开文本文件,并且应该只将它们显示在要编辑的文本区域中。我知道我的字符串包含文件内容,因为我可以打印出来,但是当我尝试将它添加到我的文本区域时,它没有显示出来。我想知道这是否是文本区域重叠的问题,但我似乎找不到错误。
我的代码的第一部分只是创建了 GUI。另一部分应该打开一个文件并用它填充文本区域。问题到底出在哪里,我该如何解决?任何帮助将不胜感激。
这是我处理创建框架和面板的代码的一部分:
public class MenuView extends JFrame {
private JPanel centerPanel;
private JPanel bottomPanel;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem openItem;
private JMenuItem closeItem;
private JButton setButton;
private JTextField text;
private JTextArea label;
private JMenuItem fileNew;
public MenuView(){
super();
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setTitle("Menu Demo");
//The center panel that will contain text
centerPanel = new JPanel();
centerPanel.setLayout(new FlowLayout());
label = new JTextArea(400,500);
centerPanel.add(label);
add(centerPanel, BorderLayout.CENTER);
//The bottom panel with the text field and button
bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(1, 2));
setButton = new JButton("Set Text");
text = new JTextField();
bottomPanel.add(setButton);
bottomPanel.add(text);
add(bottomPanel, BorderLayout.SOUTH);
//Setting up the menu
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
fileNew = new JMenu("New");
openItem = new JMenuItem("Open");
closeItem = new JMenuItem("Exit");
fileMenu.add(openItem);
fileMenu.add(closeItem);
fileMenu.add(fileNew);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
setButton.addActionListener(new ButtonCommand(label, text));
closeItem.addActionListener(new QuitMenuCommand());
openItem.addActionListener(new OpenMenuCommand(label));
}
public static void main(String [] args){
MenuView v = new MenuView();
v.setVisible(true);
}
}
这是处理打开文件的代码:
public class OpenMenuCommand implements ActionListener {
private JTextArea theLabel;
private JFileChooser fc;
private String k = "";
public OpenMenuCommand(JTextArea l){
theLabel = l;
theLabel.getParent();
fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Text file", "txt"));
}
public void actionPerformed(ActionEvent e) {
StringBuffer text = new StringBuffer();
int returnValue = fc.showOpenDialog(null);
if(returnValue == fc.APPROVE_OPTION){
theLabel.removeAll();
File f = fc.getSelectedFile();
try{
BufferedReader inFile = new BufferedReader(new FileReader(f));
String in = inFile.readLine();
while(in != null){
k = k + in;
in = inFile.readLine();
}
System.out.println(k);
theLabel.setText(k);
inFile.close();
theLabel.setVisible(true);
}catch(FileNotFoundException exc){
//Should never trigger
}catch(IOException exc){
theLabel.setText("Error reading in file.");
}
}
}
}
【问题讨论】:
-
有趣的一个。可以发截图吗?此外,如果您认为它可能与 JTextField 重叠,请尝试使用其中已有的一些文本来初始化文本字段,以进行测试。如果显示初始文本,那么我猜您可能没有重叠问题。
-
@normalocity:它与重叠无关,而是将一个非常大的组件(JTextArea)添加到一个使用 FlowLayout 的小型容器中。
-
这不是将数据加载到文本区域的方式。只需使用 JTextArea.read(...) 方法。它的一行代码。无需循环逻辑。
标签: java swing user-interface textarea action