Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String filename = fileName.getText();
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
filename = br.readLine();
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
if(line.contains(text)){
String newline = "\n";
jTextArea1.append(line + newline);
hasError = false;
}
}
if (hasError) {
JOptionPane.showMessageDialog(null, "Text Not Found");
br.close();
fr.close();
}
}}catch(IOException e){
JOptionPane.showMessageDialog(null, "File Not Found");
} }
});
So, in this function, I want to read some text files within a mentioned directory/folder by input. User selects the directories/folder using JFILECHOOSER method and the output will be listed in a textbox [Directory]. Lets say that fileName is the text field where users input the name of the file, after users input their file name, they click on a start button. The start button functions on whereby it will look into the given directory/folder [the textbox] and search for text files and output the text files' name using system.out.printIn. I have not tried the code for directory/folder path because I'm not sure how to code for it. Any help or guide to this problem? I have only created one class and I'm new to JAVA GUI
The full code is as below:
package com.directory.file;
import java.awt.BorderLayout;
import java.awt.Event;
import java.awt.EventQueue;
import java.awt.TextArea;
import java.awt.TextComponent;
import java.awt.Event.*;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;
import javax.lang.model.element.VariableElement;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Component;
import java.sql.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JSplitPane;
import javax.swing.JLayeredPane;
import javax.swing.JDesktopPane;
import javax.swing.JComboBox;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SpinnerDateModel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.text.JTextComponent;
import java.awt.Color;
import javax.swing.SwingConstants;
import java.awt.ComponentOrientation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import com.toedter.calendar.JDateChooser;
import javax.swing.JSpinner;
import org.eclipse.wb.swing.FocusTraversalOnArray;
public class Directory extends JFrame {
private JPanel contentPane;
private JTextField txtKeyword;
private JTextField fileName;
private JTextArea jTextArea1;
private JDateChooser dateChooser;
private JSpinner spinner_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Directory frame = new Directory();
frame.setVisible(true);
frame.setSize(450,630);
frame.fileName.requestFocus();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Directory() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 436, 631);
contentPane = new JPanel();
contentPane.setAlignmentX(Component.LEFT_ALIGNMENT);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDirectory = new JLabel("Directory:");
lblDirectory.setBounds(20, 29, 55, 24);
contentPane.add(lblDirectory);
JLabel lblDate = new JLabel("Date:");
lblDate.setBounds(37, 141, 55, 24);
contentPane.add(lblDate);
txtKeyword = new JTextField();
txtKeyword.setHorizontalAlignment(SwingConstants.CENTER);
txtKeyword.setToolTipText("");
txtKeyword.setColumns(10);
txtKeyword.setBounds(85, 193, 229, 20);
contentPane.add(txtKeyword);
final JDateChooser dateChooser = new JDateChooser();
dateChooser.setDateFormatString("YYYMMd");
dateChooser.setBounds(85, 141, 229, 20);
contentPane.add(dateChooser);
JLabel lblKeyword = new JLabel("Keyword:");
lblKeyword.setBounds(20, 191, 55, 24);
contentPane.add(lblKeyword);
JSeparator separator = new JSeparator();
separator.setBounds(148, 204, -113, 34);
contentPane.add(separator);
JButton btnExport = new JButton("Export");
btnExport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnExport.setBounds(324, 556, 89, 23);
contentPane.add(btnExport);
final JLabel Directory = new JLabel("");
Directory.setBorder(new LineBorder(new Color(0, 0, 0)));
Directory.setBounds(85, 30, 290, 22);
contentPane.add(Directory);
int min = 0;
int max = 23;
int step = 1;
int initValue = 0;
SpinnerModel sm = new SpinnerNumberModel(initValue, min, max, step);
final JSpinner spinner_1 = new JSpinner(new SpinnerNumberModel(0, 0, 23-1, 1));
spinner_1.setBounds(324, 143, 89, 20);
contentPane.add(spinner_1);
JButton btnNewButton = new JButton("...");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename =f.getAbsolutePath();
Directory.setText(filename);
});
btnNewButton.setBounds(377, 30, 36, 23);
contentPane.add(btnNewButton);
final JTextArea jTextArea1 = new JTextArea();
jTextArea1.setRows(15);
jTextArea1.setColumns(15);
jTextArea1.setBounds(42, 249, 351, 294);
jTextArea1.setLineWrap(true);
jTextArea1.setWrapStyleWord(true);
contentPane.add(jTextArea1);
jTextArea1.setEditable(false);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String filename = fileName.getText();
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
filename = br.readLine();
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
if(line.contains(text)){
String newline = "\n";
jTextArea1.append(line + newline);
hasError = false;
}
}
if (hasError) {
JOptionPane.showMessageDialog(null, "Text Not Found");
br.close();
fr.close();
}
}}catch(IOException e){
JOptionPane.showMessageDialog(null, "File Not Found");
} }
});
btnStart.setBounds(324, 215, 89, 23);
contentPane.add(btnStart);
JLabel lblFileName_1 = new JLabel("File Name:");
lblFileName_1.setBounds(20, 79, 75, 24);
contentPane.add(lblFileName_1);
fileName = new JTextField();
fileName.setToolTipText("");
fileName.setHorizontalAlignment(SwingConstants.CENTER);
fileName.setColumns(10);
fileName.setBounds(85, 81, 290, 20);
contentPane.add(fileName);
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{fileName, lblDirectory, lblDate, txtKeyword, btnStart, lblKeyword, separator, btnExport, Directory, dateChooser, dateChooser.getCalendarButton(), spinner_1, btnNewButton, jTextArea1, lblFileName_1}));
}
}
Problem #1
You only ever use the fileName value when trying to open the file...
FileReader fr = new FileReader(filename);
A file is a catenation of the directory and the name, for example...
FileReader fr = new FileReader(new File(Directory.getText(), filename));
Problem #2
You're doing some kind of pre-emptive read on the file which is not required...
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
You should just start reading the file, otherwise you've lost the first line of text
Problem #3
You're not closing the streams in the event of some kind of exception...
try {
FileReader fr = new FileReader(new File(Directory.getText(), filename));
BufferedReader br = new BufferedReader(fr);
//...
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found");
}
If, for some reason, an exception occurs while you are opening or reading the streams, they can never be closed...at least not until the JVM closes
Instead, you should either be using try-with-resources if you're using Java 7+ or a finally block to ensure the streams are closed, for example...
BufferedReader br = null;
try {
String filename = fileName.getText();
br = new BufferedReader(new FileReader(new File(Directory.getText(), filename)));
//...
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found");
} finally {
try {
br.close();
} catch (Exception e) {
}
}
It would also be of more help to you if you at least dumped the stack trace of the actual exception or logged it some how...
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "File Not Found");
} finally {
Problem #4
null layout. 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...
Related
I've been fighting with this and my own poor coding skills apparently.
I'm trying to create a small desktop app that will act essentially as a "Socket Listener" where I can display any information sent to the localhost IP and any port I designate. I have the program working without a UI, but I wanted to make it an actual desktop app (part of my learning journey).
I've searched around and borrowed some ideas from others and almost have it working.
When I launch the app, enter a port number and then try to connect to it using PUTTY I don't see anything displaying in my JTextArea. What should appear is a "Waiting for client" message and then when connected a "Client connected" message, then, of course, any text I type into PUTTY.
If I try connecting using PUTTY, type some text, then exit putty, all of that text and the messages above will appear in the JTextArea (JTextArea is at the bottom of the code).
What on earth am I doing wrong here?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.charset.StandardCharsets;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextArea;
public class Server extends JFrame {
private JPanel contentPane;
private JTextField portInput;
static int sessionNum = 1;
static String IPNum = "127.0.0.1";
public JButton btnListen;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Server frame = new Server();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Server() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 570, 503);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblAddress = new JLabel("IP Address:");
lblAddress.setHorizontalAlignment(SwingConstants.RIGHT);
lblAddress.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblAddress.setBounds(10, 29, 81, 27);
contentPane.add(lblAddress);
JLabel lblDisplayAddress = new JLabel("127.0.0.1");
lblDisplayAddress.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblDisplayAddress.setBounds(101, 29, 81, 27);
contentPane.add(lblDisplayAddress);
JLabel lblPort = new JLabel("Port: ");
lblPort.setHorizontalAlignment(SwingConstants.RIGHT);
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPort.setBounds(210, 33, 90, 19);
contentPane.add(lblPort);
portInput = new JTextField();
portInput.setFont(new Font("Tahoma", Font.PLAIN, 16));
portInput.setBounds(297, 31, 111, 22);
contentPane.add(portInput);
portInput.setColumns(10);
btnListen = new JButton("LISTEN");
btnListen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int portNum = Integer.parseInt(portInput.getText());
try{
ServerSocket ss=new ServerSocket(portNum, sessionNum, InetAddress.getByName(IPNum));
System.out.println("Waiting for client.........");
Socket s=ss.accept();//establishes connection
System.out.println("Client connected.........");
var rawIn = s.getInputStream();
var in = new BufferedReader(new InputStreamReader(rawIn, StandardCharsets.UTF_8)); {
while (true){
String cmd = in.readLine();
if (cmd == null) break; //client is hung up
if (cmd.isEmpty()) continue; //empty line was sent
System.out.println("Client sent: " + cmd);
}
System.out.println("Closing connection");
s.close();
}
}catch(IOException i){System.out.println(i);}
}
});
btnListen.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnListen.setBounds(450, 31, 89, 23);
contentPane.add(btnListen);
JTextArea output = new JTextArea();
output.setBounds(10, 77, 536, 382);
contentPane.add(output);
PrintStream out = new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
output.append(""+(char)(b & 0xFF));
}
});
System.setOut(out);
}
}
UPDATED
Thank you so much for the input. I've incorporated your changes and it is so unbelievably close.
One question. When I run the current code (below), Why doesn't the JTextArea show the "Waiting for client..." message right away? It shows up once PUTTY connects, but not before.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.charset.StandardCharsets;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextArea;
public class Server extends JFrame {
private JPanel contentPane;
private JTextField portInput;
static int sessionNum = 1;
static String IPNum = "127.0.0.1";
public JButton btnListen;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Server frame = new Server();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Server() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 570, 503);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblAddress = new JLabel("IP Address:");
lblAddress.setHorizontalAlignment(SwingConstants.RIGHT);
lblAddress.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblAddress.setBounds(10, 29, 81, 27);
contentPane.add(lblAddress);
JLabel lblDisplayAddress = new JLabel("127.0.0.1");
lblDisplayAddress.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblDisplayAddress.setBounds(101, 29, 81, 27);
contentPane.add(lblDisplayAddress);
JLabel lblPort = new JLabel("Port: ");
lblPort.setHorizontalAlignment(SwingConstants.RIGHT);
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPort.setBounds(210, 33, 90, 19);
contentPane.add(lblPort);
portInput = new JTextField();
portInput.setFont(new Font("Tahoma", Font.PLAIN, 16));
portInput.setBounds(297, 31, 111, 22);
contentPane.add(portInput);
portInput.setColumns(10);
btnListen = new JButton("LISTEN");
btnListen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int portNum = Integer.parseInt(portInput.getText());
try {
ServerSocket ss = new ServerSocket(portNum, sessionNum, InetAddress.getByName(IPNum));
System.out.println("Waiting for client.........");
Socket s = ss.accept();// establishes connection
Thread t = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Client connected.........");
var rawIn = s.getInputStream();
var in = new BufferedReader(new InputStreamReader(rawIn, StandardCharsets.UTF_8));
{
while (true) { // Don't do this on the EDT.
String cmd = in.readLine();
if (cmd == null)
break; // client is hung up
if (cmd.isEmpty())
continue; // empty line was sent
System.out.println("Client sent: " + cmd);
}
System.out.println("Closing connection");
s.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
} catch (IOException i) {
System.out.println(i);
}
}
});
btnListen.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnListen.setBounds(450, 31, 89, 23);
contentPane.add(btnListen);
JTextArea output = new JTextArea();
output.setBounds(10, 77, 536, 382);
contentPane.add(output);
PrintStream out = new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
output.append(""+(char)(b & 0xFF));
}
});
System.setOut(out);
}
}
You have a ServerSocket blocking to read the client connection on the Event Dispatch Thread. Spawn a new thread when you accept a connection. Something like,
btnListen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int portNum = Integer.parseInt(portInput.getText());
try {
ServerSocket ss = new ServerSocket(portNum, sessionNum, InetAddress.getByName(IPNum));
System.out.println("Waiting for client.........");
final Socket s = ss.accept();// establishes connection
Thread t = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Client connected.........");
var rawIn = s.getInputStream();
var in = new BufferedReader(new InputStreamReader(rawIn, StandardCharsets.UTF_8));
{
while (true) { // Don't do this on the EDT.
String cmd = in.readLine();
if (cmd == null)
break; // client is hung up
if (cmd.isEmpty())
continue; // empty line was sent
System.out.println("Client sent: " + cmd);
}
System.out.println("Closing connection");
s.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
} catch (IOException i) {
System.out.println(i);
}
}
});
I am still pretty new to Java and for my class, we have to make a web browser without JEditor. I just need to figure out how to use the socket when a user types in the JTextField and then make it go to that website. Also, I am only supposed to use http:// not https:// if that makes a difference. Anything helps! Thanks!
import javax.swing.*;
import java.awt.*;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.Socket;
import java.io.*;
public class WebPanel extends JPanel{
PrintWriter pw;
JTextField text = new JTextField("http://www.");
public WebPanel(){
//trying to connect to the website
try {
Socket s = new Socket(text, 80); //<<<---where the error is thrown
OutputStream os = s.getOutputStream();
pw = new PrintWriter(os, true);
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
//set layout
setLayout(null);
ButtonHandler bh = new ButtonHandler();
text.addActionListener(bh);
text.setBounds(185, 10, 315, 25);
add(text);
//buttons
JButton goButton = new JButton("GO");
goButton.addActionListener(bh);
add(goButton);
goButton.setBounds(500, 10, 75, 25);
JButton backButton = new JButton("BACK");
backButton.addActionListener(bh);
add(backButton);
backButton.setBounds(2, 10, 75, 25);
JButton forwardButton = new JButton("FORWARD");
forwardButton.addActionListener(bh);
add(forwardButton);
forwardButton.setBounds(80, 10, 100, 25);
}
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//buttons for later
if(e.getActionCommand().equals("GO")){
String input = text.getText();
System.out.println("You searched for: " + input);
pw.flush();
}else if(e.getActionCommand().equals("BACK")){
System.out.println("you pressed the back button");
pw.flush();
} else if(e.getActionCommand().equals("FORWARD")){
System.out.println("You pressed the forward button");
pw.flush();
}
}
}
}
}
For simple cases you don't need to use Sockets. You can use URL class like this:
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.IOUtils;
public class URLReadTest {
public static void main(String[] args) throws Exception {
InputStream is = new URL("http://stackoverflow.com/").openStream();
String html = IOUtils.toString(is);
is.close();
System.out.println(html); // Parse HTML here
}
}
And then you have to parse returned HTML by yourself before you can visualize it of course.
I'm stuck on how to save a file in a text editor i'm creating.Here's my code if you can help me
import java.awt.*;
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.border.*;
public class test1 {
public static void main ( String[] args )
{
JButton b1 = new JButton("Press to read a file");
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Text Reading Box" ) );
// create the middle panel components
final JTextArea display = new JTextArea ( 16, 58 );
display.setEditable ( false);
JScrollPane scroll = new JScrollPane ( display );
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
//Add Text area in to middle panel
middlePanel.add ( scroll );
// My code
JFrame frame = new JFrame ("Text Reader 0.4 Beta");
frame.add ( middlePanel );
frame.add(b1, BorderLayout.NORTH);
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible ( true );
frame.setLayout(new BorderLayout());
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
display.read(br, null);
br.close();
display.requestFocus();
}
catch(Exception error) {
System.err.println("Could'nt read a file");
}
}
});
}
}
I guess you should have another button say 'Save' to save your edited content back to the file. For that you have to handle action on save button and write contents back to the file.
package com.test;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class Random
{
public static void main(String[] args)
{
JButton b1 = new JButton("Press to read a file");
JButton b2 = new JButton("Save");
JPanel middlePanel = new JPanel();
final StringBuilder filename = new StringBuilder("");
middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Text Reading Box"));
// create the middle panel components
final JTextArea display = new JTextArea(16, 58);
display.setEditable(true);
JScrollPane scroll = new JScrollPane(display);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
// Add Text area in to middle panel
middlePanel.add(scroll);
// My code
JFrame frame = new JFrame("Text Reader 0.4 Beta");
frame.add(middlePanel);
frame.add(b1, BorderLayout.NORTH);
frame.add(b2, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
filename.append(f.getAbsolutePath());
try
{
FileReader reader = new FileReader(filename.toString());
BufferedReader br = new BufferedReader(reader);
display.read(br, null);
br.close();
display.requestFocus();
}
catch (Exception error)
{
System.err.println("Could'nt read a file");
}
}
});
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
String textToSet = display.getText();
try
{
PrintWriter writer = new PrintWriter(filename.toString(), "UTF-8");
writer.write(textToSet);
writer.close();
}
catch (FileNotFoundException | UnsupportedEncodingException exc)
{
System.err.println("Could'nt write to the file");
}
}
});
}
}
I am using WindowBuilder in Eclipse to aid in my GUI design. I am trying to make a Jlist popup after the user either enters in a text file with integers in it or, if they enter a file that doesn't exist, they select a file with integers in it from JFileChooser. My problem I am having now is that when the file is selected, nothing happens. The program also doesn't seem to recognize when I do enter in a file that exists, it just defaults to the JFileChooser. Any ideas as to what I'm doing wrong and/or how to make the Jlist appear after an appropriate file is entered?
Here is the code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GUI {
private JFrame frame;
private JTextField txtEnterFileName;
private JTextField textField;
private JFileChooser fileChooser;
private JList list;
private JList list_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtEnterFileName = new JTextField();
txtEnterFileName.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtEnterFileName.setEditable(false);
txtEnterFileName.setText("Enter File Name Below and Press Button");
txtEnterFileName.setBounds(72, 11, 304, 41);
frame.getContentPane().add(txtEnterFileName);
txtEnterFileName.setColumns(10);
textField = new JTextField();
textField.setBounds(113, 63, 221, 25);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int number;
boolean endOfFile = false;
File userF;
userF = new File(textField.getText());
if(!userF.exists()){
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home") + "/desktop"));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(userF.exists()){
try {
Scanner inFile = new Scanner(userF);
if(inFile.hasNextLine()){
inFile.close();
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(inFile.hasNextInt()){
String label[] = {"Smallest Number", "Largest Number", "Count", "Average", "Median", "Quit"};
list = new JList(label);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
});
btnNewButton.setBounds(174, 99, 89, 23);
frame.getContentPane().add(btnNewButton);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
Scanner#nextLine always seems to return true so long as there some text on the first line.
So a file in the format of ...
1 2 3 4 5 6
Will have Scanner#nextLine return true. Instead, you should check for hasNextInt first and then skip over to showing the JFileChooser
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
This is my code and below the code is the problem i have :
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
public class Write extends JFrame {
JTextArea text;
public Write(){
this.setTitle("Lista Carti!");
setSize(400, 200);
setResizable(false);
setLocation(370, 150);
setLayout(null);
JLabel lbltitlu = new JLabel("Titlu");
lbltitlu.setBounds(85, 5, 120, 25);
this.add(lbltitlu);
JTextArea text = new JTextArea();
text.setSize(199,199);
text.setBounds(85, 65, 120, 25);
add(text);
JButton btn = new JButton("Adauga text");
btn.setSize(99,99);
btn.setBounds(125, 125, 120, 25);
add(btn);
ActionListener listenerbtn = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO auto- generated method
String actionbtn = arg0.getActionCommand();
if (actionbtn.equals("Adauga")) {
Adauga();
}
}
};
btn.addActionListener(listenerbtn);
}
public void Adauga(){
String filename = "test.txt";
FileWriter writer = null;
try {
writer = new FileWriter(filename);
text.write(writer);
} catch (IOException exception) {
System.err.println("Save oops");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
}
}
This is my code to write into a file,but it does autowrite when i hover the button and when i reenter the application it won't write again in the same file, any help please? ----- Old request
New request - >
I have edited my code,implemented actionListener but it dosen't input anything to the external file as it should. Can please some one tell me why or where did i done my mistake,i'm a noob programmer by the way? :D
Thank you!
To append to the file , use the constructor File(filename,append).
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
FileWriter fw = new FileWriter(filename,true);