Populating JList with List<String> nullpointerexception - java

I am trying to populate the JList using a file I create, before I write the code for adding things to the file that is being read, I would like to make sure it will be read, and display properly on the screen. I am getting a nullpointerexception, and my GUI is launching, but only the "enter" button is showing. I appreciate any help anyone can offer me with this issue.
package movieinfo;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.apache.commons.io.FileUtils;
import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;
public class Swinggui {
private static JButton enter;
private static JTextField movietext;
private static JTextArea movieinfo;
private static JList listofmovies;//converts moviestowatch into gui element.
private static File textfilemovie; //file which movies marked for watching are saved
private static java.util.List<String> moviestowatch; //arraylist which is populated by textfilemovie than printed to GUI element.
public static void main(String[] args) throws IOException
{
Gui();
Json();
YourMovies();
}
public static void Gui()
{
JFrame maingui = new JFrame("Gui");
maingui.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
enter = new JButton("Enter");
c.gridx = 2;
c.gridy = 1;
maingui.add(enter, c);
movieinfo = new JTextArea(5,20);
movieinfo.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.red));
movietext = new JTextField(18);
c.gridx = 1;
c.gridy = 1;
maingui.add(movietext, c);
final JScrollPane scrolll = new JScrollPane(movieinfo);
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 2;
maingui.add(scrolll, c);
final JLabel titlee = new JLabel("Enter movie name below!");
c.gridx = 1;
c.gridy = 0;
maingui.add(titlee, c);
maingui.setResizable(false);
maingui.setVisible(true);
listofmovies = new JList(moviestowatch.toArray());
c.gridx = 2;
c.gridy = 3;
maingui.add(new JScrollPane(listofmovies), c);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
scrolll.getPreferredSize();
//pangui.setPreferredSize(new Dimension(300, 150));
//pangui.add(scrolll, BorderLayout.CENTER);
//movieinfo.add(scrolll);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
}
public static void Json()
{
enter.addActionListener(new ActionListener(){
#SuppressWarnings("rawtypes")
public void actionPerformed(ActionEvent e)
{
System.out.println(apicall.getMovieInfo(movietext.getText()));
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonData=parser.parseJson(apicall.getMovieInfo(movietext.getText()));
String Title = (String)jsonData.get("Title");
String Year = (String)jsonData.get("Year");
String Plot = (String)jsonData.get("Plot");
movieinfo.setText("Title: "+Title+"\nYear: "+ Year +"\nPlot: "+Plot);
}
});
}
public static void YourMovies() throws IOException
{
textfilemovie = new File("yourmovies.txt");
moviestowatch = FileUtils.readLines(textfilemovie);
}
}

You're calling moviestowatch.toArray() before you instantiate moviestowatch. You need to call YourMovies() before you call Gui().

I see that in the method Gui() you are using an un-initialized list. The method where the list is getting initialized is called afterwards ( method YourMovies())
listofmovies = new JList(moviestowatch.toArray());
^^^^^^^^^^^^^
this is null
On a side note:
As per Java naming convention, methods start with small case and follow camel case, example - yourMovies() gui()

moviestowatch is not assigned when Gui is called - reverse the order of these methods
YourMovies();
Gui();
and follow Java naming conventions for method names with initial lowercase latter, e.g. loadMovies

Related

Word count for a scrollable JTextArea (scrollPane) word count

I have been trying to make a program where data inputted into a JTextArea, would then be counted and then displayed on a JLabel the number of words, after a button is clicked.
However the code I have tried to use, just shows the value of 1 everytime.
Any idea why?
`
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SPanel extends JPanel {
public SPanel(){
final TextAPanel textPanel = new TextAPanel();
final JLabel outputLabel = new JLabel();
JButton click = new JButton ("Click");
click.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String word = textPanel.inputBox.getText();
System.out.println("Test: " +word);
}
});
}
}
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextAPanel extends JPanel {
public JTextArea inputBox = new JTextArea(20,10);
public JScrollPane scrollPane = new JScrollPane(inputBox);
TextAreaPanel(){
JLabel title = new JLabel("Please type in the box below:");
inputBox.setLineWrap(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
add(title,gc);
gc.gridx = 0;
gc.gridy = 1;
add(scrollPane, gc);
}
}
Just to put it in context, my JTextArea is on a seperate panel / class to the panel containing the button and JLabel.
Every time I run the program and click the button, after inputting some words the value is always one even if the text box is empty.
Well, if you create a new TextAPanel and assign it to the textPanel variable - then when you try to get input you get nothing, because the newly created panel doesn't contain anything. If textPanel is a field in your class, you should just remove the textPanel = new TextAPanel(); line and it should work fine. If you get a NullPointerException, it means you forgot to initialize it earlier in the code, you should probably do it in the constructor.
EDIT: OK, I made it work, the code is below. I have no idea how your program compiled, because in your TextAPanel class you had TextAreaPanel() method/constructor, which caused compilation error in my Eclipse. Anyway, I got this working, you'll need to complete it, but this should get you started:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public class SPanel extends JPanel {
public SPanel() {
final TextAPanel textPanel = new TextAPanel();
this.add(textPanel);
final JLabel outputLabel = new JLabel();
JButton click = new JButton("Click");
click.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
String word = textPanel.inputBox.getText();
System.out.println("Test: " + word);
System.out.println(word.split("\\s+").length);
}
});
this.add(click);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new SPanel());
f.setVisible(true);
}
}
#SuppressWarnings("serial")
class TextAPanel extends JPanel {
public JTextArea inputBox = new JTextArea(20, 10);
public JScrollPane scrollPane = new JScrollPane(inputBox);
TextAPanel() {
JLabel title = new JLabel("Please type in the box below:");
inputBox.setLineWrap(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
add(title, gc);
gc.gridx = 0;
gc.gridy = 1;
add(scrollPane, gc);
}
}

Getting String info from another java class rather than the same one

so I have 2 classes, 1 for a very small interface and 1 for some calculations. basically I want to have a string displayed in a box. That's done but now I need the string to be obtained from my other class. Here is where my question lies, How do I do that if my code looks like this:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class SwingJPanelDemo extends JFrame { //where I want the string to be send to from the other class
String letter = "apple"; //teststring
private JLabel LetterTest = new JLabel(letter); //where I use the string
private JButton NextButton = new JButton("Next");
private JButton NoButton = new JButton("No");
public SwingJPanelDemo() {
super("Is This Your Letter?");
JPanel newPanel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);
constraints.gridx = 0;
constraints.gridy = 0;
newPanel.add(LetterTest, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
newPanel.add(NextButton, constraints);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
newPanel.add(NoButton, constraints);
newPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Is This Your Letter?"));
add(newPanel);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
// set look and feel to the system look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SwingJPanelDemo().setVisible(true);
}
});
}
}
How would I go about Getting s string to this?
If your other class looks like this:
public class Other {
public static String text = "some text";
}
you can just use Other.text to get the String.

Connection of JButton and JTextField?

I just want to know how to do a new frame via typing a specific character then if you click the Jbutton, all the information (of that character) will pop up - for example a picture or a text.
For example, if I type the word "Dog", a picture of a dog and the information about it will pop out on a new window. Is this possible without database?
I want to do it without a database if it's possible.
Here's my code:
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
//Bago
import java.awt.GridBagLayout; // Para mahatihati yung panel
import java.awt.GridBagConstraints; // para customize yung pagkahati ng panel
class ProgDraftMain {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ProgDraft gui = new ProgDraft();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setResizable(true);
gui.pack();
gui.setVisible(true);
}
});
}
}
class ProgDraft extends JFrame {
private ImageIcon image1;
private JLabel label1;
private JTextField textField1;
private JButton butones;
private JTextField textField;
ProgDraft() {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel title = new JLabel("Dog Check", JLabel.CENTER);
Font font = new Font("Gigi", Font.BOLD, 50);
title.setFont(font);
mainPanel.add(title, BorderLayout.NORTH);
String text = "Dogs" + "<br>"
+ "Cute dogs are everywhere" + "<br>" + "<br>"
+ "Take care and stay safe!" + "<br>"
+ "I love my dogs" + "<br>" + "<br>" + "<br>"
+ "Please help!";
JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
dog.setHorizontalAlignment(JLabel.CENTER);
mainPanel.add(dog);
ImageIcon pics = new ImageIcon(getClass().getResource("Capture.png"));
JLabel logo = new JLabel(pics);
logo.setHorizontalAlignment(JLabel.CENTER);
logo.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
logo.setToolTipText("PIcture.");
JPanel iconFieldPanel = new JPanel();
iconFieldPanel.setLayout( new GridBagLayout() );
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.CENTER; // Saan ikakabit yung component
gc.weightx = 0.5; // (left and right)Space between sa edge nung panel at component
gc.weighty = 0.5; // (top and bottom)^
gc.gridx = 0; //saang cell x-axis
gc.gridy = 0; //^ y axis naman
iconFieldPanel.add(logo, gc);
gc.gridy = 1;
JLabel titleBut = new JLabel("Enter Dog Code:");
iconFieldPanel.add(titleBut, gc);
gc.gridy = 2;
textField = new JTextField(10);
iconFieldPanel.add(textField, gc );
JButton buton1 = new JButton("OK");
gc.gridy = 3;
iconFieldPanel.add( buton1, gc);
JPanel iconFieldWrapper = new JPanel();
iconFieldWrapper.add(iconFieldPanel);
mainPanel.add(iconFieldWrapper, BorderLayout.SOUTH); // add icon and field to bottom
getContentPane().add(mainPanel);
}
}
The following code may help you to solve your problem,
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class PopupExample implements ActionListener
{
JFrame frame;
JTextField t1;
JButton btn;
public PopupExample()
{
frame=new JFrame();
frame.setLayout(null);
frame.setSize(700,700);
frame. setLocation(300,10);
t1=new JTextField();
t1.setBounds(82,10,100,20);
frame.add(t1);
btn=new JButton("SUBMIT");
btn.setBounds(200,10,100,20);
btn.addActionListener(this);
frame.add(btn);
frame.setVisible(true);
}
public static void main(String ar[])
{
PopupExample obj=new PopupExample();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn)
{
String input=t1.getText();
if(input.equals("dog"))
{
JOptionPane.showMessageDialog(null,"my dog");
//you can popup new frame here about dog
//create the object of new class (which contain dog details)here.
//you can use show()
}
}
}
}
It is possible to write a program without database but you have to think about a way to store the data. For database concern, I guess you mean how to store the code and picture of these dogs.
Yes, we can do that without database, but you need to write different logic i.e. hard coding like based on the condition
Example: After getting the data from the text field
String a=xx.getText().toString().trim();if(a.equals("dog"))
{
//call the iframe which u need
}
Note: As you need to store all the images in your working directory, or store all the frames with different names which includes images and information regarding the image and call them according to your requirement.

Learning the MVC design pattern

I'm trying to get my head around the MVC design pattern using Swing in Java it's pretty confusing at the moment because I don't fully understand it. I have tried to make what I understand of it in eclipse but I have a error on line 68, I'm not sure why everytime I push a button I get a lot of errors being spat out and not the incrementing value of counter.
Thanks
public class Model
{
int counter = 0;
int counter()
{
this.counter++;
return this.counter;
}
}
#################################################################################
public class Controller
{
Model mRef;
View vRef;
public Controller(Model m, View v)
{
this.mRef = m;
this.vRef = v;
}
int inc()
{
mRef = new Model();
return mRef.counter();
}
}
######################################################################################
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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.JPanel;
#SuppressWarnings("serial")
public class View extends JFrame
{
JPanel jp;
JButton jb1;
JLabel jl1;
GridBagConstraints c;
Controller con;
public View()
{
c = new GridBagConstraints();
jp = new JPanel();
jb1 = new JButton("First");
jl1 = new JLabel("Label");
jp.setLayout(new GridBagLayout());
add(jp);
c.gridx = 0;
c.gridy = 0;
jp.add(jb1, c);
jb1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println(con.inc());
}
});
c.gridx = 0;
c.gridy = 2;
jp.add(jl1, c);
setVisible(true);
pack();
}
}
I recommend to consider using JavaFX, is simpler and prettier than Swing. It provides you with what is called a Scene Builder, where you can easily drag and drop controls to your user interface.
In the following link you can install the Scene Builder under Additional Resources.
http://www.oracle.com/technetwork/java/javase/downloads/index.html

How do I avoid creating Swing elements within a main method?

Currently my code will not run because I have no main, but when I make a main it must be static, and I am under the impression I shouldn't be making all of my variables for the Swing elements Static, as per the advice of many.
I'm not sure how to invoke the methods without using main as the constructor, currently my gui does not appear.
Thanks.
package movieinfo;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.commons.io.FileUtils;
public class Swinggui {
JButton enter;
public JTextField movietext;
JList listofmovies;// converts moviestowatch into gui
// element.
File textfilemovie; // file which movies marked for watching
// are saved
java.util.List<String> moviestowatch; // arraylist which is
// populated by
// textfilemovie
// than printed to
// GUI element
ListSelectionListener setSearch;
JButton add;
String info;
public Swinggui() throws IOException {
yourMovies();
gui();
jsonAndButtons();
}
public void gui() {
JFrame maingui = new JFrame("Gui");
maingui.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
enter = new JButton("Get Info");
c.gridx = 2;
c.gridy = 1;
maingui.add(enter, c);
add = new JButton("add");
c.gridx = 5;
c.gridy = 6;
maingui.add(add, c);
JTextArea movieinfo = new JTextArea(info, 5, 20);
movieinfo.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2,
Color.red));
movietext = new JTextField(18);
c.gridx = 1;
c.gridy = 1;
maingui.add(movietext, c);
final JScrollPane scrolll = new JScrollPane(movieinfo);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 2;
maingui.add(scrolll, c);
final JLabel titlee = new JLabel("Enter movie name below!");
c.gridx = 1;
c.gridy = 0;
maingui.add(titlee, c);
c.gridx = 1;
c.gridy = 3;
maingui.add(titlee, c);
final JLabel watchlist = new JLabel("Watchlist");
c.gridx = 5;
c.gridy = 1;
maingui.add(watchlist, c);
maingui.setResizable(false);
maingui.setVisible(true);
listofmovies = new JList(moviestowatch.toArray());
c.gridx = 4;
c.gridy = 3;
maingui.add(new JScrollPane(listofmovies), c);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
scrolll.getPreferredSize();
listofmovies.addListSelectionListener(setSearch);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
}
public void jsonAndButtons() {
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(apicall.getMovieInfo(movietext.getText()
.replaceAll(" ", "%20")));
info = apicall.getMovieInfo(movietext.getText().replaceAll(" ",
"%20"));
}
});
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
FileUtils.writeStringToFile(new File(
org.apache.commons.io.FileUtils.getUserDirectory()
+ "/yourmovies.txt"),
"\n" + movietext.getText(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
moviestowatch = FileUtils.readLines(textfilemovie);
listofmovies = new JList(moviestowatch.toArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void yourMovies() throws IOException {
textfilemovie = new File(
org.apache.commons.io.FileUtils.getUserDirectory()
+ "/yourmovies.txt");
textfilemovie.createNewFile();
moviestowatch = FileUtils.readLines(textfilemovie);
setSearch = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
info = apicall.getMovieInfo(((String) listofmovies
.getSelectedValue()).replaceAll(" ", "%20"));
}
};
}
}
Firstly, don't keep everything in one class. Create some other class and then create object of that type, and invoke its methods, it would look like this in your main() method:
MyClass myClass = new MyClass();
myClass.doStuff();
inside your main put:
new Swinggui();
This will pull you out of the static context and bring you into the non-static Swinggui constructor
Make your class Swinggui extend JFrame.
Then create a main method and create object of Swinggui
Swinggui gui = new Swinggui();
now you must make gui visible, for this write.
gui.setVisible(true);
And you are good to go.
Refer everything in code using "this" and you would have non static items.

Categories