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.
Related
I want to be able to call the Introduction.Intro() method into my main file code, but it tells me I am unable to call a non-static method intro from a static context. Since I am still fairly new to coding I'm not entirely sure what the problem is. I've added my codes down below. I've tried countless online methods but sadly none have seemed to work.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Start extends JFrame implements ActionListener
{
private JFrame Main;
private JPanel PanelA, PanelB, PanelC;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public Start ()
{
//Button
Button = new JButton("Start");
Button.addActionListener(new ButtonListener());
//Text
Text = new JLabel("Welcome To The Game"); //ADD NAME OF THE GAME
//Image
Image = new ImageIcon(getClass().getResource("download.jfif")); //ADD THE IMAGE FOR WELCOME
ImageL = new JLabel(Image);
//Top Panel (PanelA) - Image
PanelA = new JPanel();
PanelA.setBorder(BorderFactory.createEmptyBorder(0,200,150,200));
PanelA.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelA.add(ImageL);
//Middle Panel (PanelB) - Text
PanelB = new JPanel();
PanelB.setBorder(BorderFactory.createEmptyBorder(50,200,10,200));
PanelB.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelB.add(Text);
//Bottom Panel (PanelC) - Buttons
PanelC = new JPanel();
PanelC.setBorder(BorderFactory.createEmptyBorder(0,200,20,200));
PanelC.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelC.add(Button);
//Main Frame
Main = new JFrame ();
Main.add(PanelA, BorderLayout.NORTH);
Main.add(PanelB, BorderLayout.CENTER);
Main.add(PanelC, BorderLayout.SOUTH);
Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main.setTitle("GAME TITLE"); //ADD THIS LATER
Main.pack();
Main.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae)
{
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button)
{
Introduction.Intro1(); //THESE LINE RIGHT HERE
return null; //THESE LINE RIGHT HERE
}
}
}
public static void main(String[] args)
{
new Start();
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Introduction
{
private JFrame Main;
private JPanel PanelD;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public void Intro()
{
Image = new ImageIcon(getClass().getResource("guy.jfif"));
ImageL = new JLabel(Image);
PanelD = new JPanel();
PanelD.setBorder(BorderFactory.createEmptyBorder(0,100,10,100));
PanelD.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelD.add(ImageL);
PanelD.setVisible(true);
Main.add(PanelD, BorderLayout.NORTH);
}
}
EDIT: So I made another method in the Introduction class where I added this line of code, it managed to fix the error, however, the panel isn't being saved and my JFrame is outputting blank.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}
If you are looking to initialize the Introduction class in main method of Start class, You can add belo code in main method after Start()
Introduction M = new Introduction();
You main method becomes :
public static void main(String[] args)
{
new Start();
Introduction M = new Introduction();
m.Intro
}
Looking at this set of code, It looks like there is incompatible issue, as you have declare JFrame as return type, while you are returning instance of Introduction.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}
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
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Guiii extends JFrame{
private JButton menu;
private JButton custom;
public Guiii(){
super ("The Title");
setLayout(new FlowLayout());
menu = new JButton("menu Button");
add (menu);
Icon b = new ImageIcon (getClass().getResource("button.png"));
Icon x = new ImageIcon (getClass().getResource("greenbutton.png"));
custom = new JButton("Custom",b);
custom.setRolloverIcon(x);
add (custom);
HandlerClass handler = new HandlerClass();
menu.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("~s", event.getActionCommand()));
}
}
}
This is my code I am having some trouble and its not working, I have made a main for it but errors are showing can anyone help me and explain how the code will work khg
These are the errors
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at Guiii.<init>(Guiii.java:22)
at main.main(main.java:7)
This is the rest of the code but it had to be in another file:
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Guiii o = new Guiii();
o.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
o.setSize(300,200);
o.setVisible(true);
}
}
The constructor of the icon throws a NPE because getResource returns null.
Place the images in the same folder as the class Guiii.
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.
How do you make a JTextArea in the JFrame that accepts multiple input from JOptionPane? Is that even possible? Thanks to whoever helps!
Create a new class and extend JFrame
add a JTextArea to it. Make it a member variable
add a button to the frame. In the action method call open the input dialog
when the dialog returns, append the text to the JTextArea using its append method (don't forget to check for empty/null string)
Here is a sample program:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class InputTest extends JFrame {
private final JTextArea textarea;
private final JButton button;
public InputTest(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textarea = new JTextArea(5,30);
button = new JButton("new input");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String input = JOptionPane.showInputDialog(InputTest.this, "Please enter some text");
if((input != null) && !input.isEmpty()) {
textarea.append(input);
textarea.append(System.getProperty("line.separator"));
}
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(textarea, BorderLayout.NORTH);
p.add(button, BorderLayout.SOUTH);
this.getContentPane().add(p);
}
public static void main(String[] args) {
InputTest it = new InputTest("Input Test");
it.setSize(200, 200);
it.setVisible(true);
}
}