Java Eclipse text editor - java

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.

Related

How to call deriveFont() correctly after Font.createFont() in Java?

I want to resize a custom font to match my layout.
But sadly font.deriveFont(128.0f); has no effect at all. I already tried some hints I found but nothing helped yet.
The output of the System.out.println(font) equals to java.awt.Font[family=Arial,name=Arial,style=plain,size=1]
package main;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.EmptyBorder;
public class FontTest {
public static void main(String[] args){
String fName = "fonts/arial.ttf";
InputStream is = FontTest.class.getResourceAsStream(fName);
Font font = null;
try {
font = Font.createFont(Font.TRUETYPE_FONT, is);
font.deriveFont(128.0f);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EmptyBorder padding_h1 = new EmptyBorder(10, 10, 10, 10);
System.out.println(font);
JLabel text = new JLabel("Hallo Welt!");
text.setFont(font);
text.setBorder(padding_h1);
frame.add(text);
frame.setVisible(true);
}
}
font.deriveFont does not change font. Rather, it:
Creates a new Font object by replicating the current Font object and applying a new size to it.
The newly created Font object is returned.
So just calling it like this:
font.deriveFont(128.0f);
will create a new Font object, and throw it away immediately, as you are not using the return value at all.
You can move the deriveFont call to where you need the new font:
text.setFont(font.deriveFont(128.0f));
Alternatively, actually change font by reassigning it:
font = font.deriveFont(128.0f);

Read JTextfield put into word file

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.

Highlighter addHighlight not changing text color

I have a JTextArea in which I highlight some text using the addHighlight method of the Highlighter I get from the JTextArea. It highlights the text but it does not change the text color of the highlighted text to the selectedTextColor I have set.
Here is an example:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
public class SSCCE {
private JFrame frame;
private JTextArea textArea;
public SSCCE() {
frame = new JFrame();
frame.setTitle("Huge Text");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea("abcd abcd abcd");
textArea.setBackground(Color.DARK_GRAY);
textArea.setForeground(Color.LIGHT_GRAY);
textArea.setSelectionColor(Color.LIGHT_GRAY);
textArea.setSelectedTextColor(Color.DARK_GRAY);
Highlighter highLighter = textArea.getHighlighter();
HighlightPainter highLightPainter = new DefaultHighlighter.DefaultHighlightPainter(textArea.getSelectionColor());
try {
highLighter.addHighlight(0, 10, highLightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
frame.add(new JScrollPane(textArea));
frame.setSize(400, 350);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SSCCE();
}
});
}
}
Worth reading about Using Text Components
If you intend to use an unstyled text component then choose text field, password field, formatted text field, or text area.
If you intend to use a styled text component, see How to Use Editor Panes and Text Panes
JTextArea doesn't support this functionality to style a sub set of the entire content. It applies styles but across the entire content.
Find a sample code here change specific text color in java

JTextField crops text when using custom TrueType font. How to make it display text normally?

So, the problem is definitely with the font. Question is how to make the text field display text fully. Example:
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
class Example extends JFrame{
public Example(){
setLayout(new BorderLayout());
Font myFont = null;
try {
URL link = new URL("http://rghost.ru/download/50564305/e6efddd74f598b86f7ac704cab72e430a490bc7f/digital-7.ttf");
ReadableByteChannel rbc = Channels.newChannel(link.openStream());
File font_file = new File("font.ttf");
if(!font_file.exists())
font_file.createNewFile();
FileOutputStream fos = new FileOutputStream(font_file);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
myFont = Font.createFont(Font.TRUETYPE_FONT, font_file);
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JTextField myField = new JTextField("sample text");
myField.setFont(myFont.deriveFont(32.0f));
add(myField, BorderLayout.NORTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 400);
setVisible(true);
}
public static void main(String[] args){
new Example();
}
}
The font is Digital 7: dafont.com
PROBLEM SOLVED
The solution is to convert the font here (or other such place) to PFM and use it like that:
Font myFont = Font.createFont(Font.TYPE1_FONT, new File("res/my_font.pfm"));
I suspect the problem is with the Font rather than Java.
I found a page at http://onlinefontconverter.com/font?id=p1 that claims to (sometimes) fix invalid fonts, but cannot locate one that will simply report the validity. Try running it through that first.
myField.setPreferredSize(new Dimension(40,40)); // where the first argument is the width of the component,
// and 2nd is the height(that's what you need )

How do I get rid of the border made by capturing a jframe image to file?

So I made an application that creates a graphical timeline from a csv file. I have that part finished now I just need help getting the image "pretty". When capturing the image the border from the JFrame is captured too! How do I make it such that the border is not captured? Or how do I get rid of it and keep the image size?
Here is a simple example. Just to clarify your needs. Based on solution of How to remove the title bar from a JFrame Screenshot?.
The following program takes screenshot of its JFrame and writes it to the file.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
/* Writes self screenshot on Screenshot button click. */
public class ScreenshotFrame extends JFrame {
public ScreenshotFrame () {
initComponents();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new ScreenshotFrame().setVisible(true);
}
});
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JButton screenshotButton = new JButton();
screenshotButton.setText("Screenshot");
screenshotButton.setToolTipText("Take my screenshot.");
screenshotButton.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
writeImageToFile(getScreenshot());
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(screenshotButton);
pack();
}
/* Modified method from pointed solution. */
private BufferedImage getScreenshot() {
Dimension dim = this.getContentPane().getSize();
BufferedImage image =
new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);
this.getContentPane().paint(image.getGraphics());
return image;
}
/* Write image to png file in current dir.*/
private void writeImageToFile(BufferedImage image) {
try {
File file = new File("JFrameScreenshot.png");
file.createNewFile();
ImageIO.write(image, "png", file);
} catch (IOException ex) {/*do smth*/ }
}
}
Does this what you want, if_zero_equals_one? If not, maybe you could add some code to your question, that tries to do what you want.
P.S. Thanks to Darien and camickr, who pointed where to find the source for that
example.
Maybe this should be a comment. But it's clearer with such formatting.
BufferedImage image = (BufferedImage)createImage(getContentPane().getSize().width, getContentPane().getSize().height);
getContentPane().paint(image.getGraphics());
This is what I believe I was looking for.

Categories