I'm trying to start a bit of 2d code and I have this much so far. It should just make a window appear but when I run it (in debug) I get an error saying source not found? Anyone see what I'm missing?
package game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT= WIDTH/12*9;
public static final int SCALE=3;
public static final String NAME = "My Game";
private JFrame frame;
public boolean running=false;
public Game()
{
setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this,BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocation(null);
frame.setVisible(true);
}
public synchronized void start()
{
running = true;
new Thread(this).start();
}
public synchronized void stop()
{
running =false;
}
public void run()
{
while(running)
{
System.out.println("Hello!");
}
}
public static void main(String[]args)
{
new Game().start();
}
}
I was working from a few tutorials to get this and I went through the code myself a few times but I cant spot whats wrong. :(
The problem is this line:
frame.setLocation(null);
The parameter provided to setLocation must not be null. If you do not need to set the location of the frame, don't call the method. By default, the frame is placed in the upper-left corner of the screen.
Related
I'm making a chess-like game in java and I'm having an issue with the click events. The mouseClicked function isn't responding to my clicks on the window and for no apparent reason.
I have already tried a few things such as changing class names and using different functions but nothing has worked.
package main.game.com;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ClickEvent extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
System.out.println("hello");
}
}
package main.game.com;
import java.awt.Canvas;
public class Main extends Canvas {
private static final long serialVersionUID = 1673528055664762143L;
private static final int WIDTH = 416, HEIGHT = 439;
public Main() {
Window window = new Window(WIDTH, HEIGHT, "DARRAGH", this);
this.addMouseListener(new ClickEvent());
}
package main.game.com;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Window extends Canvas {
private static final long serialVersionUID = 6733885629776844621L;
public Window(int width, int height, String title, Main main) {
JFrame frame = new JFrame(title);
frame.setPreferredSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(main);
frame.setVisible(true);
main.start();
}
}
The first set of code is my mouseAdapter library and the second is the first part of my main class containing the clickListener.
You're creating a Handler object, good, you're adding it to a Canvas object (the this -- why Canvas?), and you're creating a "top-level" window object which is in fact of Window type, but you never add the Canvas to the Window, nor do you appear to display the Window, so there is no reason to expect this code to in fact work.
Now, I'm guessing that there is more code out there that you're not showing us, and this may have relevance, and if so, do consider creating and posting an adequate MCVE for giving us the best understanding of your problem.
OK, I created a MCVE with your code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends Canvas {
private static final long serialVersionUID = 1673528055664762143L;
private static final int WIDTH = 416, HEIGHT = 439;
public Main() {
Procode238Window window = new Procode238Window(WIDTH, HEIGHT, "DARRAGH", this);
this.addMouseListener(new ClickEvent());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Main();
});
}
}
class ClickEvent extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
System.out.println("hello");
}
}
// renamed to avoid clashing with the java.awt.Window class
class Procode238Window extends Canvas {
private static final long serialVersionUID = 6733885629776844621L;
public Procode238Window(int width, int height, String title, Main main) {
JFrame frame = new JFrame(title);
frame.setPreferredSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(main);
frame.setVisible(true);
// !! main.start(); // this method doesn't exist
}
}
and it works
Note that:
This whole code can be copied and pasted into a single IDE file and run and has the necessary main method, both needed for it to be an MCVE
I've renamed the Window class to avoid a naming clash and confusing with the java.awt.Window class
Your code calls the Main class's .start() method, a method not shown. Could this be causing problems?
My program uses a Jframe, whenever I minimize the window and bring it back up, the program runs itself again. How can I cause it to not do this when minimized?
Code:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.util.Random;
public class AB extends Component {
public void paint(Graphics g) {
Random r = new Random();
g.setColor(Color.black);
g.fillRect(r.nextInt(100), r.nextInt(100), 100, 100);
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.getContentPane().setBackground(Color.white);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
f.setSize(dim.width, dim.height);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new AB());
f.setVisible(true);
}
}
My guess: you have program logic present in your paint(...) or paintComponent(...) method override. If so, get the logic out of these methods, because as you're finding out, you do not have full control over when or even if they are called. The logic belongs elsewhere, perhaps in a Swing Timer, hard to say without code or a more detailed question.
If this doesn't help, then you'll need to show us the bugs in your code by creating and posting a minimal, runnable, example program as well as tell us more of the details of your program and its misbehavior.
After looking at your code, I see that my assumption/guess was correct: you are selecting your random numbers inside of the paint method, and so they will change with each repaint. You will want to
Create a class that extends JPanel.
Create your random numbers in this class's constructor, and use the random numbers to set class instance fields.
Override this class's paintComponent method
Don't forget to call the super's paintComponent method inside this method.
Use the numbers generated in the constructor in the paintComponent method override to draw your rectangle.
Place your JPanel into a JFrame.
e.g.,
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class RandomRect extends JPanel {
private static final int MAX_INT = 100;
private static final Color RECT_COLOR = Color.black;
private Random random = new Random();
private int randomX;
private int randomY;
public RandomRect() {
randomX = random.nextInt(MAX_INT);
randomY = random.nextInt(MAX_INT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(RECT_COLOR);
g.fillRect(randomX, randomY, MAX_INT, MAX_INT);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("RandomRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RandomRect());
//frame.pack();
// frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I'm following a tutorial and made a JFrame, but it's very tiny. Iv'e searched for this problem on this site, but nothing has helped. Does anybody know the problem? I did it exactly like the tutorial, and it worked for him! I'll post a picture of it also.
Here is the code:
package net.trails.std;
import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.JFrame;
public class Core extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
private static JFrame frame;
public static double dY = 0, dX = 0;
public static final int res = 1;
public static int dir = 0;
public static boolean moving = false;
public static boolean run = false;
private Image screen;
public static Dimension screenSize = new Dimension(700, 560);
public static Dimension pixel = new Dimension(screenSize.width, screenSize.height);
public static Dimension size;
public static String name = "Trails";
public Core(){
}
public static void main(String[] args) {
Core core = new Core();
frame = new JFrame();
frame.add(core);
size = new Dimension(frame.getWidth(), frame.getHeight());
frame.setSize(700, 560);
frame.setTitle(name);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
core.start();
}
public void run() {
}
}
Get rid of the line with frame.pack().
This packs the frame in as small as possible while still fitting everything inside it. You have nothing inside it yet (since core is nothing).
You're calling frame.pack() with no sized components in your JFrame. This is going to squish the whole thing down to the tiny window you currently have.
Look at the docs for pack():
http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#pack()
Basically, you need to call setSize() in your Core class (which is an applet).
I must say I tried everything and I can't understand what's wrong with my code.
In my SIView class I create MainFrame which extends JFrame with specified resolution (let's say X,Y).
Then I create gamePanel which extends JPanel whith the same resolution as MainFrame, and add it to MainFrame. The problem is that effective resolution of the panel is twice as big (x*2, y*2). It's like the panel is being streched to be twice as big.
Frame will display only a quarter (upper left quarter) of the panel either with pack() or mannualy setting the size, unless I set it to double the resolution in which case It's ok, but that's not a proper way to do that(When calculating positions in the game I have to double everything or divide it by 2 to keep proper proportions). I even tried different Layout managers wthout any succes.
Here's the code of the main view class:
public class SIView implements Runnable {
private final MainFrame mainFrame;
private final GamePanel gamePanel;
public SIView(BlockingQueue<SIEvent> eventQueue) {
this.eventsQueue = eventQueue;
mainFrame = new MainFrame();
gamePanel = new GamePanel();
gamePanel.setVisible(true);
mainFrame.getContentPane().add(gamePanel);
// mainFrame.pack();
#Override
public void run() {
mainFrame.setVisible(true);
}
public void init() {
SwingUtilities.invokeLater(this);
}
//some code not related
}
the frame class:
public class MainFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 6513420589842315661L;
public MainFrame() {
setTitle("Space Intruders");
setSize(new Dimension(SIParams.RES_X, SIParams.RES_Y));
setResizable(false);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
panel class:
public class GamePanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 8112087715257989968L;
private final PlayerShipView playerShip;
private final ArrayList<SmallEnemyShipView> smallEnemyShip;
private final ArrayList<LightMissleView> lightMissle;
public GamePanel() {
setPreferredSize(new Dimension(SIParams.RES_X, SIParams.RES_Y));
setMaximumSize(new Dimension(SIParams.RES_X, SIParams.RES_Y));
setBounds(0, 0, SIParams.RES_X, SIParams.RES_Y);
setBackground(new Color(0, 0, 0));
setLayout(new OverlayLayout(this));
setDoubleBuffered(true);
// TODO
playerShip = new PlayerShipView();
smallEnemyShip = new ArrayList<SmallEnemyShipView>();
lightMissle = new ArrayList<LightMissleView>();
this.add(playerShip);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
//some code not related
}
If I use LayoutManager and properly override getPreferredSize() in GamePanel, the code seems to work as expected:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.jfree.ui.OverlayLayout;
public class SIView implements Runnable {
public static interface SIParams {
int RES_X = 500;
int RES_Y = 400;
}
public static class GamePanel extends JPanel {
public GamePanel() {
setBackground(new Color(0, 0, 0));
setLayout(new OverlayLayout());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SIParams.RES_X, SIParams.RES_Y);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
// some code not related
}
private JFrame mainFrame;
private GamePanel gamePanel;
#Override
public void run() {
mainFrame = createMainFrame();
gamePanel = new GamePanel();
mainFrame.getContentPane().add(gamePanel);
mainFrame.pack();
mainFrame.setVisible(true);
}
private JFrame createMainFrame() {
JFrame frame = new JFrame();
frame.setTitle("Space Intruders");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return frame;
}
public void init() {
SwingUtilities.invokeLater(this);
}
// some code not related
public static void main(String[] args) {
new SIView().init();
}
}
I also dropped the MainFrame class since it is not needed to extend JFrame in this context.
I just solved everything :D But I must say I feel stupid. The problem was with painting my components, in paintcomponent() method I painted rectangle on a relative position while changing component position also relatively. That gave the effect of 2xtimes movement etc. because while the component was moving the rectangle was moving inside of it too. I guess I have a lot to learn about Swing ;) Sorry for all this trouble ;)
PS. I didn't have to change anything in Panel/Frame classes except for using pack() method after everything.
I have this project that I need to publish, but don't know which way will be best. Can somebody help me please.
I have a Gui application(Jframe). In there I have a Jpanel that contains some animations (implement runnable). So in my main method I would call the constructor first, so everything display nicely, then called Runner.start(). (Thread)
So basically the gui pop up and then the animation happens, to be specific the animation is just the title of my program that slides in.
Now I want to put this on the website so my students can use.
I do not want to use java web start, i want this to act as an applet.
So do i put this jframe into my applet?
or should I convert this whole thing from jframe to japplet? and is this applet need to implement Runnable?
The thing that bug me is that Japplet has no main method, so how can I specified when my Jpanel can execute its animation? I want the animation to occur after everything has load up on the screen, not before.
I guess put it as the last statement of init() method? Correct me if I am wrong.
Thanks,
I have a Gui application(Jframe). .. I want to put this on the website so my students can use.
While it is possible to convert the frame to an applet, a better option is to launch the frame from a link using Java Web Start.
you can do both:
MainGui
import java.awt.BorderLayout;
import javax.swing.*;
public class MainGui extends JPanel {
public MainGui() {
this(null);
}
public MainGui(MyJApplet applet) {
this.applet = applet;
if (!isApplet()) {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} else
frame = null;
setLayout(new BorderLayout());
// setPreferredSize(new Dimension(640, 480));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainGui.this.run();
}
});
}
String title() {
return "Title";
}
public void addContent() {
add(new JLabel("add content! top"));
}
void run() {
if (isApplet()) addContent();
else {
frame.setTitle(title());
frame.getContentPane().add(this, BorderLayout.CENTER);
addContent();
frame.pack();
System.out.println(getSize());
frame.setVisible(true);
}
}
boolean isApplet() {
return applet != null;
}
public static void main(String[] args) {
new MainGui(null);
}
protected final JFrame frame;
protected final MyJApplet applet;
private static final long serialVersionUID = 1;
}
MyJApplet
import java.awt.BorderLayout;
import javax.swing.JApplet;
public class MyJApplet extends JApplet {
public void start() {
}
public void init() {
getContentPane().setLayout(new BorderLayout());
addContent();
}
public void addContent() {
getContentPane().add(new MainGui(this), BorderLayout.CENTER);
}
public static void main(String[] args) {
new MainGui(null);
}
private static final long serialVersionUID = 1;
}