nothing paints on JFrame - java

I am having some trouble with my code which is written in java. The first time after I start eclipse it launches and runs perfectly, but if I try to run it again - without making any changes - the only thing I see is an empty JFrame. Why might this happen? I have gotten quite a bit of files so to launch them all up here would be a lot to look through. Maybe you've tried something like this before? Where the program can launch sometimes? If not tell me so I can add the code.
I know that all of my classes are called since I have printed them all in my search to get the game to work.
The entire code worked until I started to put most of it in different objects in order to make it easier to look through.
package Pacman;
import java.util.Scanner;
import javax.swing.JFrame;
public class Frame extends JFrame{
public static int Width, Height;
public static void main(String[] args){
Scanner console = new Scanner(System.in);
Width = console.nextInt();
Height = console.nextInt();
new Frame();
}
public Frame(){
new JFrame();
this.setTitle("PacMan");
this.setLocation(400,300);
this.setResizable(false);
this.setVisible(true);
Screen screen = new Screen(this, Width, Height);
this.add(screen);
}
}
This is the JFrame, but I am pretty sure the problem isn't here.
If you want to see the entire codesystem it's at github: https://github.com/Lampeskaerm/SoftTek_Projekt.git
I hope you can help me
Anne-Katrine

After adding the component you should use this.setVisible(true) in the last.

Related

Embed PApplet intp JApplet

How can I embed a PApplet into a JApplet ?
I wanted to add it to a JPanel inside the applet, but I couldn't.
If any of you know how I can do this. ??
As of Processing 3, you can no longer do this. PApplet no longer extends Applet, so it can't be treated as a component.
For 95% of users, this is okay. Applets are dead anyway, so you really shouldn't be using them. If at all possible, you should try deploying with Processing.js.
If you need to execute a Processing sketch from Java code, then you should use the PApplet.main("YourSketchNameHere"); function to launch it. Processing will take care of the window for you.
If you really need to treat a PApplet as a component, then you're going to have to go through its PSurface. The PSurface class contains a getNative() function that returns an object that can be treated as a component. But that's overkill for most Processing users.
Prior to Processing 3, this code should have worked for you as #Kevin has explained. So, if your question is directed towards understanding a legacy code here is what you will need to know:
import javax.swing.JFrame;
import javax.swing.JPanel;
class MyPApplet extends PApplet implements ActionListener{
#Override
public void setup() {
super.setup();
// setup
}
#Override
public void draw() {
// my draw code
}
}
public class PAppletDemo {
public static void main(String[] args) {
final JFrame frame = new JFrame("PApplet in Java Application");
JPanel panel = new JPanel();
//create an instance of your processing applet
final MyPApplet applet = new MyPApplet();
applet.init();
panel.add(applet); // From processing 3, this will give you error that applet is not a Component
frame.add(panel);
frame.setSize(applet.getSize().width, applet.getSize().height +200);
frame.setVisible(true);
}
}
To circumvent this, you will need to use PSurface getNative() function. Please refer to the example and discussion given on this link.

Why isn't anything being drawn to my JPanel?

Since I'm new I can't post more than two links, but this is an x-post from reddit.com/r/learnprogramming, just for full disclosure.
I'll basically just be pasting what I said there to here. Thanks for your help, if you can help.
I'm writing somewhat of a graphing application. I currently only have it able to graph sin(x), but that's not the point of this question. I am not able to draw to my main panel. Here is what it currently looks like.
I had an overridden paint function in my Window.java class, which drew the sin(x) function and the axes, but when I made an inner class which extended JPanel(), it would no longer draw.
I then tried to make a separate file, but that didn't draw anything either.
What could be preventing it from drawing?
Here are all my files in question.
edit: code in question:
GraphDraw.java:
//import stuff
Public class GraphDraw extends JPanel {
SinX sinx = new SinX();
GraphPanel p = new GraphPanel();
#Override
public void paintComponent(Graphics gc) {
super.paintComponent(gc);
Graphics2D g = gc;
p.paintComponent(g);
sinx.paint(g);
}
}
And in Window.java, I initialize GraphDraw and add it to my main panel, which is underneath the buttons in the picture and above the x/y min/max labels.
GraphDraw drawer = new GraphDraw();
/*
GUI code
*/
mainPanel.add(drawer);
SinX.java
//import stuff
public class SinX extends Component {
public void paint(Graphics g) {
g.setColor(Color.red);
for(double x=-400;x<=400;x=x+0.5) {
double y = 50 * sin(x*((Math.PI)/180));
int Y = (int)y;
int X = (int)x;
g.drawLine(400+X,300-Y,400+X,300-Y);
}
}
}
First, before anything else, do the following:
Change you object from Component to JComponent
Do not ever, ever call paintComponent() or paint() on a graphics object from swing or awt, use object.repaint(); (For reasons I won't go into here, because it's long and complicated)
From there I would try calling setVisible(true); on all your objects. If you are getting this code from a tutorial, then stop and use a different tutorial. You need to learn how swing and the AWT library work before you can start making user interfaces. Nobody uses AWT anymore because Swing is much better. For reasons why, look at the following page. If you are too lazy to do that, its because it's more optimized and more powerful.
What is the difference between Swing and AWT?

Trying to run Program in Ecplise as a class × 259989

I am a newbie in the Java world and this is among my first programs (Hello World, obviously!). The problem is when I try to run this program as a class from the menu with a play icon on it, a blank window shows up with no "Hello World" on it (just white colour filling the window). At the bottom border of this window there is a black thick line. But when I run this program as an applet from the same menu everything is okay and the "Hello World" shows at the right position and everything is fine. But how can I make the program run regularly as a class???
This is my code...
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class HelloProgram extends GraphicsProgram {
private static final long serialVersionUID = 1L;
public void run() {
GLabel label = new GLabel("hello, world", 100, 75);
label.setFont("SansSerif-36");
label.setColor(Color.RED);
add(label);
}
}
I have no idea about acm, but looked in this page: http://jtf.acm.org/tutorial/Introduction.html
As you see there GraphicsProgram is a subclass of JApplet and because of that it's supposed to be run as applet, not desktop application.
Try this. It will be a separate class, but you will be able to run your program from this one. Please let me know if you are confused.
public class Runner{
public static void main(String[] args){
HelloProgram p = new HelloProgram();
p.run();
}
}
I agree with publ1c_stat1c, your program is missing the "main" method for it to be considered a standalone application.
Create an instance of your application
HelloProgram hello = new HelloProgram();
call the run method of the instance
hello.run();
the main method doesn't have to be in a different class, try adding below codes in-between "run method" and "private static final long serialVersionUID = 1L;"
public static void main(String[] args){
HelloProgram hello = new HelloProgram();
hello.run();
}

Different windows with the same code?

This is the "main" class (doesn't contain the main method)
import javax.swing.*;
import java.awt.*;
//import java.lang.Object;
//import java.awt.event.ActionListener;
//import java.awt.event.;
public class Program {
public JFrame frame;
public JPanel header;
public JPanel text;
public JPanel body;
public JTextField input;
public JButton agregar;
public List listA;
public List listB;
public Program(String title) {
frame = new JFrame(title);
frame.setSize(500,600);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
header = new JPanel();
header.setBackground(new Color(255,204,50));
header.setBounds(0,0,500,100);
text = new JPanel();
text.setBackground(new Color(255,204,100));
text.setBounds(0,100,500,50);
text.setLayout(null);
//Inicializando la "entrada"
input = new JTextField(20);
input.setBounds(50,13,300,25);
text.add(input);
agregar = new JButton();
agregar.setBounds(360,12,80,25);
agregar.setText("Agregar");
text.add(agregar);
//Listo
body = new JPanel();
body.setBackground(new Color(255,204,150));
body.setBounds(0,150,500,450);
//Lo que está dentro del body
listA = new List(20);
body.add(listA);
listB = new List(20);
body.add(listB);
//Listo
//Añadir todos los paneles al frame principal
frame.add(header);
frame.add(text);
frame.add(body);
}
}
And this is the MAIN class (This one contains the main method):
public class Main {
public static void main(String[] args) {
new Program("Ordenamiento Recursivo");
}
}
Each time I run the application, the UI components are presented differently, please see attached screen shot.
Well, thanks to everyone who responded the post, I finished the program and I'm very happy with the final result, here it is:
In case anyone wants to take a look at the code, here it is: Link
Problems:
You're call setVisible(true) on your JFrame before adding components and this will lead to unreliable drawing of your program's graphics and is why you are seeing different results. Don't do this, but rather call it after you've added all to the top-level Window.
As the others are saying, read up and learn to use the layout managers.
Different windows with the same code?
I think that is very simple and possible by implements CardLayout
I'd suggest don't opening a new Top-Level Container, only if is there really important reason then use JDialog or JOptionPane
Be sure to construct the GUI on the EDT. Not doing so can cause unpredictable results.
Call pack() after the components are added using layouts and then call setVisible(true).
You will need a layout manager for your form so setting the layout manager to null is not the thing to do.
Work in progress here ... https://gist.github.com/2510570
Couple of changes. Not quite finished yet, but check out the following
Have Program extend a JFrame.
Have set a layout manager.
Update
Finally I knocked this up in IntelliJ's form designer.
https://gist.github.com/2512197
Where you want to attach behaviour to the buttons search through the code for the comments that ask you to add code. Although I did this in the InteliJ Ultimate (this one that costs money) I think that no-cost free to download Community Edition UI designer also paints Swings GUIs. Very quick and easy. Netbeans also has a good GUI painter.
The Swing Tutorial on oracle.com is worth reviewing also.

Java For Loop Inside Constructor is Infinitely Repeating

So, for some reason when I try to use a for loop to initialize panels in chess board, it actually loops the loop itself. In other words, it doesn't go on forever, but it starts and completes again and again.
package chessgame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChessGame extends JFrame implements ActionListener{
public static final int WIDTH=800;
public static final int HEIGHT=800;
public static void main(String[] args) {
ChessGame gui = new ChessGame();
gui.setVisible(true);
}
public ChessGame(){
super("Chess Game Demo");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(8,8));
JPanel[] chessSquares = new JPanel[64];
for (int a=0;a<64;a++){
System.out.println(a);
}
}
}
I have included all potentially relevant code because I plan to use indices of chessSquares to color squares black and white. When I do this I also get a NullPointerException. I can understand why I'm getting that given the following error, but I cannot at all understand why a would be printed 0, 1....62, 63 over and over again. I am relatively new to Swing and have absolutely no idea why it does this. If anyone could explain that would be tremendously helpful. Thanks.
Don't put meaningful initialization in ChessGame's constructor, but instead override frameInit. When you do, also be sure to call super.frameInit(). See the javadoc or this tutorial.

Categories