Read JTextfield put into word file - java

I create a small GUI with Netbeans. I've got an issue with settext and gettext. I'm raelly happy if you can say whre the problem is and what i have to do or you show me the solution.
i want to create a word file by clicking a button. This is working fine but there should be some text out of a JTextfiel in the word file and this isnt working.
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.HeadlessException;
import java.io.FileOutputStream;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.IOException;
private void createActionPerformed(java.awt.event.ActionEvent evt) {
try{
FileOutputStream outStream = new FileOutputStream("Bewerberinterview.docx");
XWPFDocument doc;
doc = new XWPFDocument();
XWPFParagraph paraTit=doc.createParagraph();
paraTit.setAlignment(ParagraphAlignment.CENTER);
XWPFRun paraTitRun=paraTit.createRun();
paraTitRun.setBold(true);
paraTitRun.setFontSize(20);
paraTitRun.setText(title.getText());
doc.createParagraph().createRun().addBreak();
doc.createParagraph().createRun().setText(name_content.getText());
doc.write(outStream);
doc.close();
System.out.println("createdocument.docx written successully");
}catch (HeadlessException | IOException e){
JOptionPane.showMessageDialog(null, e);
}
}
When I starting my application and put in some Text in the box and clicking "button 1 = create". The file will create fine but there is no text in it.

The following code, which is a Minimal, Reproducible Example for your described problem, works as I would expect it should.
For each click on button write it writes the file Bewerberinterview.docx file having content from the both text fields.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.apache.poi.xwpf.usermodel.*;
import java.io.File;
import java.io.FileOutputStream;
public class TextDemo extends JPanel implements ActionListener {
protected JTextField title;
protected JTextField name_content;
protected JButton write;
public TextDemo() {
super();
title = new JTextField(20);
name_content = new JTextField(20);
write = new JButton("write");
write.addActionListener(this);
add(title);
add(name_content);
add(write);
}
public void actionPerformed(ActionEvent evt) {
String titleText = title.getText();
String name_contentText = name_content.getText();
System.out.println(titleText);
System.out.println(name_contentText);
try {
FileOutputStream outStream = new FileOutputStream("Bewerberinterview.docx");
XWPFDocument doc = new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = paragraph.createRun();
run.setBold(true);
run.setFontSize(20);
run.setText(titleText);
doc.createParagraph().createRun().addBreak();
doc.createParagraph().createRun().setText(name_contentText);
doc.write(outStream);
outStream.close();
doc.close();
System.out.println("File " + new File("Bewerberinterview.docx").getAbsolutePath() + " written successully.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TextDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add contents to the window.
frame.add(new TextDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
So your described problem does not exists.
It does? Well then show a Minimal, Reproducible Example which shows the problem.

Related

Swing GUI freezes after clicking JButton for three times [duplicate]

I wrote a simple application in Swing that writes text to a file. Here is my main class:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class WritingTextToFileApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new MainFrame("Application");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Here is the other class:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
public MainFrame(String title) {
super(title);
//Set Layout Manager
setLayout(new BorderLayout());
//Create Swing Components
JTextArea textArea = new JTextArea();
JButton button = new JButton("Add");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
File file = new File("C:\\Users\\Vincent Wen\\Desktop\\Test.txt");
try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
br.write(input);
br.newLine();
} catch (IOException ex) {
System.out.println("Unable to write to file:" + file.toString());
}
}
});
//Add Swing components to conent pane
Container c = getContentPane();
c.add(textArea, BorderLayout.CENTER);
c.add(button, BorderLayout.SOUTH);
}
}
Whenever I press the button, the program freezes and nothing happens. Is there something wrong with the code? I am new to Swing so any help would be appreciated.
Swing runs the actions synchronously in the same thread that's handling the GUI input and rendering. That means that when you click the button, it waits for the action listener to complete running before it goes back to handling input and drawing the GUI. In this case, it's effectively stopping the GUI from running until you type something into the console.
You can use SwingWorker to run it asynchronously so that it continues running the GUI while it runs the action.
The problem is that when you press the button, java expects to read data from System.ini (console).
Try to start your application by using the java command on a console. Then enter some text in the console after pressing the button and press enter. Your program you work.
I fixed my problem by using textArea.getText() instead of using scanner.

Why does my audio playback freeze ActionListners?

Im using the this javaPlayer to playback my sounds.
But in my larger
project it freezes/ignores almost every input JFrame.EXIT_ON_CLOSE and ActionListners that alter the frame content. I tried to repruduce the issue in this snippet.
The btn.addActionListener(e -> System.out.println("Check1")); is not applied to my button. Only if I comment out the whole try/catch-block the "Check1" is also reached.
What could be the problem? I already tried to send the playerpart with Swing.invokeLater to another thread.
package mainMVC;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
public class Alone {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JButton btn = new JButton("Test");
btn.addActionListener(e -> System.out.println("Check"));
frame.add(btn);
frame.pack();
try (FileInputStream fis = new FileInputStream("src/EgyptianTavernFullofGuitarists_1.mp3"))
{
Player player = new Player(fis);
player.play();
} catch (IOException | JavaLayerException e) {
e.printStackTrace();
}
btn.addActionListener(e -> System.out.println("Check1"));
}
}
I don't know what's a problem. I've tested your code in my IDE, and it works. During start Frame, music plays. ActionListener returns Check and music doesn't stop, same EXIT_ON_CLOSE.
EDIT: I found that execution is stopped till the playback of the file is finished.
I managed it with a manual thread creation. Now both "Check" and "Check1" are printed.
File: Audio.java
package mainMVC;
import java.io.FileInputStream;
import java.io.IOException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
class Audio extends Thread {
public void run(){
try (FileInputStream fis = new FileInputStream("src/EgyptianTavernFullofGuitarists_1.mp3"))
{
Player player = new Player(fis);
player.play();
} catch (IOException | JavaLayerException e) {
e.printStackTrace();
}
}
}
File: Alone.java
package mainMVC;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Alone {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JButton btn = new JButton("Test");
btn.addActionListener(e -> System.out.println("Check"));
frame.add(btn);
frame.pack();
Audio myThread = new Audio();
myThread.start();
btn.addActionListener(e -> System.out.println("Check1"));
}
}

Java Swing button freezes program

I wrote a simple application in Swing that writes text to a file. Here is my main class:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class WritingTextToFileApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new MainFrame("Application");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Here is the other class:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
public MainFrame(String title) {
super(title);
//Set Layout Manager
setLayout(new BorderLayout());
//Create Swing Components
JTextArea textArea = new JTextArea();
JButton button = new JButton("Add");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
File file = new File("C:\\Users\\Vincent Wen\\Desktop\\Test.txt");
try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
br.write(input);
br.newLine();
} catch (IOException ex) {
System.out.println("Unable to write to file:" + file.toString());
}
}
});
//Add Swing components to conent pane
Container c = getContentPane();
c.add(textArea, BorderLayout.CENTER);
c.add(button, BorderLayout.SOUTH);
}
}
Whenever I press the button, the program freezes and nothing happens. Is there something wrong with the code? I am new to Swing so any help would be appreciated.
Swing runs the actions synchronously in the same thread that's handling the GUI input and rendering. That means that when you click the button, it waits for the action listener to complete running before it goes back to handling input and drawing the GUI. In this case, it's effectively stopping the GUI from running until you type something into the console.
You can use SwingWorker to run it asynchronously so that it continues running the GUI while it runs the action.
The problem is that when you press the button, java expects to read data from System.ini (console).
Try to start your application by using the java command on a console. Then enter some text in the console after pressing the button and press enter. Your program you work.
I fixed my problem by using textArea.getText() instead of using scanner.

Java - Changing Icon of JLabel does not Work

I am trying to change the icon (background) of a JLabel, but I am having an issue with the icon not updating. Whenever I tried lblStatusImg.setIcon(new ImageIcon(Brix_Updater_Module.class.getResource("/resources/fail.png"))); to change the JLabel in the main method, the compiler was first complaining that the variable lblStatusImg did not exist, so I moved it from the JFrame initialization method to a class level variable. After this, Eclipse complained that I was trying to reference a nonstatic method from static context, so I made lblStatusImg static. This made it possible for the program to compile, but the icon did not change whenever it was supposed to.
Since it's kind of hard to understand my problem here is a download link for an Eclipse workspace that demonstrates my problem. When you first open it, you will notice that there are some problems with it. They were left there on purpose to make it easier for you to see where I am having a hard time. If Eclipse asks you to make the items in question static, just do it and then run the program. You'll notice that it does not change the label icons as it should.
Since not all of you have Eclipse, here's the entire code from the workspace.
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.Window.Type;
import java.io.BufferedOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class StackOverflow_Image_Resource_Demo {
private JFrame frmUpdate;
JLabel lblStatusImg = new JLabel("");
JButton btnUpdateComplete = new JButton("OK");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StackOverflow_Image_Resource_Demo window = new StackOverflow_Image_Resource_Demo();
window.frmUpdate.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
lblStatusImg.setIcon(new ImageIcon(StackOverflow_Image_Resource_Demo.class.getResource("success.png")));
btnUpdateComplete.setVisible(true);
}
catch(Exception e)
{
Component frame = null;
lblStatusImg.setIcon(new ImageIcon(StackOverflow_Image_Resource_Demo.class.getResource("/resources/fail.png")));
JOptionPane.showMessageDialog(frame, "Update Failed", "Update Failed", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
/**
* Create the application.
*/
public StackOverflow_Image_Resource_Demo() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmUpdate = new JFrame();
frmUpdate.setType(Type.UTILITY);
frmUpdate.setTitle("StackOverflow Image Resource Issue Demo");
frmUpdate.setBounds(100, 100, 450, 300);
frmUpdate.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmUpdate.getContentPane().setLayout(null);
//JLabel lblStatusImg = new JLabel(""); - Commented out when I made lblStatusImg class level.
lblStatusImg.setIcon(new ImageIcon(StackOverflow_Image_Resource_Demo.class.getResource("/resources/updating.gif")));
lblStatusImg.setBounds(10, 22, 414, 97);
frmUpdate.getContentPane().add(lblStatusImg);
//JButton btnUpdateComplete = new JButton("OK"); - Commented out when I made btnUpdateComplete class level.
btnUpdateComplete.setVisible(false);
btnUpdateComplete.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
System.exit(1);
}
});
btnUpdateComplete.setBounds(170, 179, 89, 23);
frmUpdate.getContentPane().add(btnUpdateComplete);
}
}
Here is a newer version of my code that updates the image, but doesn't fully load the UI until everything else is done.
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.Window.Type;
import java.io.BufferedOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class StackOverflow_Image_Resource_Demo {
private JFrame frmUpdate;
JLabel lblStatusImg = new JLabel("");
JButton btnUpdateComplete = new JButton("OK");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StackOverflow_Image_Resource_Demo window = new StackOverflow_Image_Resource_Demo();
try {
lblStatusImg.setIcon(new ImageIcon(StackOverflow_Image_Resource_Demo.class.getResource("success.png")));
btnUpdateComplete.setVisible(true);
}
catch(Exception e)
{
Component frame = null;
lblStatusImg.setIcon(new ImageIcon(StackOverflow_Image_Resource_Demo.class.getResource("/resources/fail.png")));
JOptionPane.showMessageDialog(frame, "Update Failed", "Update Failed", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
window.frmUpdate.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public StackOverflow_Image_Resource_Demo() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmUpdate = new JFrame();
frmUpdate.setType(Type.UTILITY);
frmUpdate.setTitle("StackOverflow Image Resource Issue Demo");
frmUpdate.setBounds(100, 100, 450, 300);
frmUpdate.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmUpdate.getContentPane().setLayout(null);
//JLabel lblStatusImg = new JLabel(""); - Commented out when I made lblStatusImg class level.
lblStatusImg.setIcon(new ImageIcon(StackOverflow_Image_Resource_Demo.class.getResource("/resources/updating.gif")));
lblStatusImg.setBounds(10, 22, 414, 97);
frmUpdate.getContentPane().add(lblStatusImg);
//JButton btnUpdateComplete = new JButton("OK"); - Commented out when I made btnUpdateComplete class level.
btnUpdateComplete.setVisible(false);
btnUpdateComplete.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
System.exit(1);
}
});
btnUpdateComplete.setBounds(170, 179, 89, 23);
frmUpdate.getContentPane().add(btnUpdateComplete);
}
}
Two things come to find. The first is, as you say, you're trying to reference a non-static variable from a static context.
The second is, you don't seem to understand how threading works...
Basically, main is typically executed within the "main" thread (when executed by the JVM).
You then use EventQueue.invokeLater. Which as, the name suggests, will execute the Runnable "later"...at some time in the future...
EventQueue.invokeLater(new Runnable() {
public void run() {
You then try and change the the icon (let's pass over the non-static reference for a momement)...but lblStatusImg won't have been initialized nor is it likely to have been displayed, as the Runnable has not yet been executed, meaning, even if you didn't run into a NullPointerException, you won't see the change...
You can test by adding a System.out in your Runnable and before the first lblStatusImg.setIcon call in the main method.
What you should do is...
Move the "status" change change to within the Runnable context.
Provide a setStatus method that is capable of changing the label and UI content as required based on the provide status
For example...
public static final int SUCCESS = 0;
public static final int FAIL = 0;
//...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StackOverflow_Image_Resource_Demo window = new StackOverflow_Image_Resource_Demo();
// This e
window.frmUpdate.setVisible(true);
window.setStatus(StackOverflow_Image_Resource_Demo.SUCCESS);
} catch (Exception e) {
e.printStackTrace();
Component frame = null;
window.setStatus(StackOverflow_Image_Resource_Demo.FAIL);
JOptionPane.showMessageDialog(frame, "Update Failed", "Update Failed", JOptionPane.ERROR_MESSAGE);
window.dispose();
}
}
});
}
You should avoid exposing instance fields as public and instead, provide methods that either change their state indirectly (such as setStatus) or directly (setStatusIcon). In this case, I prefer the first method as this allows the class to determine what a change in status actually means.

Java Eclipse text editor

Good day.
So I'm working on this project and I'm having one question.
I have an encyclopedia and I want to add a text editor.
I have a text and a scrollpanel and I want, when I select a sentence of my text and I press one button, to change the font, make the text bold, italic, underlined etc. How can I do that?
My code looks like this, the text.txt is a text file with "aaaa" in it.
package test;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Rectangle;
import javax.swing.JFrame;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class test extends JFrame {
private static final long serialVersionUID = 1L;
JFrame test = new JFrame("test");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test frame = new test();
frame.setVisible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public test() {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(new Rectangle(0, 0, 0, 0));
getContentPane().setLayout(null);
test.setName("frame");
test.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
test.setBounds(300,0,800,800);
test.setResizable(false);
test.getContentPane().setLayout(null);
JScrollPane text = new JScrollPane();
text.setBackground(Color.DARK_GRAY);
text.setBounds(0, 0, 500, 400);
getContentPane().add(text);
JTextArea textarea = new JTextArea();
setBackground(Color.WHITE);
textarea.setEditable(false);
textarea.setWrapStyleWord(true);
textarea.setLineWrap(true);
try{
FileInputStream fstream = new FileInputStream("D:\\Facultate\\anul 2\\Java Workspace\\test\\src\\text.txt");
DataInputStream in = new DataInputStream(fstream);
Reader reader = new InputStreamReader(in);
textarea.read(reader, fstream);
}catch(Exception e){System.err.println("Error: " + e.getMessage());}
text.setViewportView(textarea);
}
}
From the documentation: "A JTextArea is a multi-line area that displays plain text." So if you want different fonts, etc. in one area, you'll have to use another control, probably RTFEditorKit
There is an amazing and Free Text Editor for Java. You can find it at
Download a ready-to-use CKEditor package that best suits your needs.
It's a product distributed by Amazon Web Services.

Categories