My code is this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Graphics;
import java.net.URL;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;
import javax.swing.Timer;
public class chromeNPlayerScreen extends JFrame implements ActionListener{
DrawScreen dPnl = new DrawScreen();
public void actionPerformed(ActionEvent e){
}
public void main(String[ ] args){
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.add(dPnl);
this.setSize(600,600);;
this.setVisible(true);
this.setResizable(false);
this.setLocation(200, 200);
}
}
But when i run it.....
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Could someone explain to me why this isnt working?
the DrawScreen code is
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Graphics;
import java.net.URL;
public class DrawScreen extends JPanel {
String picPath = "pictures/";
ClassLoader cl = pokemonChromeNewPlayerScreen.class.getClassLoader();
URL imgURL = cl.getResource(picPath+"welcomeBG.png"),imgURL2 = cl.getResource(picPath+"dialogBox.png"),
imgURL3 = cl.getResource(picPath+"Professor.png");
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG, imgDialog, imgProfessor;
public void imgImport(){
imgBG = tk.createImage(imgURL);
imgDialog = tk.createImage(imgURL2);
imgProfessor = tk.createImage(imgURL3);
}
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
Graphics2D g2 = (Graphics2D)g;
for(int x=0;x<=600;x+=25){
g2.drawLine(x,0,x,600);
g2.drawString(""+x,x+5,20);
}
for(int y=0;y<=600;y+=25){
g2.drawLine(0,y,600,y);
g2.drawString(" "+y,0,y+20);
}
}
}
This is the code for the DrawScreen, atm all it does it drag a grid but thats because i just started it and wanted the x,y values for different positions
I'm assuming this is something related to your IDE. Specifically, it's looking for a non-static version of main().
This:
public void main(String[ ] args){
}
Should actually be:
public static void main(String[ ] args){
}
... of course, this means the this reference no longer works - you'll need to actually create a chromeNPlayerScreen first:
public static void main(String[ ] args){
chromeNPlayerScreen screen = new chromeNPlayerScreen();
screen.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
screen.add(dPnl);
screen.setSize(600,600);;
screen.setVisible(true);
screen.setResizable(false);
screen.setLocation(200, 200);
}
Your main method is currently not behaving as the entry method. It should be defined as static i.e.
public static void main(String[ ] args){
public void main(String[ ] args){
should be
public static void main(String[ ] args){
Without the appropriate main-method declaration there is no entry point for the JVM.
Having said this, it looks like the code currently in your 'main' should really be in a constructor of your class - and it looks like you probably meant to create an instance of your class in the main-method.
Your main is not static , replace this:
public void main(String[] args)
by this :
public static void main(String[] args)
Related
I am building a simple program with one button. I want to play the "zvuk.wav" file after I click on the button. It's not working though and I cant solve why. When I click the button, nothing happens. The zvuk.wav file is in the src file with the classes.
Here is my first class which imports java.applet:
package Music;
import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;
public class Music {
private URL soubor;
public Music(String cesta){
try {
soubor = new URL("file:"+cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button:
package Music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame{
public static final int WIDTH = 480;
public static final int HEIGHT = 600;
private String file;
public MainFrame(){
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
JButton bPlay = new JButton("PLAY");
jPanel.setLayout(null);
add(jPanel);
jPanel.add(bPlay);
bPlay.setBounds(200, 250, 100, 50);
bPlay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Music music = new Music("zvuk.wav");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Please note that Applet.newAudioClip(url).play() does not throw an error if it fails for whatever reason (for example nothing will happen if the project cannot find the wav file).
Try this stand alone test app. Does it work?
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("file:zvuk.wav" );
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
System.in.read();
ac.stop();
} catch (Exception e) {
System.out.println(e);
}
}
}
If this small sample works, then it should be a small matter to modify it for your purposes.
However if it doesn't work then we almost certainly know that you project is unable to find the wav file.
Try add this to the code above:
//existing line
URL url = new URL("file:zvuk.wav" );
//new lines to debug wav file location
File myMusicFile = new File(url.getPath());
if(myMusicFile.exists() && !myMusicFile.isDirectory()) {
System.out.println("File exists and is not a directory");
}
If the file does not exist then that's your problem, and you need to point your URL to the correct location.
However if the file does exist and it still doesn't work then we have another possible issue outside of code.
It is possible that .play() is completing too quickly, see below for an example of how to keep it alive.
It is possible that your wav file is not a type that can be played, or it requires an unsupported codec. This is a far bigger topic and needs a new question, and a little bit of research on your part.
Here is the example to keep it alive from the sample code:
//load and start audio
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
//keep thread alive until a key is pressed
System.in.read();
ac.stop();
Sources:
http://www.java2s.com/Code/JavaAPI/java.applet/AppletnewAudioClipURLaudioFileURL.htm
http://docs.oracle.com/javase/7/docs/api/java/applet/AudioClip.html#play%28%29
I do this using NetBeans. This is the code.
Music.java file
package sound.play;
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
public class Music {
private URL soubor;
public Music(String cesta) {
try {
soubor = new URL("file:" + cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainFrame extends javax.swing.JFrame {
public static final int WIDTH = 200;
public static final int HEIGHT = 200;
private String file;
public MainFrame() {
initComponents();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
jPanel.setLayout(null);
add(jPanel);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Music music = new Music("zvuk.wav");
String filename = "zvuk.wav";
URL url = this.getClass().getResource(filename);
File myMusicFile = new File(url.getPath());
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
I was working on my class project. I tried to draw a face emoji using the graphics thing, but I typed in the class and it says FaceComponent is not found in the FaceComponent project. I was confused about how to name the class and main method.Also, if I want to add a frame, I would have to introduce another class and main method. How do I do that in one program?
package facecomponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
/**
*
* #author HelenPeng
*/
public class FaceComponent extends JComponent {
public static void main(Graphics g) {
Graphics2D g2= (Graphics2D)g;
Ellipse2D.Double interestingEmoji = new Ellipse2D.Double(0,0,100,100);
g2.draw(interestingEmoji);
Ellipse2D .Double eye1 = new Ellipse2D.Double(25,25,10,10);
Ellipse2D .Double eye2 = new Ellipse2D.Double(50,25,10,10);
g2.draw(eye2);
g2.draw(eye1);
Line2D.Double mouth = new Line2D.Double(35,75,75,75) ;
g2.draw(mouth);
}
}
In Java args contains the supplied command-line arguments as an array of String objects.
change
public static void main(Graphics g)
In the Java programming language, every application must contain a
main method whose signature is:
public static void main(String[] args) {
When your java program run as application JVM will first try to find main method will one of the below syntax, so try to change your syntax to one of the belo version.
public static void main(String[] args) { }//Prefered style
public static void main(String args[]) { }
public static void main(String... args) { }//which additionally allows callers to use varargs syntax
Here your definition of main method is wrong. One solution is to have a main class and a drawing class. Change your FaceComponent class to below:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
import javax.swing.JPanel;
/**
*
* #author HelenPeng
*/
public class FaceComponent extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2= (Graphics2D)g;
Ellipse2D.Double interestingEmoji = new Ellipse2D.Double(0,0,100,100);
g2.draw(interestingEmoji);
Ellipse2D .Double eye1 = new Ellipse2D.Double(25,25,10,10);
Ellipse2D .Double eye2 = new Ellipse2D.Double(50,25,10,10);
g2.draw(eye2);
g2.draw(eye1);
Line2D.Double mouth = new Line2D.Double(35,75,75,75) ;
g2.draw(mouth);
}
}
Then create a new class called FaceComponentTest and paste the code below in it.
import javax.swing.JFrame;
public class FaceComponentTest
{
public static void main( String[] args )
{
FaceComponent faceComponent = new FaceComponent();
JFrame faceComponentFrame = new JFrame( "My Face" );
faceComponentFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
faceComponentFrame.add( faceComponent );
faceComponentFrame.setSize( 400, 400 );
faceComponentFrame.setVisible( true );
}
This will display the face. Good luck.
public class FirstClass
{
public static void main(String[] args)
{
System.out.println("Java");
}
}
In above coding portion everything is good. But you may still get,, "no main class found"!! (It is because, I have deleted the built in class and created a new class named "FirstClass".)
For not getting this error at first 'debug' the class and then 'run'
This is the strangest bug I've ever encountered.
Whenever I start my program, in about 1 of 2 times, the gui is successfully created and pop-ups. In the other 1 out of 2 times, I get no gui, I get no error and all the code is executed in the same order as whenever the gui is successfully created.
What is causing this bug? And how could I resolve this? I'm clueless..
The view class :
package view;
import controller.GameController;
import lombok.Data;
import model.GameModel;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#Data public class View extends JFrame {
GameInterface gameInterface = new GameInterface();
MainMenuScreen menuScreen = new MainMenuScreen();
public View() {
super("View");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
displayMenuScreen();
setVisible(true);
}
public void displayMenuScreen(){
menuScreen.getSTARTTHEGAMEButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
GameModel.getInstance().newGame();
displayGameInterface();
GameController.startGame();
}
});
setContentPane(menuScreen.getContentPane());
}
public void displayGameInterface(){
setContentPane(gameInterface.getContentPane());
}
}
The Main Menu class:
package view;
import lombok.Data;
import javax.swing.*;
#Data public class MainMenuScreen extends JFrame{
private JButton STARTTHEGAMEButton;
private JPanel rootPanelMainMenu;
private JTextPane crazyBananaRepublicTycoonTextPane;
public MainMenuScreen() {
super("MY GAME'S NAME");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setContentPane(rootPanelMainMenu);
System.out.println("HEYHEY3");
}
}
The class where the view is created:
import model.GameModel;
import model.GameModelObserver;
import view.View;
public class CrazyBananaRepublicTycoon {
public static final void main(String args[]){
View view = new View();
view.setVisible(true);
GameModelObserver gameModelObserver = new GameModelObserver(view.getGameInterface());
GameModel.getInstance().addObserver(gameModelObserver);
GameModel.getInstance().setGameModelObserver(gameModelObserver);
}
}
You are not properly using the Event Dispatch Thread...
You must only interact with most Swing/AWT objects via the EDT.
Change your main method:
public static final void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
View view = new View();
view.setVisible(true);
GameModelObserver gameModelObserver = new GameModelObserver(view.getGameInterface());
GameModel.getInstance().addObserver(gameModelObserver);
GameModel.getInstance().setGameModelObserver(gameModelObserver);
}
}
}
I made the following code to move a rectangle using arrowkeys of keyboard. The "keyPressed" function does not seem to be working properly.Infact, i don't think it is even getting called when a key is pressed bcz when i tried to print some text when a key is pressed, it was not getting printed.All i see in the output window is a stationary rectangle fixed at the top left corner of the window.Here is my code....pls help me...i need it desperately
import javax.swing.JFrame;
public class Main
{
public static void main(String args[])
{
JFrame window=new JFrame();
window.setSize(600,400);
window.setTitle("window");
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingComponent DC=new drawingComponent();
window.add(DC);
}
}
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.Timer;
public class drawingComponent extends JComponent implements ActionListener,KeyListener
{
Timer t=new Timer(2000,this);//moving after 5 milliseconds
static int x=0;
static int y=0;
private static int velx=0;
private static int vely=0;
public drawingComponent()
{
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
System.out.println("tr1");
}
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
Rectangle rect1=new Rectangle(x,y,50,30);
g2.setColor(Color.RED);
g2.fill(rect1);
System.out.println("tr2");
}
public void actionPerformed(ActionEvent e) //inbuilt fncn f actionListener(interface) which needs to be created
{
x+=velx; //changing values
y+=vely;
System.out.println("tr3");
repaint(); //inbuilt fncn to repeat the paintComponent method
}
public void keyPressed(KeyEvent e)
{
int code=e.getKeyCode();
if(code==KeyEvent.VK_UP)
{ velx=0; vely=-1;repaint(); }
if(code==KeyEvent.VK_DOWN)
{ velx=0; vely=1; repaint(); }
if(code==KeyEvent.VK_LEFT)
{vely=0; velx=-1; repaint(); }
if(code==KeyEvent.VK_RIGHT)
{vely=0; velx=1; repaint();}
}
public void keyTyped(KeyEvent e)
{}
public void keyReleased(KeyEvent e)
{}
}
Welcome to the wonderful world of KeyListeners...
While you have set the component focusable, you've not requested that the component be focused.
You could try calling requestFocusInWindow, but he this raises the question of when to call it.
You could call it within the constructor, but because the component doesn't belong to a valid visible component yet, the call may fail. You could override the components addNotify method and add the call to it, after you call super.addNotify, but the requestFocusInWindow method doesn't gurentee that focus will be given the component
Instead, you could simply avoid all this hassle and use the key bindings API instead, which will give you control over the level of focus require for key events to be triggered
As a side note, you should call setVisible on your frame after you've set up the UI completely
package common;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ResourcesToAccess {
public static Icon sharedAbstractDownIcon;
public static Icon sharedAbstractPlayIcon;
public static Icon sharedAbstractPauseIcon;
public static Icon sharedAbstractBlackCursor;
public static Icon sharedAbstractWhiteCursor;
public ResourcesToAccess(){
InputStream is = this.getClass().getClassLoader().getResourceAsStream("/src/images/blackCursor.png");
try{
BufferedImage bi = ImageIO.read(is);
sharedAbstractBlackCursor = (Icon) new ImageIcon(bi);
new JFrame().add(new JLabel(sharedAbstractBlackCursor)).setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
new ResourcesToAccess();
}
}
I am using this code to see whether the PNG images can be properly loaded to create JLabels, Icons, etc but I get the error that:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at common.ResourcesToAccess.<init>(ResourcesToAccess.java:21)
at common.ResourcesToAccess.main(ResourcesToAccess.java:29)
Why do I see that error message?
try with
this.getClass().getClassLoader().getResourceAsStream("images/blackCursor.png")
it is looking in your classpath so no more src directory there