How to read File and write content into JTextArea? - java

I want to transfer content from a text file into a JTextarea. I suppose my code just needs small adjustments but even through research. I am not able to find out, what is wrong. So far it is just displaying an empty JFrame instead of the text of the file.
this.setSize(this.width, this.height);
this.setVisible(true);
this.jScrollPane = new JScrollPane(this.jTextArea);
this.jPanel = new JPanel();
this.jPanel.setOpaque(true);
this.jTextArea.setVisible(true);
try {
this.jTextArea = new JTextArea();
this.jTextArea.read(new InputStreamReader(
getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")),
null);
} // catch
this.add(this.jScrollPane);
And the usage:
public static void main(String[] args) {
new TextFrame(new File("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name"), 500, 500);
}

You have 2 important issues in this code:
You are creating jScrollPane this.jScrollPane = new JScrollPane(this.jTextArea); before reading the file content using jTextArea
The method does not work read(new InputStreamReader(
getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")), null); Use the one in the following example.
You have to catch the exception to solve the problems
public class TextAreaDemo extends JFrame {
private JScrollPane jScrollPane;
private JTextArea jTextArea ;
private static final String FILE_PATH="/Users/user/IdeaProjects/StackOverflowIssues/file.txt";
public TextAreaDemo() {
try {
jTextArea = new JTextArea(24, 31);
jTextArea.read(new BufferedReader(new FileReader(FILE_PATH)), null);
} catch (Exception e){
e.printStackTrace();
}
jScrollPane = new JScrollPane(this.jTextArea);
this.add(this.jScrollPane);
this.setVisible(true);
this.setSize(400, 200);
}
public static void main(String[] args) {
TextAreaDemo textAreaDemo = new TextAreaDemo();
}

Related

typewriter effect with JTextArea and Scanner JAVA

I'm making a game with my teammate for a school project.
I have created a JTextArea where the lines of a text file would be printed.
I would like to add the typeWriter effect, therefore I searched for answers on this website.
I found some pretty information here :
java-add-typewriter-effect-to-jtextarea
using-timer-to-achieve-typewriter-effect-in-jtextarea
I tried the solutions above, without success.
I'll put my code :
public static void ui() {
Font baseText = new Font("Roboto", Font.PLAIN, 30);
JFrame mainWindow = new JFrame("Main Window");
JTextArea textArea = new JTextArea();
textArea.setFont(baseText);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
JPanel panelButton = new JPanel();
panelButton.setLayout(new FlowLayout());
JButton bContinue = new JButton("Continue");
bContinue.setFont(baseText);
Path path = FileSystems.getDefault().getPath("beginning.txt");
try {
Scanner sc = new Scanner(path);
while(sc.hasNextLine()){
slowDisplay(line, textArea);
}
} catch (IOException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
}
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelButton.add(bContinue);
mainWindow.add(textArea);
mainWindow.add(panelButton, BorderLayout.SOUTH);
mainWindow.setBounds(0, 0, 1920, 1080);
mainWindow.setVisible(true);
}
Here is the content of the slowDisplay Method :
public static void slowDisplay(String line, JTextArea textArea){
Timer timer = new Timer(500, null);
timer.addActionListener(new ActionListener(){
int index=0;
#Override
public void actionPerformed(ActionEvent e) {
if(index<line.length()){
textArea.append(String.valueOf(line.charAt(index++)));
}
else if(index==line.length()){
textArea.append("\n");
}
else{
timer.stop();
}
}
});
timer.start();
}
What it does is that it browses the columns of the text files and write the characters, it creates something awful, unreadable and I don't know why :
The thing
I'll put the content of my text file :
-Mmmh...
-I-I feel cold. Where am I?
-Huh? Is this thing where I'm lying is a human sized plant?!
I looked around, I saw nothing but trees, bushes, and plants.
-What the...
If someone can guide me please, I would be grateful.
I have also tried typewriter effect way long ago.
Instead i used Thread.sleep() function to perform this task.
So here is the method for it.
void typeEffect(String str,JTextArea textArea)throws Exception{
//loop through each character and append it to the JTextArea
for(int i==0;i<str.length();i++){
textArea.append(str.charAt(i)+"");
Thread.sleep(20);//stops for 20 milliseconds
}
}
This looks very simple.
EDIT 1:-
I Have this code which is working as required.
import javax.swing.*;
class DelayTest
{
public static void main(String args[])throws Exception
{
JFrame f=new JFrame("Main Frame");
JTextArea textA=new JTextArea();
f.setSize(720,600);
f.add(textA);
f.setVisible(true);
typeEffect("Hello This is a sample String",textA);
}
static void typeEffect(String str,JTextArea textArea)throws Exception{
//loop through each character and append it to the JTextArea
for(int i=0;i<str.length();i++){
textArea.append(str.charAt(i)+"");
Thread.sleep(100);//stops for 100 milliseconds
}//closing of loop
}//closing of method
}//closing of class
I have executed this code and found it working.

JTable, data, non static method

What's the problem? Non-static variable data cannot be referenced from a static context. I would like to load data from .dat file, but I don't know how can I do it? I tried it but it doesn't work because of the previous error message. Thank you for the helping.
public class StudentFrame extends JFrame {
private StudentData data;
private static String[] columnNames = {"A","B","C","D"};
private void initComponents() {
this.setLayout(new BorderLayout());
}
#SuppressWarnings("unchecked")
public StudentFrame() {
super("Hallgatói nyilvántartás");
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
data = new StudentData();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.dat"));
data.students = (List<Student>)ois.readObject();
ois.close();
} catch(Exception ex) {
ex.printStackTrace();
}
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students.dat"));
oos.writeObject(data.students);
oos.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
});
setMinimumSize(new Dimension(500, 200));
initComponents();
}
public static void main(String[] args) {
StudentFrame sf = new StudentFrame();
sf.setVisible(true);
sf.setLayout(new BorderLayout());
JTable table = new JTable(data,columnNames);//PROBLEM
table.setFillsViewportHeight(true);
/*Jscroll...*/
scrollPane.setViewportView(table);
sf.add(table.getTableHeader(), BorderLayout.PAGE_START);
sf.add(table, BorderLayout.CENTER);
sf.add(scrollPane, BorderLayout.LINE_END);
sf.setVisible(true);
}
}
Suggest restructuring your code and moving the contents of the main method into your StudentFrame class. There is no real reason to use static variables, make TableData a member variable of StudentFrame. Only instantiate StudentFrame from main method, set up the frame and display it. how the contents are displayed should be part of the StudentFrame class.
columnNames is fine as a static, as its a constant.
Your StudentFrame private member variables need public accessors and then you would reference them in main as JTable table = new JTable(sf.getData(), StudentFrame.getColumnNames());

Displaying an image, Java

I'm new to Java GUI, and am having issues displaying an image. My intention is to display a large image and allow the user to click on regions of the image to indicate where certain features are located. Anyway, I'm getting a rough start because I can't even get the image to appear, despite reading Oracle's explanation and other solutions.
I've created a JFrame and used its setContentPane() method to add a JPanel and JLabel. I use the setIcon() method of the JLabel to add an image to it, or at least that's my intention...
Any advice is appreciated, especially if there's a better way of doing this. I'll be using OpenCV to process images, and plan to convert them to Java image (or BufferedImage) before displaying them.
Here is the code. I left out the libraries to save space.
public class Pathology {
public static void main(String[] args) {
PrimaryFrame primaryFrame = new PrimaryFrame();
primaryFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
primaryFrame.setSize(1500, 900);
primaryFrame.setVisible( true );
primaryFrame.setContentPane(primaryFrame.getGui());
try {
primaryFrame.setImage(ImageIO.read(new File("C:\\Users\\Benjamin\\Pictures\\Pathology\\C\\001.png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GUI Class:
public class PrimaryFrame extends JFrame{
//private JTextField textField1;
JPanel gui;
JLabel imageCanvas;
public PrimaryFrame() {
super( "Pathology-1" );
//setLayout(new FlowLayout());
//textField1 = new JTextField("Chup!", 50);
//add(textField1);
}
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui==null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5,5,5,5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300,100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
}
Would you laugh at me if I'd tell you that you just have to put the primaryFrame.setVisible( true ); to the end of the main method? :)
For furture understanding, you don't have to call frame.setVisible(true) every time you want to add/update something in the frame (in an ActionListener, for example). Instead you can call frame.revalidate() and frame.repaint(). (Where frame can be replaced with the particular panel)
You need to setVisible(true) after the call to setImage():
primaryFrame.setImage(ImageIO.read(new
File("C:\\Users\\Benjamin\\Pictures\\Pathology\\C\\001.png")));
because any update to the GUI after setVisible() will not be shown.
That's it and the code should be like this:
public class Pathology {
public static void main(String[] args) {
PrimaryFrame primaryFrame = new PrimaryFrame();
primaryFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
primaryFrame.setSize(1500, 900);
primaryFrame.setContentPane(primaryFrame.getGui());
try {
primaryFrame.setImage(ImageIO.read(new File(
"C:\\Users\\Benjamin\\Pictures\\Pathology\\C\\001.png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
primaryFrame.setVisible( true );
}
}

Choosing between custom JPanel and JTable layout

I'm trying to set up a JPanel which will display lines and text horizontally. It will take a text file, and I'm trying to display the lines and text at the same time given the size of the file. Would it be more appropriate (being relatively new to coding) to use a JTable layout, or make my own layout on a JPanel?
Below is a very basic example on how you could use a JTextPane to display some text from a text file within a JFrame. If you want to do anything more then things like layoutmangers will come into play, but for simple text display this should be suitable:
public class SO{
public static void main(String[] args) throws IOException{
JFrame frame = new JFrame();
JTextPane pane = new JTextPane();
frame.add(pane);
BufferedReader br = new BufferedReader(new FileReader("D:\\Users\\user2777005\\Desktop\\test.txt"));
String everything = "";
try {
StringBuilder sbuild = new StringBuilder();
String line = br.readLine();
while (line != null) {
sbuild.append(line);
sbuild.append('\n');
line = br.readLine();
}
everything = sbuild.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
br.close();
}
pane.setFont(new Font("Segoe Print", Font.BOLD, 12));
pane.setText(everything);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
As shown a JTexPane does also allow for Font changes.
Good luck!

java.awt.Container.checkNotAWindow error in simple gui

I am trying to draw a simple GUI (created with windowbuilder in eclipse), I want to have 2 buttons and a scrollable text area between them. I have created the following code to achieve the above:
public class Main extends JFrame implements ActionListener{
public Font font; //used for the font file
public JTextArea txtDataWillBe;
public Main() throws FontFormatException, IOException{
setTitle("Main title ");
setBounds(100, 100, 1200, 600);
getContentPane().setLayout(null);
txtDataWillBe = new JTextArea();
txtDataWillBe.setText("Your data will display here");
txtDataWillBe.setFont(new Font("Droid Sans", Font.BOLD, 18));
txtDataWillBe.setEditable(false);
txtDataWillBe.setColumns(1);
txtDataWillBe.setBounds(0, 40, 919, 484);
getContentPane().add(txtDataWillBe);
JButton button = new JButton("CLICK TO OPEN");
button.setBounds(0, 0, 940, 40);
button.setFont(new Font("Coalition", Font.PLAIN, 18));
getContentPane().add(button);
JButton btnPrint = new JButton("PRINT");
btnPrint.setBounds(0, 531, 940, 40);
btnPrint.setFont(new Font("Coalition", Font.PLAIN, 18));
getContentPane().add(btnPrint);
}
private final String JTextFile = null;
JFileChooser chooser;
String choosertitle;
public static File deletefile;
EDIT:
public static void main(String s[]) {
JFrame frame = new JFrame("Reader");
Main panel = null;
try {
panel = new Main();
} catch (FontFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
File deleteme = new File (deletefile + "mx.txt");
deleteme.delete();
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
I originally had the JTextarea inside of a JScrollPane (thinking that was the best way to get the scrolling I want working). I removed the JScrollPane thinking that was causing the console error, but I am still getting the error.
Console output is:
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:439)
at java.awt.Container.addImpl(Container.java:1035)
at java.awt.Container.add(Container.java:923)
EDIT: Main added above.
What I am doing wrong with my GUI?
Do I need a JScrollPane and JTextArea to enable vertical scrolling of the loaded text?
Thanks for your help;
Andy
EDIT:
I have edited as per the suggestions below so my code now reads:
public Main() throws FontFormatException, IOException{
JFrame frame = new JFrame("Reader ");
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
File deleteme = new File (deletefile + "mx.txt");
deleteme.delete();
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(getPreferredSize());
frame.setVisible(true);
The rest of the code is as before but all I am getting displayed is a blank grey frame without any of my components (although they are all showing in windowbuilder).
Thanks for the continued help.
The console output is describing exactly what is wrong here.
IllegalArgumentException: adding a window to a container
In the line frame.getContentPane().add(panel,"Center"); you add panel into your content pane, but panel itself is an instance of Main extends JFrame.
You should remove any reference to the outer frame at all and just add the window listener to the Main frame, i.e. the main code reduces to something like
JFrame frame = new Main();
frame.addWindowListener( ... );
frame.setVisible(true);
You may also want to move the addWindowListener part inside class Main.

Categories