Eclipse Java - Running FIle issues; Im new around here - java

I have the following code:
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.Renderer;
import javax.swing.Timer;
// All packages imported , ready for use... Add more if need be : +
#SuppressWarnings("unused")
public class main implements KeyListener, ActionListener
{
public boolean board_show =true;
public int AOB1 = 16;
public int AOB2 = 16;
public static int WOB = 640;
public static int HOB = 640;
public int GStat = 0;
// Defines when game is playing, toggle-able twice 0, 1, 2
// 0 = Menu, 1 = Paused, 2 = Game
// Might Become Redundant
// TODO Make this feature redundant!
public boolean click, space;
public int turn;
public Component renderer;
public void ScreenUp()
{
Timer timer = new Timer(20, this);
JFrame jframe = new JFrame("CHESS");
jframe.setSize(WOB, HOB);
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.add(renderer);
jframe.addKeyListener(this);
timer.start();
}
public static void render(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0, 0, WOB, HOB);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
And I want to know why Eclipse, my editor will not let me run this file, as a whole, even in other modes it comes up with errors. I am fairly new to Java, so I am trying to make a Game - Chess. For now I just want to know why the editor will not let me run it and how I can run it. And of course, since I am new to Java, I only know the basics of the language, so any detailed response would be greatly appreciated!

You expect that having a class named main is enough to define an entry point to run a Java application. Wrong.
You need a method with exactly this signature
public static void main(String[] args) {
in your class. That method defines what happens when you "run" the class/application.
And the real answer is: study those tutorials written for people ... that just "start" with Java, like the one from Oracle. Even when you are proficient in other languages - when you just assume how things work; chances are that you run into exactly this kind of problems.

Related

How do I make a (keyPressed) KeyListener?

Im trying to write a very simple program that allows you to control a sprite with arrow keys and move around the screen. From what I understand, to do this I need a keyPressed() KeyListener. I believe Im doing this correctly based on the Java Doc but its not returning the correct output when I press the designated key. Can someone please tell me what is wrong with my code, and if possible, provide a simple example of the usage of this class? Thanks!
(Note, code is unfinished)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Display extends JPanel implements ActionListener, KeyListener {
Display() {
// super();
loadImages();
initTimer();
this.addKeyListener(this);
}
BufferedImage sprite;
Timer timer;
int up = 0;
public void loadImages() {
File spriteImage = new File("Pacman_sprite.png");
try {
sprite = ImageIO.read(spriteImage);
} catch (IOException e) {
System.out.println("Sprite import failed");
}
}
public void initTimer() {
timer = new Timer(100, this);
timer.start();
this.addKeyListener(this);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
System.out.println("Key press registered"); //does not print this?
if (key == KeyEvent.VK_UP) {
System.out.println("sucess"); // does not print this?
up++;
repaint();
}
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("release");
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.WHITE);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(sprite, 500, 500 + up, null);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
repaint();
}
}
EDIT:
May have found the answer here. I moved the key handling code to a new class called KeyHandler then added these two lines to the constructor:
addKeyListener(new KeyHandler());
setFocusable(true);
It now appears to be working just fine (sort of, at least it is detecting when the up key is hit. My graphics aren't.)
You are not adding the listener to the JPanel.
Note: I would suggest you to change your design. Right now, Display class is both a JPanel and a Listener (which doesn't make sense in my opinion).
But to add the listener in your code do something like,
this.addKeyListener(this); // This looks awkward right. That's why you should change the design.
in your constructor.

KeyListener not work in object [duplicate]

This question already has answers here:
java keylistener not called
(2 answers)
Closed 8 years ago.
I got problem with KeyListener. I create class gra where is full code need to play game Tetris in constructor i only addKeyListener. In other class Menu I create object Gra gra = new Gra() and coll it when condition is met gra.start(g); but when I am in class Gra KeyListener not work. Please help me sove this issue.
He is code from class gra
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.swing.JPanel;
//#SuppressWarnings("serial")
public class Gra extends JPanel implements KeyListener{
public Gra(){
addKeyListener(this);
setFocusable(true);
requestFocus();
repaint();
}
public void start(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
setFocusable(true);
requestFocus();
repaint();
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
System.err.println("sdfafs");
char c = arg0.getKeyChar();
System.err.println(c);
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
char c = arg0.getKeyChar();
System.err.println(c);
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
char c = arg0.getKeyChar();
System.err.println(c);
}
}
KeyListener is very fickle. The component it is registered to must e focusable and have focus. There are many ways a component can loss focus or, depending on the system, not receive focus when requested.
Instead, use the key bindings API, as it will allow you to configure the focus level which will trigger the key events regardless

Swing - Avoid line filling between different lines

I'm trying to get into Swing by developing a simple drawing application in Java.
The problem is that I'm using an array of Points to keep track on the mouseDragged event, but when I release the mouse button and I begin to draw a new line they get connected (previous line's last node to the first point of the new line).
I was thinking maybe to keep track of the Points listened by the mousePressed and mouseReleased listeners in another ArrayList, to know which are the begin and end points of every line and then, when it's time to draw the lines between the points, checking if they are in the ArrayList and avoid drawing that line.
What is your suggested approach? How can I implement this in my code? Thank you!
package ccdraw;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.event.MouseInputListener;
#SuppressWarnings("serial")
public class DrawingArea extends JPanel implements MouseInputListener {
private ArrayList<Point> pointList = new ArrayList<Point>();
//private ArrayList<Point> beginEndPoints = new ArrayList<Point>();
public DrawingArea() {
super();
super.setPreferredSize(new Dimension(400,400));
setBorder(BorderFactory.createLineBorder(Color.black));
addMouseListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(1.5f));
for (int i=1;i<pointList.size()-1;i++){
// here i should check when it changes between old and new line
// and don't draw the line between those two points!
//if(pointList.get(i).x - pointList.get(i+1).x <= 1 && pointList.get(i).y - pointList.get(i+1).y <= 1)
g2d.drawLine(pointList.get(i).x, pointList.get(i).y, pointList.get(i+1).x, pointList.get(i+1).y);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
pointList.add(arg0.getPoint());
}
#Override
public void mouseReleased( MouseEvent arg0) {
pointList.add(arg0.getPoint());
repaint();
}
#Override
public void mouseDragged(MouseEvent arg0) {
pointList.add(arg0.getPoint());
repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
I was thinking maybe to keep track of the Points listened by the mousePressed and mouseReleased listeners in another arraylist,
Keep an ArrayList of ArrayLists.
So every time you do a mousePressed you start an new ArrayList for the series of Points to be added by the mouseDragged event.
Then in the painting code you iterate through the two ArrayLists. This should be easier than adding exception logic for the start/end points.
Another option is to do the drawing directly to a BufferedImage, so you don't need to keep track of the Points at all. Check out Custom Painting Approaches which compares these two general custom painting approaches to decide which approach is best for your requirment.

draw and save an image

I'm coding the simple project to draw lines and save likes an image,but when I run, it shows an errors that I can't fix. Please help me.
Here is my code:
package image;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class paint extends JFrame{
private Point points[] = new Point[10000];
private Point pointends[] = new Point[10000];
private int pointCount = 0;
private JButton save_btn;
public paint()
{
panel paint2 = new panel();
add(paint2,BorderLayout.CENTER);
}
private class panel extends JPanel
{
public panel()
{
setBackground(Color.WHITE);
save_btn = new JButton();
save_btn.setText("123");
this.add(save_btn);
/* save btnhandler = new save();
save_btn.addActionListener(btnhandler);*/
MouseHandler handler = new MouseHandler();
this.addMouseMotionListener(handler);
this.addMouseListener(handler);
}
#Override
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
for(int i = 0;i <pointCount;i++)
{
g.setColor(Color.RED);
g.drawLine(points[i].x, points[i].y, pointends[i].x, pointends[i].y);
}
}
}
private class MouseHandler extends MouseAdapter
{
#Override
public void mouseDragged(MouseEvent e)
{
// TODO Auto-generated method stub
pointends[ pointCount-1] = e.getPoint();
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
super.mousePressed(e);
//find point
if(pointCount < points.length)
{
points[ pointCount ] = e.getPoint();//find point
pointends[ pointCount ] = e.getPoint();
pointCount++;
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseReleased(e);
/*pointends[pointCount]=e.getPoint();
repaint();
pointCount++;
*/
}
}
}
and the class of save event
package image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
public class save implements ActionListener{
private paint paint1 = new paint();
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String str = JOptionPane.showInputDialog(null, "Enter file name: ");
//
BufferedImage bufImage = new BufferedImage(paint1.getWidth(), paint1.getHeight(),BufferedImage.TYPE_INT_RGB);
try {
ImageIO.write(bufImage, "jpg", new File(str + ".jpg"));
} catch (IOException ox) {
// TODO: handle exception
ox.printStackTrace();
}
}
}//end class
The Problem is that Your paint JFrame creates an instance of your save ActionListener, and your save ActionListener creates an instance of your paint JFrame. Thus you run into an infinite loop of constructors.
Instead of creating a new paint object, pass the current one in the constructor for save.
private paint paint1 = null;
public save(paint panel) {
this.paint1 = panel;
}
Now, in your panel constructor, pass a reference to the current instance to the ActionListener:
save btnhandler = new save(my_paint); // see Update below
save_btn.addActionListener(btnhandler);
This should fix your immediate problem. However, I recommend restructuring your code a bit, and you should also try to follow Java coding conventions, e.g., using CamelCase names for classes, and using correct indentation. This will make it much easier for others (and yourself) to read and undertand your code.
Update: I just realized that your object structure is a bit more complicated... your paint JFrame creates a panel JPanel, which creates a save ActionListener, which again creates a paint JFrame. The basic argument and solution remain the same, but instead of using new save(this) you have to either pass a reference to the JFrame containing the JPanel, or change the type of the field in your ActionListener.
Alternatively you could make bothe the JPanel and the ActionListener inner classes of the paint JFrame. This way you can access the JFrame directly from within the ActionListener and do not have to pass a reference at all, thus circumvent the problem entirely and giving a bit more structure to the code.

Mouse Pointer Problem in Java Swing

I have created the following simple Java Swing program which outputs a 3*3 square in the window every time the user clicks their mouse. The squares remain in the window even if the user clicks more than once. The program compiles and runs just fine, however, when one clicks in the window the square is drawn far below where the mouse pointer is. I've been racking my brain over this one for a while -- what can I change here to get the square to appear exactly with the pointer on each click? Many thanks for any help!
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class ClickCloud extends JComponent {
final ArrayList<Point2D> points = new ArrayList<Point2D>();
public void addPoint(Point2D a) {
points.add(a);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for (int i = 0; i < points.size(); i++) {
Point2D aPoint = points.get(i);
g2.draw(new Rectangle2D.Double(aPoint.getX(), aPoint.getY(), 3, 3));
}
}
public static void main(String[] args) {
final ClickCloud cloud = new ClickCloud();
JFrame aFrame = new JFrame();
class ClickListen implements MouseListener {
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
cloud.addPoint(arg0.getPoint());
cloud.repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setSize(500, 500);
aFrame.add(cloud);
aFrame.addMouseListener(new ClickListen());
aFrame.setVisible(true);
}
}
You're adding the MouseListener to the JFrame, but displaying the results in the JComponent and relative to the JComponent. So the location of the Point clicked will be relative to the JFrame's coordinates, but then displayed relative to the JComponent's coordinates which will shift things down by the distance of the title bar. Instead simply add the MouseListener to the same component that is responsible for displaying the results so that the display and clicking coordinates match:
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setSize(500, 500);
aFrame.add(cloud);
//!! aFrame.addMouseListener(new ClickListen()); // !! Removed
cloud.addMouseListener(new ClickListen()); // !! added
aFrame.setVisible(true);
By the way: Thanks for creating and posting a decent SSCCE as this makes it so much easier to analyse and solve your problem.

Categories