I am trying to make a save button but I don't know how to do it. I will explain a little bit about my program. When someone start the program it shows a JOptionPane and the user need to write a nickname and then when he clicks on OK button it saves his nickname in a text.file. This is a part from my code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.event.*;
public class SummerExamProject extends JFrame {
JButton Exit, About, Question1, Question2, Question3, Question4;
JPanel panel, panel2, panel3, panel4 ;
public SummerExamProject(){
initUI();
}
public void initUI(){
setTitle("Java");
setSize(500, 450);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JFrame frame = new JFrame();
JFrame frame1 = new JFrame("");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(0,3,8,9));
String code = JOptionPane.showInputDialog(frame1, " Enter a nickname ", "Nickname needed", JOptionPane.WARNING_MESSAGE);
If you want to store nickname to file you can use PrintWriter. Lets say you saved the nickname in String variable called nickname:
String nickname = "myAwesomeNickname";
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("c:/nicknames.txt", true)));
out.println(nickname);
out.close();
} catch (IOException e) {
//exception handling
}
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("text.txt"));
out.print(code); // your String here
} catch (IOException e) {
} finally {
if (out != null)
out.close();
}
text.txt can also be a full path like new FileOutputStream("D:/folder/text.txt")
There are a few more options to write to files, though.
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
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.
I have a simple web browser coded in java.
As you may know, the application can't display much.
For instance, google. It won't display the page the right way.
But that's not the problem I want to solve..
The problem is that it won't display pages like AGAR.io (don't misspell the "agar" word.. There's a Jeff the Killer jumpscare if you open this page : agor.io. So be careful :))
Here's the java code of the simple web browser:
package Gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.IDN;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
#SuppressWarnings("serial")
public class Frame extends JFrame implements HyperlinkListener {
private JTextField txtURL= new JTextField("");
JEditorPane ep = new JEditorPane();
private JLabel lblStatus= new JLabel(" ");
public Frame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pnlURL = new JPanel();
pnlURL.setLayout(new BorderLayout());
pnlURL.add(new JLabel("URL: "), BorderLayout.WEST);
pnlURL.add(txtURL, BorderLayout.CENTER);
getContentPane().add(pnlURL, BorderLayout.NORTH);
getContentPane().add( ep, BorderLayout.CENTER);
getContentPane().add(lblStatus, BorderLayout.SOUTH);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
String url = ae.getActionCommand().toLowerCase();
if (url.startsWith("http://"))
url = url.substring(7);
ep.setPage("http://" + IDN.toASCII(url));
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Frame.this, "Browser problem: " + e.getMessage());
}
}
};
txtURL.addActionListener(al);
setSize(300, 300);
setVisible(true);
}
public void hyperlinkUpdate(HyperlinkEvent hle) {
HyperlinkEvent.EventType evtype = hle.getEventType();
if (evtype == HyperlinkEvent.EventType.ENTERED)
lblStatus.setText(hle.getURL().toString());
else if (evtype == HyperlinkEvent.EventType.EXITED)
lblStatus.setText(" ");
}
public static void main(String[] args) {
new Frame();
}
}
But the program can't display pages such as agar.io.
Agar.io is a page with a simple game that seems to not use flashplayer..
Is there a way of making it possible?
I am creating a program which allows the user to enter data and then click a button to view said data. On the first frame I want the user to select an item from a ComboBox and when they click a button it takes the selected item from the ComboBox and enters it as a parameter for another method which will bring up data from a file (this method isn't yet complete).
The code I have so far is as follows:
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SpringLayout;
public class Main implements ActionListener{
static JButton ViewData = new JButton("View Data");
static JButton AddItem = new JButton("Add Item");
String Item = null;
public static void main(String[]args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new Main();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public Main() throws IOException{
//Populating ComboBox
String FilePath = "C:/Users/Harry/AS Computing/CWTreasurers/src/ItemList";
BufferedReader input = new BufferedReader(new FileReader(FilePath));
ArrayList<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}//End While
}//End Try
catch (FileNotFoundException e) {
System.err.println("Error, file " + FilePath + " didn't exist.");
}//End catch
finally {
input.close();
}//end Finally
String[] lineArray = strings.toArray(new String[]{});
JComboBox ChooseItems = new JComboBox(lineArray);
//End populating ComboBox
JFrame frame = new JFrame("CharityWeekTreasury");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//Sets Default properties of the window
Container ContentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
ContentPane.setLayout(layout);
//Defines the container for all objects and the layout
ContentPane.add(ChooseItems);
ContentPane.add(ViewData);
ContentPane.add(AddItem);
ViewData.addActionListener(this);
AddItem.addActionListener(this);
//Adds Objects to window
layout.putConstraint(SpringLayout.WEST,ChooseItems,5,SpringLayout.WEST,ContentPane);
layout.putConstraint(SpringLayout.NORTH,ChooseItems,5,SpringLayout.NORTH,ContentPane);
layout.putConstraint(SpringLayout.WEST,ViewData,5,SpringLayout.EAST,ChooseItems);
layout.putConstraint(SpringLayout.NORTH,ViewData,5,SpringLayout.NORTH,ContentPane);
layout.putConstraint(SpringLayout.WEST,AddItem,5,SpringLayout.EAST,ViewData);
layout.putConstraint(SpringLayout.NORTH,AddItem,5,SpringLayout.NORTH,ContentPane);
layout.putConstraint(SpringLayout.EAST,ContentPane,5,SpringLayout.EAST,AddItem);
layout.putConstraint(SpringLayout.SOUTH,ContentPane,5,SpringLayout.SOUTH,ChooseItems);
//Sets Positioning of objects relative to each other
frame.pack();
frame.setVisible(true);
//Makes frame visible
}//End Window
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource();
if(b.equals(ViewData)){
Item = ChooseItems.getSelectedItem();
ViewData view = new ViewData(Item);
}else if(b.equals(AddItem)){
new AddItem();
}
}
}
ViewData is both a button and the name of another class in the project, the main error is that the line
Item = ChooseItems.getSelectedItem();
Doesn't seem to work, I believe this to be due to the positioning of where ChooseItems is declared, this meaning that there is no ChooseItems to get a selected item of.
Any help is much appreciated. Thanks.
hi friends im new here i write a code in two classes where in one class i declare a jtextarea and a button when we click the button then text will split and it display in the jlabel but here is problem is that the text is written in jtext area and button also working but when jlabel frame open it show nothing here is my code
the first class
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class Try extends JFrame {
JTextArea text;
String string;
public Try(){
super("survey");
Container container=getContentPane();
container.setLayout(new FlowLayout());
text=new JTextArea();
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(350,150));
string=text.getText();
JButton showDialogBtn = new JButton("Add Text");
container.add(text);
container.add( showDialogBtn);
showDialogBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jlabel l=new jlabel();
l.setSize(700,700);
l.setVisible(true);
}
});
}
public static void main(String[] args) {
// TODO code application logic here
Try t=new Try();
t.setSize(400,500);
t.setVisible(true);
}
String getArray()
{
return string ;
}
}
But the second class that is jlabel class is not showing the required result plz help in this regard
import java.awt.Container;
import java.awt.Font;
import javax.swing.*;
class jlabel extends JFrame {
Try t=new Try();
public jlabel(){
JFrame frame=new JFrame("jlabel");
JPanel jp1=new JPanel();
String string=t.getArray();
String[] labelStrings = string.split(" \\s*");
for (String labelString : labelStrings)
{
// create JLabels and add
JLabel label = new JLabel(labelString);
jp1.add(label);
frame.add(jp1);
}
}
}
waiting for reply thanks in advance
Regards,
The first class is decent, but the "jLabel" class had so many bugs. Please see below the one that works.
A summary of the issues in the jlabel class:
Another Try object was instantiated and this instance was used
You were creating a new JFrame even though you were subclassing it already.
No layout manager.
And so on...
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class Label extends JFrame {
public Label(String string) {
super("jlabel");
JPanel jp1 = new JPanel();
jp1.setLayout(new BoxLayout(jp1, BoxLayout.Y_AXIS));
String[] labelStrings = string.split(" \\s*");
for (String labelString : labelStrings) {
// create JLabels and add
JLabel label = new JLabel(labelString);
jp1.add(label);
}
getContentPane().add(jp1);
}
}
In the Try class, initialize it this way:
Label l = new Label(text.getText());
The problem is that you call the getText() outside the actionPerformed() method. This method is run when the button is pressed, so if you want to get text then, you should call the method getText() within actionPerformed().
Your code gets text as soon as it is run and all it can find is nothing! So, that's what is pastes into the JLabel.