Game in Java won't respond to key presses - java

I have just exported a Java game I made to a Runnable JAR.
The game has an opening screen (a class named OpeningScreen extending JPanel). When you press ENTER, it's supposed to go from the opening screen to the game itself (create a new Board instance and add it to the JPanel.)
It works fine inside Eclipse.
An instance of OpeningScreen is created in the class with main(), named Starter.
When exporting, I set the Starter class as the "Launch configuration", and set "Library handling" to "Extract required libararies into generated JAR".
After exporting, I get a window saying that it exported with compile errors, but doesn't tell me which errors exactly.
When starting the program from the generated JAR, the opening screen does show, but pressing ENTER won't start the game, although it does work inside Eclipse.
Here's the code for OpeningScreen:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class OpeningScreen extends JPanel implements KeyListener{
private static final long serialVersionUID = 1L;
public OpeningScreen(){
setFocusable(true);
setVisible(true);
addKeyListener(this);
}
public void paint(Graphics g){
super.paint(g);
setBackground(Color.BLACK);
Graphics2D g2d = (Graphics2D) g;
// A lot of drawing Strings.
}
public void startGame(){
JFrame frame = new JFrame("Pong Battle");
frame.setSize(500,500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Board board = new Board();
frame.add(board);
frame.setVisible(true);
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key==KeyEvent.VK_ENTER)startGame();
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
}
EDIT: Starter class:
import javax.swing.*;
import java.awt.*;
public class Starter extends JFrame {
public Starter(){
setSize(500,500);
setResizable(false);
setTitle("Pong Battle");
setDefaultCloseOperation(EXIT_ON_CLOSE);
OpeningScreen openingS = new OpeningScreen();
add(openingS);
setVisible(true);
}
public static void main(String[]args){
Starter starter = new Starter();
}
}
What could be the problem? Thanks

Don't use a KeyListener. You should be using Key Bindings.
See Motion Using the Keyboard for the reasons why and a working example.

Your opening screen needs to be added inside another container and subsequently another Jframe
Create another JFrame.
Make it undecorated. f.setUndecorated(true)
Make opening screen panel as content panel f.setContentPane(new OpeningPanel())
Display this frame.
Remove the opening screen frame once Enter key is pressed. f.dispose()
and then call startGame()

Related

Error occurs when trying to start Java GUI in IntelliJ

GameLauncher class
package me.beanbeanjuice;
import me.beanbeanjuice.utilities.Game;
import me.beanbeanjuice.utilities.filehandlers.DictionaryHandler;
import me.beanbeanjuice.utilities.filehandlers.DistributionHandler;
public class GameLauncher {
public GameLauncher() {
new Window();
}
public static void main(String[] args) {
new DictionaryHandler();
new DistributionHandler();
new Game();
// TESTING. MenuScreen() should start first. MenuScreen() when "startButton" is hit, it should start game.
//new Window();
new GameLauncher();
}
}
Window class
package me.beanbeanjuice;
import javax.swing.JFrame;
public class Window extends JFrame {
public Window() {
super();
setTitle("Boggle");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new GamePanel(720, 1280));
add(getContentPane());
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
GamePanel class
package me.beanbeanjuice;
import javax.swing.*;
import java.awt.*;
public class GamePanel extends JPanel {
public static int width;
public static int height;
public GamePanel(int width, int height) {
super();
setPreferredSize(new Dimension(width, height));
setFocusable(true); // Allows the JPanel to have input as soon as the JFrame is made.
requestFocus();
}
}
Error Message
Error Message in GameLauncher class
Hello, I'm following a tutorial for making a Java GUI in IntelliJ, and it won't even start. If you look at the last link, it shows this weird "error" and it won't start the GUI. It leads to the "Error Message" link as shown for link number 4. How do I fix this? I followed the tutorial exactly and even tried making a new project to no avail. I've tried swapping the Window() and GameLauncher() calls in the GameLauncher class but it is still not working. I've also tried with and without the super() call.
So the issue was with a display driver, however, I do not know if it still occurs. What fixed it was unplugging all of my external monitors, running the code, plugging them back in, stopping the code, running the code, then it worked again.
In Window Constructor in the Window class, at this line add(getContentPane()); you are adding container's parent to itself. This line is the same as writing getContentPane.add(getContentPane()).
I dont know what do you mean to put in the frame. Using JFrame you need to add the child to the JFrame's content pane. Removing this line works for me.
https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html

How to draw shape inside of JPanel that is inside JFrame

I have issue with drawing shapes inside of JPanel that I already added using Netbeans GUI. Now, I have no idea where to add code for drawing a circle inside of that JPanel and how to insert and call it in the JPanel that is sitting empty now, waiting for this shape to be drawn. I already set up destination JPanel to be Flow layout.
Netbeans Designer created a big class in which I have entire frame with this JPanel, and I want to keep it inside of it as I can't really add it any other way because Designer doesn't let me change main initComponents method in which all components are sitting now. I have been reading tutorials and previous posts but noone really encountered this using Netbeans Designer.
SO can someone just help me with adding proper method in this frame class and how to call it from JPanel I want to draw in. JPanel is 50x50 pixels.
So as per #Abra, I changed some code:
so I made a new Circle Class, adjusted it a bit as I don't want to create a new frame but put this in JPanel.
public class Circle extends JPanel {
Color color;
public void circle(Color color) {
this.color = color;
setPreferredSize(new Dimension (30,30));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(0, 0, r, r);
g.setColor(color);
}
private void showGUI() {
JPanel panel = new JPanel();
panel.add(this, FlowLayout.CENTER);
panel.setVisible(true);
}
}
Then I opened JPanel in Designer, and added code to run it, in initComponents method like this:
circlePanel.setPreferredSize(new java.awt.Dimension(40, 40));
new Circle().showGUI();
PanelDS.add(circlePanel);
circlePanel is destination for this drawing and is inside PanelDS itself. It doesn't work this way tho, but Netbeans shows no errors in code. Additionally, how can I forward color to circle class.
In order to draw on a JPanel you need to override the paintComponent() method of JPanel. In order to override the method, you need to create a class that extends JPanel. I don't think that there exists a GUI designer that can generate the required code for you. So you have to write the code of the class that extends JPanel.
Here is a minimal example. It displays a blue circle.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Drawing2 extends JPanel {
private JFrame frame;
public Drawing2() {
setPreferredSize(new Dimension(100, 100));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(25, 25, 50, 50);
}
private void showGui() {
frame = new JFrame("Drawing");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
new Drawing2().showGui();
}
}
Here's what you should see when you run the above code.

Combining class with buttons and frame - GUI

I want to create menu buttons in Screen class and add menu to frame then. I don't know what is wrong with it. How to create buttons in other class and add it to to the frame?
My frame class:
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Start extends JFrame {
public static String title = "Bozenka";
public static Dimension size = new Dimension(700,500);
public static String backgroundPath = "/home/alpha_coder/Eclipse/Bozenka/images/bg.jpg";
public Start(){
setTitle(title);
setSize(size);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
setResizable(false);
initialization();
}
public void initialization(){
Screen screen = new Screen();
screen.setBounds(20, 20, 660, 60);
add(screen);
try {
setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File(backgroundPath)))));
setBackground(Color.WHITE);
} catch (IOException e) {
System.out.println("Image doesn't exist");
}
setVisible(true);
}
public static void main(String[] args){
Start start = new Start();
}
}
The class where I want to create a menu:
import java.awt.*;
import javax.swing.*;
public class Screen extends JPanel{
public JButton test;
public Screen(){
setBackground(Color.pink);
test = new JButton("test");
test.setBounds(2, 2, 40, 10);
}
}
Most important: get rid of setLayout(null) and setBounds(...) as that will lead to an extremely difficult to create and adjust GUI. Learn and use the layout managers.
Create your JButtons in your new class, Screen
add them to this, the Screen JPanel but first give it a decent layout manager, such as a GridLayout,
In another class, create an instance of your JFrame class and an instance of the Screen object, and add the Screen JPanel to your JFrame's contentPane in whatever desired location you want, be it BorderLayout.CENTER or one of the other locations.
Again, most important: google and study the layout manager tutorial. Here's the link.
Note, a major problem with your current code is that you add your JButton to nothing. It needs to be added to Screen, to this for your code to work in any way.

Making an image show up in Java

I've been struggling to get an image to show up for some time now. Ive read a few different things, and all of them seem to have different ways of showing images. Can someone tell me what I'm doing wrong? I'm trying to make a program that uses 2 classes to make a picture show up in a frame. I guess what I don't understand still is what a Graphics object is, what a Graphics2D object is and how its different, and what method from what class do I call in order to make an image show up. Here is my code:
public class Smiley {
private BufferedImage smileyFace;
private Graphics2D renderWindow;
private Dimension smileyPosition;
private File smileyFile;
public Smiley() {
try{
smileyFile = new File("C:\\Users\\MyName\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
}
catch (Exception e){
System.out.println("There was an error finding or reading the file \" smiley.png.\"");
}
MainScreen.graphicPane.drawImage(smileyFace,50,50, null);
}
and the second class:
public class MainScreen extends JFrame{
public static MainScreen ms;
public static Graphics2D graphicPane;
public static void main (String[] args){
MainScreen ms = new MainScreen();
Smiley newSmiley = new Smiley();
}
public MainScreen(){
super("Main Screen Window");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(500,800);
this.getContentPane().setBackground(Color.black);
graphicPane = (Graphics2D) this.getContentPane().getGraphics();
}
}
the program compiles with no errors and nothing is reported back to me about not finding the file.
Your going to need some sore of paint method. For that you will require a Component to paint on. You need to learn a GUI framework, like Swing. There are clear compoents you can paint on like a JPanel. With that panel you need to override its paintComponent method.
The Graphcics object is what the component uses to actually paint the graphic onto the component.
The Graphics2D object just extends the capabilities of the Graphics object.
You should take a look at the Swing tuorial and the **Graphics toturial
To get your program running though you would do something like this
public class DrawPanel extends JPanel {
BufferedImage smileyFace;
public DrawPanel() {
try{
smileyFile = new File("C:\\Users\\MyName\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
}
catch (Exception e){
System.out.println("There was an error finding or reading the file \" smiley.png.\"");
}
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(smileyFace,50,50, this);
}
#Override
public Dimension getPreferredSize(){
return new Dimension(500, 500);
}
}
Then you can instantiate that panel in another class, adding it to a JFrame to run it
public class Main {
public static void main(String[] args) {
SwingUtiliites.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new DrawPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
You are calling this in your constructor for your Smiley class.
MainScreen.graphicPane.drawImage(smileyFace,50,50, null);
If you are going to paint the image yourself you need to override paintComponent() in a component that gets added to your main screen.
Or just add the image to a JLabel that you added to the main screen.
You draw image in wrong way.
For using drawImage() you need to use that in paintComponent() method of JComponent(for example JPanel), examine next code:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.beans.Transient;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends JFrame {
public Example() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Smiley());
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
new Example();
}
class Smiley extends JPanel{
private BufferedImage smileyFace;
Smiley(){
try {
File smileyFile = new File("C:\\Users\\MyName\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
} catch (Exception e) {
System.out
.println("There was an error finding or reading the file \" smiley.png.\"");
}
}
#Override
#Transient
public Dimension getPreferredSize() {
return new Dimension(smileyFace.getWidth(),smileyFace.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(smileyFace, 0,0, this);
}
}
}
or you can add your image to JLabel and that do all for you, change Smile class like next:
class Smiley extends JPanel{
Smiley(){
ImageIcon icon = new ImageIcon("C:\\Users\\MyName\\Desktop\\smiley.png");
JLabel l = new JLabel(icon);
add(l);
}
}
ALso read more about customPaintings.

I want to make my frame close when the X(close button) is clicked

I have a small template that ive built for the purpose of implementing an applet through a simple java application via netbeans 7.1 (as in not using Javacard, Netbeans Platform etc ..just a simple java application with applet initialized when application runs)
I have managed to make it invoke the applet when i press the run button in netbeans and i ahve functionality inside the applet but, i cant seem to get it to close and i have a horrible feeling people are gonna tell me to have used jFrame and implement the EXIT_ON_CLOSE method.
This is NOT something I would like to know how to do , my mission is to implement it using Frames != jFrames.
I hope someone can help as its bugged me for a bit now and i have to get on with Java assignment that involves its use.
Enclosed is the code/classes for A: the appletframe and B:the applet
* 1.4 Write an applet to display a line of text.
* The text should then change its font size and style (bold, italic, underline)
* depending on where the mouse is clicked on the screen.
*/
package appletframe;
import java.awt.Graphics;
import java.awt.Frame;
import java.applet.Applet;
/**
* #author MuthaLoad aka Gruffy2012
*/
import java.awt.*;
public class AppletFrame extends Applet{
public static void main(String[] args) {
/*construct needs object instances*/
MrApplet mrApplet = new MrApplet(); // create instance/obj of MrApplet
Frame myFrame = new Frame("Applet"); // create frame "title optional"
//setDefaultCloseOperation(myFrame.EXIT_ON_CLOSE);(jFrame- not wanted)
/* add applet to the frame*/
//myFrame.addWindowListener();
myFrame.add(mrApplet, BorderLayout.CENTER);
myFrame.setBounds(10,10,500,500);
myFrame.setVisible(true); // step to make frame visible
/*initialize instance of mrApplet*/
mrApplet.init();
} // end main
} // end class
B: applet
package appletframe;
import java.awt.*; //for buttons
import java.awt.event.*; //for events
import java.applet.*; //main applet api`s
import java.awt.Graphics; //graphics
public class MrApplet extends Applet implements ActionListener
{
private static final long serialVersionUID = 1L;
Button btnClick;
String msg = "";
public void init()
{
// TODO start asynchronous download of heavy resources
setSize(500, 500);
Button btnClick = new Button("Press Me ");
btnClick.addActionListener(this);
add(btnClick);
}
public void actionPerformed(ActionEvent e)
{
//throw new UnsupportedOperationException("Not supported yet.");
msg = "Yay, the button works";
repaint();
}
public void paint (Graphics g)
{
g.setFont(new Font("Serif", Font.ITALIC, 30)); //new font obj, font , font style, font size
g.setColor(new Color(0,255,0)); //new color obj, r,g,b
g.drawString(msg, 40, 80);
}
// TODO overwrite start(), stop() and destroy() methods
}
Once again thanks for reading, and to clarify any confusions..
I am looking for a pointer as to the solution of closing my applet and frame window upon exit , without reimplementing it all using jFrame, though i know this would be easier in the first instance.
Thankyou and as always, indebted to all your advice.
gruffy321
add this line at the end of ApplicationFrame class.
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You want to do it with Frame not with JFrame, then you have to add the WindowListener event to the frame and have to override windowClosing() method.
myFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
});

Categories