Why does my code produce errors? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
* A simple panel for testing various parts of our game.
* This is not part of the game. It's just for testing.
*/
package game;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
/**
* A simple panel for testing various parts of our game.
* This is not part of the game. It's just for testing.
*/
public class TestPanel extends JPanel
{
private static final long serialVersionUID = 1L; // Ignore this - It's just to get rid of a warning.
// Instance variable(s).
private Image backdrop;
/**
* Constructor - loads a background image
*/
public TestPanel ()
{
try
{
ClassLoader myLoader = this.getClass().getClassLoader();
InputStream imageStream = myLoader.getResourceAsStream("resources/path_1.jpg");
backdrop = ImageIO.read(imageStream);
// You will uncomment these lines when you need to read a text file.
InputStream pointStream = myLoader.getResourceAsStream("resources/ path_1.txt");
Scanner s = new Scanner (pointStream);
}
catch (IOException e)
{
System.out.println ("Could not load: " + e);
}
}
/**
* This paint meethod draws the background image anchored
* in the upper-left corner of the panel.
*/
public void paintComponent (Graphics g)
{
g.drawImage(backdrop, 0, 0, null);
}
/* Override the functions that report this panel's size
* to its enclosing container. */
public Dimension getMinimumSize()
{
return new Dimension (600, 600);
}
public Dimension getMaximumSize()
{
return getMinimumSize();
}
public Dimension getPreferredSize()
{
return getMinimumSize();
}
}
This code is aimed towards a videogame assignment I am working on for my Java course. This class is only used to test our code out. In the direction for the assignment, I was told to put code that is present within the try block, as show above. Apparently, the code should open a JPEG image that I have within a folder in my workspace. However, when I try the code, it only states:
Exception in thread "main" java.lang.NullPointerException at
java.io.Reader.<init>(Unknown Source) at
java.io.InputStreamReader.<init>(Unknown Source) at
java.util.Scanner.<init>(Unknown Source) at
game.TestPanel.<init>(TestPanel.java:43) at
game.TestApplication.main(TestApplication.java:24)
I am not fully clear on what inputStream and classLoaders do. So, if you have any basic information on either, that would be great. Also, I know the other methods below the constructor method have no code within them. The directions for my assignment have not stated what I should input into these methods.
enter code here
enter code here

You've got some extra spaces in the second filename there:
"resources/ path_1.txt"
Clearly that's a typo. Then, when you call getResourceAsStream with this stream, it doesn't find the file you want, because of those extra spaces, so that call returns a null pointer, which is being passed into scanner, and eventually causing the NPE.

There are lots of existing SO Questions that explain why getResourceAsStream returns null under various circumstances; e.g.
Junit + getResourceAsStream Returning Null
getResourceAsStream() is always returning null
getResourceAsStream returning null
The method getResourceAsStream returns null on ubuntu
They all boil down to one root cause: the class loader can't find the resource you told it to find. The javadoc says that if the classloader can't find the requested resource, it returns null rather than throwing an exception.
And that can happen for a variety of reasons. The common ones include:
the resource doesn't exist,
the resource is not on the classpath (e.g. it is a file in the file system),
it does exist on the classpath but you've used the wrong path string for it, or
you've used a relative path string, but the context you are resolving it is incorrect.

Related

Trying to Save a Java GUI as an Image in higher resolution

I am new to Stack Overflow but not new to programming. I am writing a java project for my own personal use, and maybe for some friends. I create a GUI, and add some images to a collage, and then I want to save it as a JPG that will scale to print nicely on an 8 1/2 x 11 paper (landscape).
I found the following code by asaren08 on Github, which works fine but the jpg is lower resolution. I need something of print quality.
I create my collage in an ImagePanel shown in the class below, it looks nice. I save it and print it and it is low resolution. I understand that is because my screen is lower resolution than my printer. If I create it pretending my resolution is 300 DPI, then it shows up on my screen scaled to fit, and that is what it saves, which is not what I want! It is not even proportional. For example, my laptop monitor is 15 inches -ish, wide and short. My image comes out wider than it should, exactly what I see on my monitor, but I want to to come out the way I set it, not the way it shows up on my monitor. On the other hand, I need to be able to see the GUI to set up my collage...
Any suggestions?
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class ImagePanel extends JPanel {
/**
* Save the Panel as image with the name and the type in parameters
*
* #param name name of the file
* #param type type of the file
*/
public void saveImage(String name,String type) {
System.out.println("width of image panel ="+getWidth());
BufferedImage image = new BufferedImage(getWidth(),getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
paint(g2);
try{
ImageIO.write(image, type, new File(name+"."+type));
} catch (Exception e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
Update: I added my ImagePanel to a JScrollPane as suggested in the comments. That makes it hard to see where I'm at in my collage. So for now, my silly solution is to put a little thumbnail above the ImagePanel to show what the whole thing looks like and I can see from that where I'm sitting on the ImagePanel.

How to use a CustomScoreQuery in Lucene 7.x

I'm relativly new to Lucene and want to implement my own CustomScoreQuery since I need it for my University.
I used the Lucene demo as my starting point to index all documents in a Folder and want to score them using my own algorithm.
Here are the links to the source code of the demo.
https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/IndexFiles.html
https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/SearchFiles.html
I'm checking with Luke: Lucene Toolbox Project to see my Index which is as expected. My problem occurs accessing it.
package CustomModul;
import java.io.IOException;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Terms;
import org.apache.lucene.queries.CustomScoreProvider;
import org.apache.lucene.queries.CustomScoreQuery;
import org.apache.lucene.search.Query;
public class CountingQuery extends CustomScoreQuery {
public CountingQuery(Query subQuery) {
super(subQuery);
}
public class CountingQueryScoreProvider extends CustomScoreProvider {
String _field;
public CountingQueryScoreProvider(String field, LeafReaderContext context) {
super(context);
_field = field;
}
public float customScore(int doc, float subQueryScore, float valSrcScores[]) throws IOException {
IndexReader r = context.reader();
//getTermVector returns Null
Terms vec = r.getTermVector(doc, _field);
//*TO-DO* Algorithm
return (float)(1.0f);
}
}
protected CustomScoreProvider getCustomScoreProvider(
LeafReaderContext context) throws IOException {
return new CountingQueryScoreProvider("contents", context);
}
}
In my customScore function I access the Index like described in most Tutorials. I should get access to the Index using getTermVector but it returns NULL.
In other posts I read that this could be caused by contents being a TextField which is declared in the Lucene Demo IndexFiles.
After trying a lot of different approaches I came to the conclusion that I need help and here I am.
My Question now is if I need to adjust the Index Process (how?) or is there another way to access the Index in the ScoreProvider other then getTermVector?
I was able to solve the Problem myself and wanted to share my solution if someone finds this Question looking for answers.
The Problem was indeed caused by the contents being a TextField in
https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/IndexFiles.html
To solve this Problem one has to construct his own Field which I did replacing line 193 in said IndexFile with
FieldType myFieldType = new FieldType(TextField.TYPE_STORED);
myFieldType.setOmitNorms(true);
myFieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS);
myFieldType.setStored(false);
myFieldType.setStoreTermVectors(true);
myFieldType.setTokenized(true);
myFieldType.freeze();
Field myField = new Field("contents",
new BufferedReader(new InputStreamReader(stream,
StandardCharsets.UTF_8)),
myFieldType);
doc.add(myField);
this allows the use of getTermVector in the customScore Function. Hope this will help someone in the future.

Unable to change system string resource

I am making a Xposed Module that would allow users to modify the message displayed on the lock screen when Wrong pattern, pin or password is entered.
I am following this tutorial.
After digging into the android source code on GitHub, I found out the method that displays the message on the lock screen, that was onPatternChecked() in the class com.android.keyguard.KeyguardPatternView.java. The method uses the kg_wrong_pattern string resource which has the value Wrong Pattern when wrong pattern is drawn.
This is how my class looks like:-
package com.batrashubham.customlockscreenerrormessage;
import android.content.res.XResources;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
/**
* Created by shubham on 19/7/16.
*/
public class CustomErrorMessage implements IXposedHookInitPackageResources,IXposedHookZygoteInit {
#Override
public void initZygote(StartupParam startupParam) throws Throwable {
XResources.setSystemWideReplacement("android","bool","config_unplugTurnsOnScreen",false);
}
#Override
public void handleInitPackageResources(XC_InitPackageResources.InitPackageResourcesParam resparam) throws Throwable {
if(!resparam.packageName.equals("com.android.keyguard")){
return;
}
XposedBridge.log("I just got into your lock screen");
resparam.res.setReplacement("com.android.keyguard", "string", "kg_wrong_pattern", "Nice try.!!");
}
}
The module is showing up in the Xposed Installer app and is successful activated, but still the original message is showing up on the lock screen when I draw a wrong pattern.
I am currently testing it on Android 6.0.1 (CyanogenMod 13).
What am I doing wrong?

Documentation Confusion [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm aspiring to be a software engineer, and I have been taking Computer Science courses for my degree college. While they teach us a lot of basics that are mostly easy to learn online, I also want to learn things such as common documentation conventions. I am sure that once I start taking courses like data structures they will teach a lot more about the processes leading up to the actually coding, which from what I understand are the most important parts. But I would like to start learning to do things properly early on, so I am trying to learn how to properly document my code.
I read the Wikipedia page about javadoc, and I tried to the best of my ability to replicate it. If anyone could provide any tips, pointers, or corrections to my documentation (or even the code) for this simple program I made just to practice documentation it would be much appreciated.
Transform.java
import javax.swing.JFrame;
/**
* #author Nekko Rivera nekkoriv#gmail.com
* #version 1.0
* #since 2015-08-9
*/
public class Transform
{
public static void main(String[] args)
{
Gui theGui = new Gui();
theGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theGui.setSize(600, 400);
theGui.setResizable(false);
theGui.setVisible(true);
}
}
Gui.java
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* #author Nekko Rivera nekkoriv#gmail.com
* #version 1.0
* #since 2015-08-9
*/
public class Gui extends JFrame
{
/**
* Generated by Eclipse
*/
private static final long serialVersionUID = 7253493887106168112L;
/**
* Name displayed on choiceBox for the user to select
*/
String[] portraitNames = {"Default", "Nurio", "Giada", "Triggah", "Spider"};
/**
* The images that will be displayed upon selection
*/
Icon[] portraits = {new ImageIcon(getClass().getResource("default.png")), new ImageIcon(getClass().getResource("nurio.png")), new ImageIcon(getClass().getResource("Giada.png")),
new ImageIcon(getClass().getResource("Triggah.png")), new ImageIcon(getClass().getResource("spider.png"))};
/**
* Allows the user to choose a portrait to display
*/
private JComboBox <String> choiceBox;
/**
* Prompt for the user to change their appearance
*/
private JLabel promptLabel;
/**
* Builds the window for the program
*/
/**
* Displays the image chosen by the user
*/
private JLabel pictureLabel;
public Gui()
{
super("Transform");
setLayout(new FlowLayout());
drawGui();
}
/**
* Draws the items onto the frame
*/
public void drawGui()
{
pictureLabel = new JLabel(portraits[0]);
promptLabel = new JLabel("Change appearance?");
choiceBox = new JComboBox <String> (portraitNames);
choiceBox.addItemListener(
new ItemListener(){
#Override
public void itemStateChanged(ItemEvent event)
{
if(event.getStateChange() == ItemEvent.SELECTED)
pictureLabel.setIcon(portraits[choiceBox.getSelectedIndex()]);
}
}
);
add(pictureLabel);
add(promptLabel);
add(choiceBox);
}
}
TLDR: is this documented correctly?
There is not really a correct way to do documentation. What is good documentation depends on a lot of factors:
the type of software (application, library, ...)
the target group of the documentation (fellow programmers, end users, ...)
conventions and tastes of your organisation/company
etc.
Javadoc only generates a specific kind of documentation, namely API documentation for programmer's using the documented things (this may include your future self). In light of this some general pointers can be given:
All classes, fields and methods visible from outside the package must be documented. This includes public classes and public and protected members (fields and methods). In your case, documentation for the public classes is missing.
Whether private and package private items must also be documented depends on local customs. It is never wrong to document something.
Useful Javadoc documentation for a method describes what a method does. It may also describe how the method does that, but in most cases that is not really interesting for the person using the method and can also be documented with non-Javadoc comments.
Documentation should be precise. If there are pre-conditions, they should be mentioned (for example, something cannot be null, a number must be >= 0, etc). If there are specific corner cases, they should be mentioned. If a method has side-effect, this must be mentioned.
I hope these pointers are helpful.

How do I construct and use an object inside the inner class of a nested class?

I posted this earlier, but it wasn't quite up to par with stackoverflow standards. I cleaned up the code and articulated my question a bit more, so here goes:
I'm making a two player asteroids game in an applet for a CS1 project. I'm trying to figure out how to implement sound effects using methods I can call at certain times. I found this tutorial (http://www.dreamincode.net/forums/topic/14083-incredibly-easy-way-to-play-sounds/) on doing just that, but I'm having some trouble with the nested loop syntax.
How do I construct the 'Sound' object within the Sound class from a different class (in my case, AsteroidsGame.java) ?
Because of the messiness of the tutorial code, here's mine for improved readability.
//Import Statements
import java.applet.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Audioapp extends JApplet
{
public class Sound // Holds one audio file
{
private AudioClip song; // Sound player
private URL songPath; // Sound path
Sound(String filename)
{
try
{
songPath = new URL(getCodeBase(),filename); // Get the Sound URL
song = Applet.newAudioClip(songPath); // Load the Sound
}
catch(Exception e){} // Satisfy the catch
}
//Loops audio file
public void playSound()
{
song.loop();
}
//Stops audio file
public void stopSound()
{
song.stop();
}
//Plays audio file once
public void playSoundOnce()
{
song.play();
}
} //Closes Sound()
public void init()
{
Sound testsong = new Sound("song.mid");
testsong.playSound();
}
} //Closes Audioapp()
Edit 1: Just remembered someone from the last thread suggested I post what this does when I compile/run it. This .java on it's own does nothing; but it does indeed compile without errors when placed with the rest of my project.
Edit 2: Thanks a lot Zim-Zam for all your help, if anyone finds this thread and has the same issue, please consult his comments.
I recommend that you change your inner class to public static class Sound - this will let you construct instances of the class without needing an instance of Audioapp.
Then, to create an instance of Sound, you simply treat it as though its name were Audioapp.Sound, e.g. Audioapp.Sound sound = new Audioapp.Sound()
If the inner class isn't static, then you would use Audioapp.Sound sound = audioApp.new Sound(), where audioapp is an instance of Audioapp

Categories