How to use ScreenViewport properly with an AWT Canvas in LibGdx? - java

I'm making a Swing application using LibGdx as a backend for the map editor part. I use a LwjglApplication and pass a java.awt.Canvas to it.
I use a ScreenViewport to make the area being resize as the window is resized, but it does not work. The graphics is interpolated with a bad aspect ratio.
public class MapEditorCanvas extends JPanel implements ApplicationListener
{
/**
*
*/
private static final long serialVersionUID = 5383413314123855231L;
/**
*
*/
private Canvas _canvas;
/**
*
*/
public MapEditorCanvas()
{
super(new BorderLayout());
_canvas = new Canvas();
add(_canvas,BorderLayout.CENTER);
LwjglApplication app = new LwjglApplication(this, _canvas);
}
/**
*
*/
private SpriteBatch batch;
/**
*
*/
private Sprite sprite;
/**
*
*/
private Viewport viewport;
/**
*
*/
private OrthographicCamera _camera;
#Override
public void create()
{
_camera = new OrthographicCamera();
_camera.setToOrtho(true);
_camera.update();
viewport = new ScreenViewport(_camera);
batch = new SpriteBatch();
batch.setProjectionMatrix(_camera.combined);
sprite = new Sprite(new Texture(Gdx.files.internal("project/assets/graphics/wheel.png")));
repaint();
}
#Override
public void render()
{
GL11.glClearColor(0, 0, 0, 1);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
batch.begin();
viewport.apply();
sprite.draw(batch);
batch.end();
}
//
// Some others methods
//
/**
*
*/
#Override
public void resize(int width, int height){
viewport.setScreenSize(width, height);
viewport.update(width, height, false);
_camera.setToOrtho(true,width,height);
_camera.update();
}
}
Is there something wrong with my code ?
Bonus question : the LibGdx application is not drawn until the component is resized, someone knows why ?
Thanks in advance

Related

How to render a GLUT shape in a internal panel?

I created a simple GUI using swing in Netbeans. The idea is user chooses a shape, enters dimensions, clicks the button to render a GLUT shape in the internal panel (in green) on the GUI. I'm stuck at trying to get the shapes to render on the inner panel.
What is a good method or example to draw or render shapes onto an internal panel or canvas of a GUI?
GUI layout for reference:
Update:
Shape Class
package swing_tests;
import static com.sun.javafx.fxml.expression.Expression.add;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.*;
import com.jogamp.opengl.util.gl2.GLUT;
/**
*
* #author Charlie
*/
public class Shape extends GLJPanel {
/**
* #param args the command line arguments
*/
// fields
int width;
int height;
int length;
String name;
//Constructor
public Shape (int w, int h, int l, String n){
width = w;
height = h;
length = l;
name = n;
}
private final GLUT glut = new GLUT();
// Methods
public void JOGLShapes() {
GLCapabilities caps = new GLCapabilities(null);
GLJPanel display = new GLJPanel(caps);
display.setPreferredSize( new Dimension (50,50));
display.setVisible(true);
display.setBackground(Color.red);
add(display, BorderLayout.CENTER);
}
/////////////////////////////////////
public void display(GLAutoDrawable drawable) {
GL2 gl2 = drawable.getGL().getGL2(); // The object that contains all the OpenGL methods.
gl2.glClear( GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT );
gl2.glLoadIdentity(); // Set up modelview transform.
glut.glutSolidTeapot(2);
}
public void init(GLAutoDrawable drawable) {
// called when the panel is created
GL2 gl = drawable.getGL().getGL2();
gl.glClearColor(0.3F, 0.3F, 0.3F, 1.0F); // TODO: Set background color
gl.glEnable(GL2.GL_DEPTH_TEST); // TODO: Required for 3D drawing, not usually for 2D.
}
public void getArea () {
System.out.println("Area is " + width * height);
}
public void getVolume(){
System.out.println("Volume is "+ width * height * length);
}
public String getName(){
return name;
}
/// Setters
public void setWidth(int newWidth){
width = newWidth;
}
public void setHeight(int newHeight){
height = newHeight;
}
public void setDepth(int newLength){
length = newLength;
}
}

How to make a 'texture' jump up and return to starting position android java libgdx

So I am just trying to make my game character, which is a texture (ball), to jump up in the air and then return back down to the position that it started at when the screen is pressed. I was just wondering if someone could give me a code example or help me to do this with my current code which is below. I have basically just drawn the background and the ball texture and positioned the ball where I want it to start the jump. The ball texture is what I want to make jump straight up.
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture ball;
#Override
public void create () {
batch = new SpriteBatch();
background = new Texture("gamebackground.png");
ball = new Texture("ball2.png");
ball.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
}
#Override
public void render () {
batch.begin();
float scaleFactor = 2.0f;
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(ball, 80, 145, ball.getWidth() * scaleFactor, ball.getHeight() * scaleFactor);
batch.end();
}
#Override
public void dispose () {}
}
There are a million ways to do this.
Here's a simple (and not very flexible way). Create a Ball class that has variables for x and y position, velocity, and acceleration. Then give it an update method for applying the acceleration and velocity to the position:
public class Ball {
public static final float GRAVITY = -100; // size depends on your world scale
public static final float BOUNCE_DAMPENING = 0.6f;
public final Vector2 position = new Vector2();
public final Vector2 velocity = new Vector2();
public final Vector2 acceleration = new Vector2(0, GRAVITY);
public void update (){
float dt = Gdx.graphics.getDeltaTime();
velocity.add(acceleration.x * dt, acceleration.y * dt));
position.add(velocity.x * dt, velocity.y * dt);
if (position.y <= 0){ // hit ground, so bounce
position.y = -position.y * BOUNCE_DAMPENING;
velocity.y = -velocity.y * BOUNCE_DAMPENING;
}
}
}
This is a very rudimentary way of handling physics. It would be more sophisticated to use Box2D, but the above is fine if you're just learning.
Now, you need to create a ball instance and use it to track your ball position. Use the Ball object's position when drawing it. And you can react to taps to apply a velocity.
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture ballTexture;
Ball ball;
#Override
public void create () {
batch = new SpriteBatch();
background = new Texture("gamebackground.png");
ballTexture = new Texture("ball2.png");
ballTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
ball = new Ball();
}
#Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // don't forget to clear screen
if (Gdx.input.justTouched())
ball.velocity.y += 100;
ball.update();
batch.begin();
float scaleFactor = 2.0f;
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(ballTexture, ball.position.x, ball.position.y, ballTexture.getWidth() * scaleFactor, ballTexture.getHeight() * scaleFactor);
batch.end();
}
#Override
public void dispose () {
batch.dispose();
background.dispose();
ballTexture.dispose();
}
}
You also need to read up on pixel units vs. world units and how to solve the scale problem with Viewports. See https://xoppa.github.io/blog/pixels/ and https://github.com/libgdx/libgdx/wiki/Viewports

Drawing a Line with MouseAdapter Not Showing Java

Found this sample code which should produce a drawn line after clicking, but does not show anything or works. Assume all import statements are correct, code gives no errors and I have no idea why it would not work. The line color is red while the background is white so it should show clearly if it works. The mouse listener seems to be correct as well. Any reason why this code will not work?
public class PathPanel extends JPanel {
/**
* The panel width.
*/
public static final int WIDTH = 400;
/**
* The panel height.
*/
public static final int HEIGHT = 400;
/**
* The background color of the panel.
*/
public static final Color BACKGROUND_COLOR = Color.WHITE;
/**
* The color to paint with.
*/
public static final Color FOREGROUND_COLOR = Color.RED;
/**
* The line width.
*/
public static final int LINE_WIDTH = 8;
// Instance Fields
/**
*
*/
private static final long serialVersionUID = -3644129903653409515L;
/**
* The path being created.
*/
private final Path2D myPath;
// OR you could use Path2D.Double instead of GeneralPath
// Constructor
/**
* Constructs a new general path panel.
*/
public PathPanel() {
super();
myPath = new GeneralPath();
myPath.setWindingRule(GeneralPath.WIND_EVEN_ODD);
//myPath = new Path2D.Double();
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(BACKGROUND_COLOR);
addMouseListener(new MyMouseListener());
}
/**
* Paints the current path.
*
* #param theGraphics The graphics context to use for painting.
*/
#Override
public void paintComponent(final Graphics theGraphics) {
super.paintComponent(theGraphics);
final Graphics2D g2d = (Graphics2D) theGraphics;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(FOREGROUND_COLOR);
g2d.setStroke(new BasicStroke(LINE_WIDTH));
g2d.draw(myPath);
}
// Main Method
/**
* Creates and displays a GeneralPathPanel.
*
* #param theArgs Command line arguments (ignored).
*/
public static void main(final String... theArgs) {
final PathPanel panel = new PathPanel();
final JFrame frame = new JFrame("GeneralPathPanel Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// Inner Class
/**
* Listens for mouse clicks, to draw on our panel.
*/
private class MyMouseListener extends MouseAdapter {
/**
* Handles a click event.
*
* #param theEvent The event.
*/
#Override
public void mouseClicked(final MouseEvent theEvent) {
if (myPath.getCurrentPoint() == null) {
myPath.moveTo(theEvent.getX(), theEvent.getY());
} else if (theEvent.getClickCount() == 2) {
myPath.closePath();
} else {
myPath.lineTo(theEvent.getX(), theEvent.getY());
}
repaint();
}
}
}
The Sample Code you posted works fine for me. Have you tried to add a System.out.println() in the mouseClicked(final MouseEvent theEvent) Method to check if it is actually called? If it is not called, you could try to change it to mouseReleased.
The imports I used:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.GeneralPath;
import java.awt.geom.Path2D;

LIBGDX/BOX2D: Re-sizing Touchpad is not working when the Table.setBounds is called

public class PlayScreen implements Screen {
private final float PPM = 100f;
private final float GAME_WORLD_WIDTH = 1920;
private final float GAME_WORLD_HEIGHT = 1080;
private OrthographicCamera cam;
private Viewport viewport;
private Stage uiControls;
private TextureAtlas uiAtlas;
private Skin uiSkin;
private Table uiTable;
private Touchpad leftTouchPad;
private World world;
private Box2DDebugRenderer renderer;
private Body ship;
private SpriteBatch batch;
#Override
public void show() {
batch = new SpriteBatch();
world = new World(new Vector2(0,0), true);
renderer = new Box2DDebugRenderer();
//////////////////////////////////////////////////////////////////////////////
//*************************SET UP CAMERA/VIEWPORT***************************//
//////////////////////////////////////////////////////////////////////////////
float aspectRatio = (float)Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth();
cam = new OrthographicCamera(GAME_WORLD_WIDTH / PPM ,GAME_WORLD_HEIGHT / PPM);
cam.position.set(0,0,0);
viewport = new ExtendViewport( (GAME_WORLD_WIDTH * aspectRatio) / PPM, (GAME_WORLD_HEIGHT)/PPM, cam);
viewport.apply();
////////////////////////////////////////////////////////////////////
// ****************** SET UP STAGE AND ADD UI ******************* //
////////////////////////////////////////////////////////////////////
uiControls = new Stage(viewport);
uiAtlas = new TextureAtlas(Gdx.files.internal("ui/playScreen/playUI.pack"));
uiSkin = new Skin(uiAtlas);
uiTable = new Table(uiSkin);
uiTable.setBounds(-(GAME_WORLD_WIDTH / PPM) / 2, -(GAME_WORLD_HEIGHT / PPM) / 2, GAME_WORLD_WIDTH / PPM, GAME_WORLD_HEIGHT / PPM);
////////////////////////////////
// ** UI CONTROLS AND VIEW ** //
////////////////////////////////
//*** CONTROL PAD ***//
TouchpadStyle positionControlStyle = new TouchpadStyle();
positionControlStyle.knob = uiSkin.getDrawable("knob");
positionControlStyle.background = uiSkin.getDrawable("background");
leftTouchPad = new Touchpad(1, positionControlStyle);
////////////////////////
// ** ADD TO STAGE ** //
////////////////////////
uiTable.top();
uiTable.add(leftTouchPad);
uiControls.addActor(uiTable);
///////////////////////////////////////////////////////////////////
// ************************* SET UP WORLD ********************** //
///////////////////////////////////////////////////////////////////
BodyDef testDef = new BodyDef();
testDef.type = BodyDef.BodyType.DynamicBody;
testDef.linearDamping = 2f;
testDef.position.set(0, 0);
PolygonShape shape = new PolygonShape();
shape.setAsBox(1,1);
FixtureDef def = new FixtureDef();
def.shape = shape;
ship = world.createBody(testDef);
ship.createFixture(def);
///////////////////////////////////////////////////////
// **************** SET UP SPRITES ***************** //
///////////////////////////////////////////////////////
Gdx.input.setInputProcessor(uiControls);
}
#Override
public void render(float delta) {
Gdx.gl20.glClearColor(0, 0, 0, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
ship.applyForceToCenter(5 * leftTouchPad.getKnobPercentX(), 5 * leftTouchPad.getKnobPercentY(), true);
cam.update();
world.step(1 / 30f, 8, 3);
renderer.render(world, cam.combined);
batch.begin();
batch.end();
uiTable.act(delta);
uiTable.debug();
uiControls.draw();
}
#Override
public void resize(int width, int height) {
viewport.update(width,height);
cam.position.set(0, 0, 0);
uiControls.getViewport().update(width,height,false);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
So, here is what's happening. I added the touchpad to the table, but it seems to be way off of where it's supposed to be, and much larger than normal. The debug drawing indicates that the stage and table are definitely in the correct position.
I've tried to call touchpad.setBouds(), and touchpad.setSize(), but neither of them worked.
Is the stage perhaps the issue?
When you put any Actor into a Table, calling setBounds or setSize on it will no longer work because the Table is now managing the bounds of the Actor and will keep overwriting your direct changes to the Actor's bounds. You instead can control its size through the Table Cell that it is in.
When you call table.add(), a Cell is returned, and that is where you can adjust the cell size and how the Actor in the cell should be handled within the cell. For example:
uiTable.add(leftTouchPad).width(300).height(300).fill();
will make the cell 300 x 300, and the fill call tells it to scale the Actor in it to the same dimensions as the cell.
Also, you should not be calling uiTable.act but instead call uiControls.act.

Canvas shows content only by minimizing and resizing the window

im using the Canvas class to make a screensaver as a schoolproject.
But the window generated by Canvas doesnt show my objects on it (current time)
until i minimize it an resize it again. After that all things works fine.
so what is wrong?
thank you for coming answers!
with kind regards
leon
those are the classes, i peronally think that the problem is in the class Start or BufferedCanvas
import java.awt.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Start
{
int fensterX = 900;
int fensterY = 700;
Farbengenerator fg = new Farbengenerator();
BufferedCanvas c =newBufferedCanvas("Bild",fensterX,fensterY);
Zeit z = new Zeit();
SchriftParameter sp = new SchriftParameter();
public void zeichneText(){
double x = 100;
double y = 100;
double fy =0.01;
double fx =0.02;
int red=0;
int green=0;
int blue=0;
double colourGrowRate=0.05;
String uhr;
c.setFont(sp.setzteSchrift());
c.setForegroundColour(Color.BLACK);
c.setBackgroundColour(Color.WHITE);
for(int i=0;i<100;i++){
c.drawString("Starting...",(int)x,(int)y);
c.updateAndShow();
try{Thread.sleep(50);}
catch(Exception e){};
c.updateAndShow();
}
CreateButton d = new CreateButton();
d.run();
while(true) {
c.erase();
uhr = z.erstelleZeit();
c.drawString(uhr,(int)x,(int)y);
if((int)x >fensterX-93 || (int)x <5){
fx = fx * (-1);
red=fg.gibROT();
green=fg.gibGRUEN();
blue=fg.gibBLAU();
Color colour = new Color(red,green,blue);
c.setForegroundColour(colour);
}
if((int)y > fensterY-1 || (int)y < 46){
fy = fy * (-1);
red=fg.gibROT();
green=fg.gibGRUEN();
blue=fg.gibBLAU();
Color colour = new Color(red,green,blue);
c.setForegroundColour(colour);
}
if((int)colourGrowRate>=1){
fg.generiereFarbe();
colourGrowRate = 0.05;
}
colourGrowRate=colourGrowRate+colourGrowRate;
x = x + fx;
y = y + fy;
c.updateAndShow();
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
public class BufferedCanvas
{
private JFrame frame;
private CanvasPane canvas;
private Graphics2D graphic;
private Color backgroundColour;
private Image canvasImage;
BufferStrategy buff;
/**
* Create a BufferedCanvas with default height,
width and background colour
* (300, 300, white).
* #param title title to appear in Canvas Frame
*/
public BufferedCanvas(String title)
{
this(title, 300, 300, Color.white);
}
/**
* Create a BufferedCanvas with default background colour (white).
* #param title title to appear in Canvas Frame
* #param width the desired width for the canvas
* #param height the desired height for the canvas
*/
public BufferedCanvas(String title, int width, int height)
{
this(title, width, height, Color.white);
}
/**
* Create a BufferedCanvas.
* #param title title to appear in Canvas Frame
* #param width the desired width for the canvas
* #param height the desired height for the canvas
* #param bgClour the desired background colour of the canvas
*/
public BufferedCanvas(String title, int width, int height, Color bgColour)
{
frame = new JFrame();
canvas = new CanvasPane();
frame.setContentPane(canvas);
frame.setTitle(title);
canvas.setPreferredSize(new Dimension(width, height));
backgroundColour = bgColour;
frame.pack();
frame.createBufferStrategy(2);
buff = frame.getBufferStrategy();
graphic = (Graphics2D)buff.getDrawGraphics();
setVisible(true);
}
/**
* Set the canvas visibility and brings canvas to the front of screen
* when made visible. This method can also be used to bring an already
* visible canvas to the front of other windows.
* #param visible boolean value representing the desired visibility of
* the canvas (true or false)
*/
public void setVisible(boolean visible)
{
if(graphic == null) {
// first time: instantiate the offscreen image and fill it with
// the background colour
Dimension size = canvas.getSize();
canvasImage = canvas.createImage(size.width, size.height);
graphic = (Graphics2D)canvasImage.getGraphics();
graphic.setColor(backgroundColour);
graphic.fillRect(0, 0, size.width, size.height);
graphic.setColor(Color.black);
}
frame.setVisible(true);
}
/**
* Update the canvas and show the new image.
*/
public void updateAndShow(){
buff.show();
}
/**
* Provide information on visibility of the Canvas.
* #return true if canvas is visible, false otherwise
*/
public boolean isVisible()
{
return frame.isVisible();
}
/**
* Draw a given shape onto the canvas.
* #param shape the shape object to be drawn on the canvas
*/
public void draw(Shape shape)
{
graphic.draw(shape);
//canvas.repaint();
}
/**
* Fill the internal dimensions of a given shape with the current
* foreground colour of the canvas.
* #param shape the shape object to be filled
*/
public void fill(Shape shape)
{
graphic.fill(shape);
//canvas.repaint();
}
/**
* Erase the whole canvas.
*/
public void erase()
{
Color original = graphic.getColor();
graphic.setColor(backgroundColour);
Dimension size = canvas.getSize();
graphic.fill(new Rectangle(0, 0, size.width, size.height));
graphic.setColor(original);
//canvas.repaint();
}
/**
* Erase a given shape's interior on the screen.
* #param shape the shape object to be erased
*/
public void erase(Shape shape)
{
Color original = graphic.getColor();
graphic.setColor(backgroundColour);
graphic.fill(shape); // erase by filling background colour
graphic.setColor(original);
//canvas.repaint();
}
/**
* Erases a given shape's outline on the screen.
* #param shape the shape object to be erased
*/
public void eraseOutline(Shape shape)
{
Color original = graphic.getColor();
graphic.setColor(backgroundColour);
graphic.draw(shape); // erase by drawing background colour
graphic.setColor(original);
//canvas.repaint();
}
/**
* Draws an image onto the canvas.
* #param image the Image object to be displayed
* #param x x co-ordinate for Image placement
* #param y y co-ordinate for Image placement
* #return returns boolean value representing whether the image was
* completely loaded
*/
public boolean drawImage(Image image, int x, int y)
{
boolean result = graphic.drawImage(image, x, y, null);
//canvas.repaint();
return result;
}
/**
* Draws a String on the Canvas.
* #param text the String to be displayed
* #param x x co-ordinate for text placement
* #param y y co-ordinate for text placement
*/
public void drawString(String text, int x, int y)
{
graphic.drawString(text, x, y);
//canvas.repaint();
}
/**
* Erases a String on the Canvas.
* #param text the String to be displayed
* #param x x co-ordinate for text placement
* #param y y co-ordinate for text placement
*/
public void eraseString(String text, int x, int y)
{
Color original = graphic.getColor();
graphic.setColor(backgroundColour);
graphic.drawString(text, x, y);
graphic.setColor(original);
//canvas.repaint();
}
/**
* Draws a line on the Canvas.
* #param x1 x co-ordinate of start of line
* #param y1 y co-ordinate of start of line
* #param x2 x co-ordinate of end of line
* #param y2 y co-ordinate of end of line
*/
public void drawLine(int x1, int y1, int x2, int y2)
{
graphic.drawLine(x1, y1, x2, y2);
//canvas.repaint();
}
/**
* Draws a dot/pixel on the Canvas.
* #param x x co-ordinate of dot
* #param y y co-ordinate of dot
*/
public void drawDot(int x, int y)
{
graphic.drawLine(x, y, x, y);
//canvas.repaint();
}
/**
* Sets the foreground colour of the Canvas.
* #param newColour the new colour for the foreground of the Canvas
*/
public void setForegroundColour(Color newColour)
{
graphic.setColor(newColour);
}
/**
* Returns the current colour of the foreground.
* #return the colour of the foreground of the Canvas
*/
public Color getForegroundColour()
{
return graphic.getColor();
}
/**
* Sets the background colour of the Canvas.
* #param newColour the new colour for the background of the Canvas
*/
public void setBackgroundColour(Color newColour)
{
backgroundColour = newColour;
graphic.setBackground(newColour);
}
/**
* Returns the current colour of the background
* #return the colour of the background of the Canvas
*/
public Color getBackgroundColour()
{
return backgroundColour;
}
/**
* changes the current Font used on the Canvas
* #param newFont new font to be used for String output
*/
public void setFont(Font newFont)
{
graphic.setFont(newFont);
}
/**
* Returns the current font of the canvas.
* #return the font currently in use
**/
public Font getFont()
{
return graphic.getFont();
}
/**
* Sets the size of the canvas.
* #param width new width
* #param height new height
*/
public void setSize(int width, int height)
{
canvas.setPreferredSize(new Dimension(width, height));
Image oldImage = canvasImage;
canvasImage = canvas.createImage(width, height);
graphic = (Graphics2D)canvasImage.getGraphics();
graphic.drawImage(oldImage, 0, 0, null);
frame.pack();
}
/**
* Returns the size of the canvas.
* #return The current dimension of the canvas
*/
public Dimension getSize()
{
return canvas.getSize();
}
/**
* Waits for a specified number of milliseconds before finishing.
* This provides an easy way to specify a small delay which can be
* used when producing animations.
* #param milliseconds the number
*/
public void wait(int milliseconds)
{
try
{
Thread.sleep(milliseconds);
}
catch (Exception e)
{
// ignoring exception at the moment
}
}
/************************************************************************
* Nested class CanvasPane - the actual canvas component contained in the
* Canvas frame. This is essentially a JPanel with added capability to
* refresh the image drawn on it.
*/
private class CanvasPane extends JPanel
{
public void paint(Graphics g)
{
g.drawImage(canvasImage, 0, 0, null);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class CreateButton extends JFrame implements ActionListener{
public void run() {
createAndShowGUI();
}
public CreateButton() {
// set layout for the frame
this.getContentPane().setLayout(new FlowLayout());
JButton button1 = new JButton();
button1.setText("closeApp");
//set actionlisteners for the buttons
button1.addActionListener(this);
// define a custom short action command for the button
button1.setActionCommand("closeApp");
// add buttons to frame
add(button1);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new CreateButton();
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
if (action.equals("closeApp")) {
System.exit(1);
}
}
}
import java.awt.*;
public class SchriftParameter
{
public Font setzteSchrift(){
Font f = new Font("Fixed",1,24);
return (f);
}
}
public class Farbengenerator
{
int r=0;
int g=0;
int b=0;
public void generiereFarbe(){
if (r<255&&g==0&&b==0){
r++;
}
else if (r==255&&g<255&&b==0){
g++;
}
else if (r>0&&g==255&&b==0){
r= r-1;
}
else if (r==0&&g==255&&b<255){
b++;
}
else if (r==0&&g>0&&b==255){
g=g-1;
}
else if (r<255&&g==0&&b==255){
r++;
}
else if (r==255&&g==0&&b>0){
b=b-1;
}
}
public int gibROT () {
return(r);
}
public int gibGRUEN () {
return(g);
}
public int gibBLAU () {
return(b);
}
}
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Zeit
{
public String erstelleZeit(){
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date d = new Date();
String uhr = df.format(d);
return (uhr);
}
}

Categories