Passing values to applets - java

I have a little problem with passing values from one class into another which extends the Applet class.
for eg. my From.java contains the following code:
public class From{
public static Graphics g;
String name = "Jack Black";
To drawString = new To(g,name);
}
and my To.java contains this:
public class To extends Applet {
To(Graphics g, String name){
g.setColor(Color.black);
g.drawString(name, 20, 20);
}
}
I've made an constructor to pass the values, but i understand that paint method draws the graphics into Applet and thats why my code doesn't work. So, sadly, i cant make it working, I hope you guys can help me out here.

Oh, Hi :)
I watched your code and... You can simply modify your code in this direction as...
A)
public class From{
private String name;
public From(){}
public void setName(String name){this.name=name;}
public String getName(){return this.name;}
}
B) Here is applet...
public class To extends Applet {
Paint paint=new Paint();
...
public void setFrom(From from)
{
paint.drawString(from.getName());
}
}
C) And some simplification...
public class Paint extends JPanel
{
private String name;
public Paint (){}
public void drawString(String name)
{
this.name=name;
this.repaint();
}
public void paintComponent(Graphics g)
{
g.setColor(Color.black);
g.drawString(this.name, 20, 20);
}
}
That should help :)
Good luck

Related

Why do I get an error (Nullpointerexception) when trying to clear Canvas?

I have a project, in which I should create a robot that moves between randomly created squares, till it sticks between two squares, or it reaches the end of the Canvas. For that I have a Super class Figur that has two subclass (Kreis) Circle and (Rechteck) Square, I have a Class Spielfeld(Gamefield) that has methods to populate an arraylist of figure, commands that user gives, of what robot should do, ...and at the end of this methods it calls the method zeichnen(draw) from Class Leinwand(Canvas).
public abstract class Figur{
///..some fields, constructions, methhods..
abstract public void zeichnen(Graphics g);
}
public class Rechteck extends Figur{
///..some fields, constructions, methhods..
public void zeichnen(Graphics g){
g.setColor(getFarbe());
g.drawRect(getPosition().getX(),getPosition().getY(),getBreite(),getLaenge());
g.fillRect(getPosition().getX(),getPosition().getY(),getBreite(),getLaenge());
}
public class Kreis extends Figur{
public void zeichnen(Graphics g){
g.setColor(getFarbe());
g.drawOval(getPosition().getX(),getPosition().getY(),getBreite(),getLaenge());
g.fillOval(getPosition().getX(),getPosition().getY(),getBreite(),getLaenge());
}
public class Spielfeld {
static ArrayList<Figur> myCharacters = new ArrayList<>();
//some methods that adds points(circles) and Squares to the arraylist MyCharacters
//some methods like movebetweensquares that calls method zeichnen in Leinwand
public class Leinwand{
public void zeichnen(ArrayList<Figur> figur){
loeschen();
zeichenflaeche.repaintFiguren(figur);
}
private void loeschen() {
Color original = graphic.getColor();
graphic.setColor(hintergrundfarbe);
Dimension size = zeichenflaeche.getSize();
graphic.fill(new Rectangle(0, 0, size.width, size.height));
graphic.setColor(original);
}
private class Zeichenflaeche extends JPanel {
private static final long serialVersionUID = 20060330L;
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int j=0; j<Spielfeld.get_ myCharacters ().size();j++){
Figur s= Spielfeld.get_ myCharacters ().get(j);
s.zeichnen(g);
}
}
public void repaintFiguren(ArrayList<Figur> figuren{
for( Figur f: Spielfeld.get_ myCharacters ()){
for(int i=0; i<Spielfeld.get_ myCharacters ().size();i++){
if(f instanceof Rechteck){
repaint(figuren.get(i).getPosition().getX(),
figuren.get(i).getPosition().getY(),
figuren.get(i).getBreite(),figuren.get(i).getLaenge()); }
else if(f instanceof Kreis){
repaint(figuren.get(i).getPosition().getX(),
figuren.get(i).getPosition().getY(),
figuren.get(i).getBreite(),
figuren.get(i).getLaenge());}
}
}
}
}

How can I let a class add onto my paint function?

I know that is poorly worded, but I don't know how to word it better. Essentially I have my own JComponent MyComponent and it paints some stuff onto its graphics. I want it to paint its stuff, then call a method to finish the paint, here is an example:
public class MyComponent extends JComponent{
// etc
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g2 = (Graphics2D)g;
g2.drawSomething(); // etc
// Once it is done, check if that function is exists, and call it.
if(secondaryPaint != null){
secondaryPaint(g2);
}
}
}
Then, in a different class:
// etc
MyComponent mc = new MyComponent()
mc.setSecondaryDrawFunction(paint);
// etc
private void paint(Graphics2D g2){
g2.drawSomething();
}
I'm not sure how lambdas work or if they are applicable in this situation, but maybe that?
No lambdas, but the Function interface will work
You can do :
public class MyComponent extends JComponent{
// etc
Function<Graphics2D, Void> secondaryPaint;
public MyComponent(Function<Graphics2D, Void> myfc){
secondaryPaint = myfc;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
//g2.drawSomething(); // etc
// Once it is done, check if that function is exists, and call it.
if(secondaryPaint != null){
secondaryPaint.apply(g2);
}
}
static class Something {
public static Void compute(Graphics2D g){
return null;
}
public Void computeNotStatic(Graphics2D g){
return null;
}
}
public static void main(String[] args) {
Something smth = new Something();
new MyComponent(Something::compute); // with static
new MyComponent(smth::computeNotStatic); // with non-static
}
}

How can I add a long text to my fillRect?

I'm working on a program that add pins to a map, the pins are are subclasses to a class that draws a triangle to the map and are clickable, and if you click it shall unfold and show different things like name, text or a picture.
I've one working subclass that creates a rectangle out of the triangle and shows what the name of the place is. For this I used the drawString. But now, to my second subclass, it shall show an description over the place, and the description could be quite long and for this I can't use the drawString, because it only shows on one row, and it will clip my text..
I tried to add the description to a JTextArea, and add that one to a JScrollPane and then I tried to add the scrollpane to the rect area, but that didn't seem to work, because "The method add(JScrollPane) is undefined for the type Graphics"
Here is my super class:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
abstract public class Place extends JComponent {
private String name;
private int x,y;
boolean highlighted = false;
boolean hidden = false;
boolean showed = false;
public Place(int x, int y, String name){
setBounds(x,y,30,30);
this.name=name;
this.x=x-15;
this.y=y-30;
Dimension d = new Dimension(30,30);
setPreferredSize(d);
setMaximumSize(d);
setMinimumSize(d);
addMouseListener(new MouseLis());
}
abstract protected void show(Graphics g);
protected void paintComponent(Graphics g){
super.paintComponent(g);
// g.setColor(Color.BLACK);
if(!showed){
setBounds(x,y,30,30);
int[] xes = {0,15,30};
int[] yes = {0,30,0};
g.fillPolygon(xes, yes, 3);
} else {
show(g);
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public String getName() {
return name;
}
class MouseLis extends MouseAdapter{
#Override
public void mouseClicked(MouseEvent mev){
showed = ! showed;
repaint();
}
}
}
and here is my subclass that doesn't work..
class DescPlace extends Place{
private String Description;
private JTextArea desc = new JTextArea(Description);
public DescPlace(int x, int y, String name, String descr){
super(x,y,name);
this.Description = descr;
}
protected void show(Graphics g){
setBounds(getX(), getY(),150,200);
g.setColor(Color.YELLOW);
g.fillRect(0, 0, 150, 200);
//g.add(new JScrollPane(desc));
}
}
You can use the same JTextArea and just paint it using Graphics instance
desc.setSize(width, height); //define size
desc.paintAll(g); //paint
You can use a JLabel to do this, using it to display HTML-formatted content.
From Oracle's docs:
If you want to mix fonts or colors within the text, or if you want formatting such as multiple lines, you can use HTML. HTML formatting can be used in all Swing buttons, menu items, labels, tool tips, and tabbed panes, as well as in components such as trees and tables that use labels to render text.
Source: https://docs.oracle.com/javase/tutorial/uiswing/components/html.html
EDIT
No time to write a thousand words, so here's an example:
new JLabel("<html><p>This will</p><br /><p>appear over multiple</p><br /><p>lines</p></html>")
The same applies to JToolTip if you go down that route.

paintComponent isn't painting anything?

I haven't been able to paint anything using an actionListener and paintComponent. I'm pretty sure I have the image name/path right. What am I doing wrong?
JApplet "Runner.java"
public class Runner extends JApplet{
public void init(){
World world = new World();
Container screen = this.getContentPane();
screen.add(world);
setSize(1200, 800);
repaint();
}
}
part of "World.java"
protected ArrayList<WorldObject> allStillObjects = new ArrayList<WorldObject>();
protected ArrayList<MovableObject> allMovableObjects = new ArrayList<MovableObject>();
protected ArrayList<WorldObject> screenStillObjects = new ArrayList<WorldObject>();
protected ArrayList<MovableObject> screenMovableObjects = new ArrayList<MovableObject>();
public World(){
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(new Color(255,255,255));
this.setFocusable(true);
this.setFocusTraversalKeysEnabled(false);
this.addObject(new Card(this, "Two of Clubs", 0, 0, "card_two_c.png"));
timer = new Timer(60, new ClickListener());
timer.start();
}
public void addObject(WorldObject obj){
if(obj instanceof MovableObject){
this.allMovableObjects.add((MovableObject)obj);
if(isOnScreen(obj))
this.screenMovableObjects.add((MovableObject)obj);
}else{
this.allStillObjects.add(obj);
if(isOnScreen(obj))
this.screenStillObjects.add(obj);
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for(WorldObject obj : this.screenStillObjects)
obj.paintComponent(g);
for(MovableObject obj : this.screenMovableObjects)
obj.paintComponent(g);
}
private class ClickListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
}
}
"ImageObject.java"
protected ImageIcon pic;
public ImageObject(World world, String name, int worldX, int worldY, String imageName){
super(world, name, worldX, worldY);
URL imgURL = getClass().getResource("images/" + imageName);
pic = new ImageIcon(imgURL);
this.width = pic.getIconWidth();
this.height = pic.getIconHeight();
}
public void paintComponent(Graphics g){
super.paintComponent(); //doesn't work with or without this line
pic.paintIcon(world, g, this.getWorldX(), this.getWorldY());
}
If there isn't enough of the code here I can add more
Edit: What's the best alternative to using a JApplet? World extends JPanel, WorldObject extends JPanel, ImageObject extends WorldObject, MovableObject extends ImageObject, Card extends MovableObject
I added the method for addObject above.
Well thank you for your answers, er, comments! They were very helpful. I went and changed my program so that it used a JFrame instead of a JApplet, and after a little fiddling, got an image to print. From there I was able to revert back to a JApplet and it works! Still not sure what my initial problem was though :|

I have a somewhat (read: EXTREMELY) broken hitwall function and I don't see what I am doing wrong

Alright, now I am working on a small derp-ish game based on Brownian motion, and I am working on a hit-wall function for the particles, but it isn't working. Basically, I am expressing the direction of the particles in radians, and whenever it hits a wall, I add Pi radians to the direction to flip it, but for some reason, it either isn't getting called or not working. These are the peices of code I have, any suggestions are welcome.
import java.awt.*;
public class Particle implements Actor {
protected double xPos;
protected double yPos;
protected Velocity v;
protected Color hue;
protected boolean needsUpdate;
public Particle(){
this((Math.random()*500),(Math.random()*500),new Velocity((int)(Math.random()*500),(Math.random()*Velocity.TAU)));
}
public Particle(double x, double y, Velocity vel){
xPos=x;
yPos=y;
v=vel;
hue=Color.red;
needsUpdate=false;
}
public void draw(Graphics g) {
g.setColor(hue);
g.fillOval((int)xPos, (int)yPos, 16, 16);
}
public void act() {
xPos+=v.getSlopefromDirection();
yPos+=1;
}
public void onHitWall(int dir) {
v.setDirection((v.getDirection()+Math.PI)%(Math.PI*2));
}
public void onHitOther(Actor other) {
}
public boolean canCollide() {
return true;
}
public int getLeftX() {
return (int)xPos;
}
public int getRightX() {
return (int)xPos+4;
}
public int getTopY() {
return (int)yPos;
}
public int getBottomY() {
return (int)yPos+4;
}
}
And this is the class I am using to display it:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import static java.lang.System.out;
public class Feild extends JFrame{
protected ArrayList<Actor> actors;
private final int size=500;
protected Thread th;
public Feild(ArrayList<Actor> a){
super("A Brownian Love Story");
setSize(size, size);
actors=a;
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
th = new Thread();
while(true){
paint(getGraphics());
}
}
public void paint(Graphics g){
super.paint(g);
//g.fillRect(0, 0, 500, 500);
for(int i=0;i<actors.size();i++){
if(actors.get(i).getLeftX()<=0)
actors.get(i).onHitWall(1);
if(actors.get(i).getRightX()>=500)
actors.get(i).onHitWall(2);
if(actors.get(i).getTopY()<=0)
actors.get(i).onHitWall(1);
if(actors.get(i).getBottomY()>=500)
actors.get(i).onHitWall(2);
actors.get(i).act();
actors.get(i).draw(g);
}
for(int i=0;i<1000;i++){out.println(i);}
}
}
So i tried changing the paint function to checking for collisions after acting, and it still looks like onHitWall is getting skipped over, even though after putting in a print statement it isn't.
The problem you have is that your particles will move until they hit a wall, and then the next time you go through the look, they will still be in the wall, turn around again, and continue going into the wall.
If you check for collisions after your act() function this should solve the problem.
They will go into the wall, see they are in the wall, and turn around. The next loop, they will move back out of the wall, and continue on.

Categories