I am kinda new to Java. I am creating a simple program to read a text file and put its contents into text area in a java swing frame. My file looks like this
Hello World!
What a beautiful World!
For the java frame I created a button and an action for the button to import the text from the text file into the text area when clicked. The problem is that the program only reads the second line of the text file "What a beautiful world!" I know it is probably a tiny stupid mistake, but I couldn't figure it out. here is my code for the class
import java.io.*;
import java.util.*;
public class JavaGui {
Scanner scnr;
static String fileText;
public void openfile(){
try{
scnr = new Scanner(new File("C:\\Users\\13195\\New JavaGui\\abc.txt"));
}
catch (FileNotFoundException e){
System.out.println("File Not Found. Try Again!");
}
}
public void readfile(){
while (scnr.hasNextLine()){
fileText = scnr.nextLine();
System.out.println(fileText);
}
scnr.close();
}
}
And here is the class with main method:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuiFrame implements ActionListener {
private JTextArea jtxt = new JTextArea(30, 30);
private JFrame fr = new JFrame("Framework");
private JButton btn = new JButton("View Text");
static String t;
public GuiFrame(){
fr.add(jtxt);
btn.addActionListener(this);
fr.add(btn);
//Frame
fr.setLayout(new FlowLayout());
fr.setSize(50,50);
fr.setVisible(true);
}
public static void main(String[] args) {
new GuiFrame();
JavaGui fr = new JavaGui();
fr.openfile();
fr.readfile();
t = JavaGui.fileText;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn){
jtxt.setText(t);
}
}
}
Related
Ok so I will try to make this as understandable as possible.
I have created a simple GUI with an "open" button and a textArea (along with other stuff but that's not important right now). Basically I am creating a method that when I click the Open button it displays the contents of the file in the textArea.
I believe 99% of the method I have written is correct but I keep getting a NullPointerException and I don't quite understand why. Hopefully my code will clear up any confusion on what I am asking, I will comment on the line of code where I get the exception. Here is my code:
Application class (Basic setup of my GUI):
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class Application extends JFrame {
public OutputPanel outPanel = new OutputPanel();
public BarcodePanel barPanel = new BarcodePanel();
public ButtonPanel btnPanel = new ButtonPanel();
public ReferencePanel refPanel = new ReferencePanel();
public Application() {
super("Book Processor");
this.setLayout(new BorderLayout());
btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
outPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
refPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
add(btnPanel, BorderLayout.NORTH);
add(outPanel, BorderLayout.WEST);
add(refPanel,BorderLayout.SOUTH);
}//end constructor
public static void main(String[] args) {
Application frame = new Application();
frame.setSize(1000,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}//end main
}//end class
The next set of code is my ButtonPanel class(this is where I am having an issue) So I have an openFile method, that when I click the button it should display the contents of the file in the textArea. Again I receive a NullPointerException and I do not understand why. Here is the code for this class:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ButtonPanel extends JPanel{
JButton btnOpen = new JButton("Open");
OutputPanel outPanel = new OutputPanel();
Scanner input;
public ButtonPanel() {
ButtonHandler handler = new ButtonHandler();
add(btnOpen);
btnOpen.addActionListener(handler);
}//end constructor
/**
* Method for displaying the file onto the textArea.
*
*/
private void openFile() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = chooser.showOpenDialog(this);
String fileName;
fileName = chooser.getSelectedFile().getAbsolutePath();
try {
Scanner input = new Scanner(Paths.get(fileName));
StringBuilder sb = new StringBuilder();
while(input.hasNextLine()) {
sb.append(input.nextLine()+ "\n");
}
outPanel.txtOutput.setText(sb.toString());//my issue is with this line right here
} catch (IOException e) {
e.printStackTrace();
}
finally {
input.close();
}
}//end readFile
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()== btnOpen) {
openFile();
}
}//end actionPerformed
}//end actionlistener
}//end class
Here is my last class, OutputPanel, this class contains the JTextArea:
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class OutputPanel extends JPanel{
public JTextArea txtOutput = new JTextArea(20,50);
public OutputPanel() {
add(txtOutput);
}//end constructor
}//end class
How do I get the textArea to display the contents of the file? More importantly, why am I getting this exception and what can I do to fix it? Hopefully this makes as much sense as possible, and I really appreciate any and all input from you guys.
Your NullPointerException is actually been caused by
} finally {
input.close();
}
Because input is null (well, obviously). This is because you're shadowing the variable in the try-catch block
try {
Scanner input = new Scanner(Paths.get(fileName));
//...
} finally {
// This is null because the instance field has not been initialised
input.close();
}
A better solution would be to make use of the try-with-resources statement
try (Scanner input = new Scanner(Paths.get(fileName))) {
StringBuilder sb = new StringBuilder();
while (input.hasNextLine()) {
sb.append(input.nextLine() + "\n");
}
outPanel.txtOutput.setText(sb.toString());//my issue is with this line right here
} catch (IOException e) {
e.printStackTrace();
}
An even better solution would be to make use of JTextArea's ability to read the contents of a Reader, for example...
try (FileReader reader = new FileReader(chooser.getSelectedFile())) {
outPanel.txtOutput.read(reader, fileName);
} catch (IOException e) {
e.printStackTrace();
}
Now, before you ask why there's no content in your text area, the reason is because you create a new instance of OutputPanel in your ButtonPanel class, this has no relationship to the instance you created in your Application and added to the screen.
You will need to pass an instance of the OutputPanel to the ButtonPanel (via the constructor) so the references match up.
Personally, a better solution would be define an interface which had a read method which took a File. OutputPanel would implement this interface and ButtonPanel would require a reference to an instance of this interface. This decouples the code and prevents ButtonPanel from making unnecessary changes to the OutputPanel - because it's really not it's responsibility to do so - it's the OutputPanels responsibility to load the file and display it
I want to create a simple stand-alone application that will take some input from user (some numbers and mathematical functions f(x,y...)) and write them to a file. Then with the help of this file I will run a command.
Basic ingredients that I need:
-- JTextArea for users input.
-- ButtonHandler/ActionListener and writing of the input to a (txt) file
-- ButtonHandler/ActionLister to execute a command
What is the best way to do it?
A current running code that I have (basically a toy) - which does not write anything, just executes - is:
import java.applet.*;
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dialog;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.util.*;
import java.io.BufferedWriter;
public class Runcommand3
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
//JApplet applet = new JApplet();
//applet.init();
final JFrame frame = new JFrame("Change Backlight");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JButton button = new JButton("Click me to Run");
button.setBounds(55,100,160,30);
panel.add(button);
frame.setSize(260,180);
frame.setVisible(true);
//This is an Action Listener which reacts to clicking on the button
button.addActionListener(new ButtonHandler());
}
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
double value = Double.parseDouble(
JOptionPane.showInputDialog("please enter backlight value"));
//File theFile = new File("thisfile.txt");
//theFile.write(value);
String command = "xbacklight -set " + value;
try{Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);}
catch(IOException t){t.printStackTrace();}
}
}
In the above example how can I write 'value' to a file? Then, how can I add more input (more textfields)? Can I do it in the same class or I need more?
My confusion comes (mainly but not only) from the fact that inside the ButtonHandler class I can NOT define any other objects (ie, open and write files etc).
This is the way I would write to a file. I will let you convert this code into your GUI for practice. See more on BufferedWriter and FileWriter
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Files {
public static void main(String args[]){
System.out.print("Enter Text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("text.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.newLine();
writer.close();
System.err.println("Your input of " + text.length() + " characters was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
}
For your second question, you may like to consider having a JTextField on your JFrame for the user to enter lines into instead of a JOptionPane. It's just a simple text box, and you can add the box's contents to the file every time the button is pressed:
public static void main(String[] args) {
JTextField myTextField = new JTextField();
// Your code, set size and position of textfield
panel.add(myTextField);
}
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String text = myTextField.getText();
myTextField.setText("");
new BufferedWriter(new FileWriter("text.txt")).write(text).newLine().close();
// the rest of your code
}
}
I am trying to create a simple web browser but when i run it and hover over an URL the URL gets run even though i gave event.getEventType()==HyperlinkEvent.EventType.ACTIVATED
why does it behave like event.getEventType()==HyperlinkEvent.EventType.ENTERED
Here is the full Code
package gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
public class WebBrowser extends JFrame{
private JTextField addressbar;
private JEditorPane display;
public WebBrowser(){
super("Sagar Browser");
addressbar = new JTextField("Enter a URL");
addressbar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
load(event.getActionCommand());
}
}
);
add(addressbar,BorderLayout.NORTH);
display = new JEditorPane();
display.setEditable(false);
display.addHyperlinkListener(
new HyperlinkListener(){
public void hyperlinkUpdate(HyperlinkEvent event){
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED);
load(event.getURL().toString());
}
}
);
add(new JScrollPane(display),BorderLayout.CENTER);
}
private void load(String usertext){
try{
display.setPage(usertext);
addressbar.setText(usertext);
}catch(Exception e){
System.out.println("Enter Full URL");
}
}
public static void main(String[] args){
WebBrowser w = new WebBrowser();
w.setSize(500,500);
w.setVisible(true);
}
}
Your listener ignores the relevant predicate. You probably meant this:
new HyperlinkListener(){
public void hyperlinkUpdate(HyperlinkEvent event){
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED) {
load(event.getURL().toString());
}
}
}
Related examples are examined here and here.
a basic problem that i can't figure out, tried a lot of things and can't get it to work, i need to be able to get the value/text of the variable
String input;
so that i can use it again in a different class in order to do an if statement based upon the result
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class pInterface extends JFrame {
String input;
private JTextField item1;
public pInterface() {
super("PAnnalyser");
setLayout(new FlowLayout());
item1 = new JTextField("enter text here", 10);
add(item1);
myhandler handler = new myhandler();
item1.addActionListener(handler);
System.out.println();
}
public class myhandler implements ActionListener {
// class that is going to handle the events
public void actionPerformed(ActionEvent event) {
// set the variable equal to empty
if (event.getSource() == item1)// find value in box number 1
input = String.format("%s", event.getActionCommand());
}
public String userValue(String input) {
return input;
}
}
}
You could display the window as a modal JDialog, not a JFrame and place the obtained String into a private field that can be accessed via a getter method. Then the calling code can easily obtain the String and use it. Note that there's no need for a separate String field, which you've called "input", since we can easily and simply extract a String directly from the JTextField (in our "getter" method).
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TestPInterface {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JFrame frame = new JFrame("TestPInterface");
// JDialog to hold our JPanel
final JDialog pInterestDialog = new JDialog(frame, "PInterest",
ModalityType.APPLICATION_MODAL);
final MyPInterface myPInterface = new MyPInterface();
// add JPanel to dialog
pInterestDialog.add(myPInterface);
pInterestDialog.pack();
pInterestDialog.setLocationByPlatform(true);
final JTextField textField = new JTextField(10);
textField.setEditable(false);
textField.setFocusable(false);
JPanel mainPanel = new JPanel();
mainPanel.add(textField);
mainPanel.add(new JButton(new AbstractAction("Get Input") {
#Override
public void actionPerformed(ActionEvent e) {
// show dialog
pInterestDialog.setVisible(true);
// dialog has returned, and so now extract Text
textField.setText(myPInterface.getText());
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// by making the class a JPanel, you can put it anywhere you want
// in a JFrame, a JDialog, a JOptionPane, another JPanel
#SuppressWarnings("serial")
class MyPInterface extends JPanel {
// no need for a String field since we can
// get our Strings directly from the JTextField
private JTextField textField = new JTextField(10);
public MyPInterface() {
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
add(new JLabel("Enter Text Here:"));
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = (Window) SwingUtilities.getWindowAncestor(MyPInterface.this);
win.dispose();
}
});
}
public String getText() {
return textField.getText();
}
}
A Good way of doing this is use Callback mechanism.
I have already posted an answer in the same context.
Please find it here JFrame in separate class, what about the ActionListener?.
Your method is a bit confusing:
public String userValue(String input) {
return input;
}
I guess you want to do something like this:
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
Also your JFrame is not visible yet. Set the visibility like this setVisible(true)
First post for me. I'm a student in my first year of a comp science degree.
I was just building a basic GUI for an assignment and for some reason, which I cannot see for the life of me, one of the JFrames I have created, an instance of the Register Class displays completely blank when it is called from the Register buttons action listener in the Login Class...
I also have an individual main Class which contains the Main method and calls the Login Class. The Login Class JFrame works fine and as mentioned, the issues only occur with the Registration Class when it is called within the Login Class' Register button action listener. All other JFrames in the program work fine too.
I have attempted to call the Register Class direct from the main and it has the same issues, although I have attempted to reduce it to its most basic form and it still does not display anything aside from a blank uncolored JFrame.
Here is the code (Unfinished but working as is). I apologise for my sloppyness but I am a complete beginner.
Can anyone see what is wrong with it?
Thanks in advance!
package guitest;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Register extends JFrame{
JButton regSubmit = new JButton("Submit");
JTextField email = new JTextField();
JTextField name = new JTextField();
JTextField Address1 = new JTextField();
JTextField Address2 = new JTextField();
JPasswordField password1 = new JPasswordField();
JPasswordField password2 = new JPasswordField();
String nameTxt = email.getText();
String passTxt = password1.getText();
String info = "";
FlowLayout layout1 = new FlowLayout();
public void Reg(){
this.setTitle("La Volpe Registration");
this.setLayout(layout1);
this.add(Address1);
this.add(Address2);
this.add(email);
this.add(password1);
this.add(password2);
this.add(name);
this.add(regSubmit);
this.getContentPane().setBackground(Color.green);
this.setSize(370, 160);
regSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
regSubmitActionPerformed(evt);
}
private void regSubmitActionPerformed(java.awt.event.ActionEvent evt) {
String name = email.getText();
String pass = password1.getText();
String info = "";
System.out.println("registering...");
boolean eof;
try{
// Create file
FileWriter file = new FileWriter("\\regdata.txt");
BufferedWriter out = new BufferedWriter(file);
out.write("\n"+nameTxt+", "+passTxt);
}
catch (Exception e){
}
}
});
this.setVisible(true);
}
}
And the class that links to it...
package guitest;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/**
* #author david
*/
public class Login {
JFrame loginFrame = new JFrame();
Register reg3 = new Register();
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear");
JButton register = new JButton ("Register with Us");
JPasswordField pass = new JPasswordField(20);
JTextField email = new JTextField(20);
JLabel em = new JLabel("Email Address: ");
JLabel pw = new JLabel("Password: ");
String pathname;
String line;
String [] records = new String [1000];
int count = 0;
FlowLayout layout1 = new FlowLayout();
public Login(){
//Adds Email label and text field
loginFrame.add(em);
loginFrame.add(email);
//Adds password label and field
loginFrame.add(pw);
loginFrame.add(pass);
//Adds buttons
loginFrame.add(submit);
loginFrame.add(clear);
loginFrame.add(register);
loginFrame.getContentPane().setBackground(Color.green);
loginFrame.setLayout(layout1);
loginFrame.setSize(370, 160);
loginFrame.setTitle("La Volpe - Login");
submit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitActionPerformed(evt);
}
private void submitActionPerformed(java.awt.event.ActionEvent evt){
String emailadd = email.getText();
String password = pass.getText();
pathname = "\\regdata.txt";
boolean eof;
try{
FileReader file = new FileReader(pathname);
BufferedReader buff = new BufferedReader(file);
eof = false; // set the eof boolean to false
while (!eof){
line = buff.readLine();
if (line == null){ // test to see if the end of file has been reached
eof = true; // if the end of file has been found set the eof Boolean to true
}
else{
// end of file not reached so move the contents of the line to the records
//array
records[count] = line;
count ++;
System.out.println(line); // print out the new line input for error checking
}
}
buff.close();
}
catch (IOException e){
System.out.println("Error -- "+ e.toString());
}
boolean notTrue = false;
for (int i = 0; i < count; i++) {
if ((!notTrue)&&((emailadd + "," + password).equals(records[i]))) {
FoodSelectionMain loggedIn = new FoodSelectionMain();
loggedIn.setVisible(true);
}
}
if (!notTrue){
JOptionPane.showInputDialog("Please check your login "
+ "and try again. If you are a new user, please "
+ "register by pressing the 'REGISTER' button");
}
}
});
// TODO add your handling code here:
clear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearActionPerformed(evt);
}
public void clearActionPerformed(java.awt.event.ActionEvent evt){
email.setText(null);
pass.setText(null);
}
});
register.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
registerActionPerformed(evt);
}
public void registerActionPerformed(java.awt.event.ActionEvent evt){
reg3.setVisible(true);
System.out.println("Register pressed");
}
});
loginFrame.setVisible(true);
}
}
Try this,
in Register class, correct the constructor name to Register() from Reg().
Keep these few Guidelines in your mind before constructing a gui app
Create an object of the subclass of the container .
Consider all the components which goes in the container as instance variables.
Set these instance variable and event handling outside the constructor in methods, (ie setComponent(), setHandler().etc) but do these method invocations from constructor.
Now in main use this...
.
EventQueue.invokeLater(new Runnable() {
public void run() {
Myframe f = new Myframe();
f.setVisible(true);
}
}