i\'m working on my first GUI program and almost finished the last class is a jFrame that has a .txt file and a button to close the window and i don\'t know how to append my
To read a file into a JTextArea
you can simply use JTextArea#read, this will, however, discard the current contents of the JTextArea
Updated
After adding the code to an IDE, I've noted that you are not adding rules
(the JTextArea
) to anything so it will never be visible...
The general structure of how you create your UI is also a little skewed, try something more like...
public class Rules extends JFrame {
public Rules() throws IOException {
super();
// Initial setu[
setTitle("Rules Of Santorini Board Game");
// Create the basic UI content
JTextArea textArea = new JTextArea(40, 20);
JScrollPane scrollPane = new JScrollPane(textArea);
// Read the file
try (BufferedReader reader = new BufferedReader(new FileReader(new File("resources/New Text Document.txt")))) {
textArea.read(reader, "File");
} catch (IOException exp) {
exp.printStackTrace();
}
getContentPane().setBackground(Color.ORANGE);
JButton ok = new JButton("Got It");
add(textArea, BorderLayout.SOUTH);
add(ok, BorderLayout.SOUTH);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//dispose();
//?? No idea what this is for, but it won't do much
setVisible(false);
}
});
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Don't use MouseListener
s with buttons, instead you should be using an ActionListener
Don't use null
layouts. Pixel perfect layouts are an illusion in modern UI design, you have no control over fonts, DPI, rendering pipelines or other factors that will change the way that you components will be rendered on the screen.
Swing was designed to work with layout managers to overcome these issues. If you insist on ignoring these features and work against the API design, be prepared for a lot of headaches and never ending hard work...
where to place my .txt file?
You can try any one
// Read from same package
InputStream in = getClass().getResourceAsStream("abc.txt");
// Read from resources folder parallel to src in your project
File file = new File("resources/abc.txt");
// Read from src/resources folder
InputStream in = getClass().getResourceAsStream("/resources/abc.txt");
--EDIT--
Must read A Visual Guide to Layout Managers.
Here is some points from your code:
null
layout Rules.setLayout(null);
JFrame#setVisible(true);
in the end when all the components are addedSwingUtilities.invokeLater()
to initialize the GUI