How can I display text with Slick? - java

I have been trying to display text with ninjacave's tutorials and lot's of others but I can't get it to work.
Could someone give me a link to a tutorial that works?
Thanks.
The code is below:
Main Class:
package oregon.client;
import oregon.src.*;
import org.lwjgl.*;
import org.lwjgl.opengl.*;
import static org.lwjgl.opengl.GL11.*;
public class Oregon {
public static Settings settings = new Settings();
public GameController controls = new GameController();
public FPSCounter fps = new FPSCounter();
public void init() {
try {
if (settings.fullscreen) {
Display.setDisplayModeAndFullscreen(Display
.getDesktopDisplayMode());
} else if (!settings.fullscreen) {
Display.setDisplayModeAndFullscreen(new DisplayMode(
settings.defaultWidth, settings.defaultHeight));
}
Display.setVSyncEnabled(true);
Display.create();
} catch (LWJGLException e) {
stop(e);
}
initOpenGL();
start();
}
public void initOpenGL() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, settings.defaultWidth, settings.defaultHeight, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
}
public void debug() {
}
public void openGL() {
}
public void start() {
while (!Display.isCloseRequested()) {
controls.keyboard();
fps.tick();
debug();
openGL();
Display.update();
Display.sync(100);
}
Display.destroy();
}
public static void stop() {
System.exit(0);
Display.destroy();
}
public static void stop(Exception e) {
e.printStackTrace();
System.exit(0);
Display.destroy();
}
public static void setFullscreen() {
try {
Display.setDisplayModeAndFullscreen(Display.getDesktopDisplayMode());
} catch (LWJGLException e) {
stop(e);
}
}
public static void removeFullscreen() {
try {
Display.setDisplayModeAndFullscreen(new DisplayMode(
settings.defaultWidth, settings.defaultHeight));
} catch (LWJGLException e) {
stop(e);
}
}
public static void main(String args[]) {
Oregon oregon = new Oregon();
oregon.init();
}
}
That was the code for the main-class.
EDIT:- This is a picture of what I'm getting with Jesse B's code.

DavidB mentions in his answer using the graphics instance to drawString(). This will use your current font. This means you should call graphics.setFont() first, otherwise it will use the default system font. This also makes it hard to remember (in various methods of your game) which is the 'current' font.
Alternatively, you can initialize a font instance and use it directly to drawString. From Slick2D Wiki...
// initialise the font
Font font = new Font("Verdana", Font.BOLD, 20);
TrueTypeFont trueTypeFont = new TrueTypeFont(font, true);
// render some text to the screen
trueTypeFont.drawString(20.0f, 20.0f, "Slick displaying True Type Fonts", Color.green);
This requires that all supported platforms can resolve the font name. A better option is to embed the font in your JAR by placing it it your resources directory.
EDIT
After seeing the picture you posted, my guess is that you don't have the font loading correctly. Try this instead...
graphics.drawString("Test drawing string.",20.0f,20.0f);
If this works, it confirms the font isn't working. If you want to use custom fonts, you will have to add your font file into your JAR and reference it as a resource.

Download the Slick2D library and import the jar.
Inside your class to cover the scope of the whole class:
Font font;
TrueTypeFont ttf;
Your init method
public void init(GameContainer gc){
font = new Font("Verdana", Font.BOLD, 20);
ttf = new TrueTypeFont(font, true);
}
Your render method:
public void render(GameContainer gc, Graphics g){
//render code here
ttf.drawString("Hello, World!")
}

According to this tutorial, you can call drawString from your graphics object in the render method.
g.drawString("Hello World!",200,200);

Related

Graphics2D drawImage won't send correctly to printer

My issue is, i'm trying to print using Java and it seems to give a random result each time(Look at the pictures and you will understand). The first time I run it the Image prints fine, but the second time there is a black box covering half of the screen. Here is the First Run
and the Second run
Here is the code:
package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.ImageObserver;
import javax.swing.*;
import java.awt.print.*;
import java.net.URL;
public class HelloWorldPrinter implements Printable, ActionListener {
private Image ix = null;
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/*
* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
ix = getImage("Capture.JPG");
g.drawImage(ix, 1, 1, null);
return PAGE_EXISTS;
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}
}
public static void main(String args[]) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f = new JFrame("Hello World Printer");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JButton printButton = new JButton("Print Hello World");
printButton.addActionListener(new HelloWorldPrinter());
f.add("Center", printButton);
f.pack();
f.setVisible(true);
}
public Image getImage(String path) {
Image tempImage = null;
try {
URL imageURL = HelloWorldPrinter.class.getResource(path);
imageURL = HelloWorldPrinter.class.getResource(path);
tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
} catch (Exception e) {
System.out.println(e);
}
return tempImage;
}
}
Thanks for taking the time to read this and I hope you have a solution.
EDIT: I'm using Microsoft Print To PDF so I can view the print. I don't know if it's relevant but I would add it anyways.
MadProgrammer's solution worked.
Don't use Toolkit#getImage, this could using a thread to load the image an or caching the results in unexpected ways, consider using ImageIO.read instead, it will block until the image is fully realised. It's also possible that your getImage method is triggering an exception and is returning a blank image, but since you ignore the exception result, it's hard to know – MadProgrammer

How do I make this an 'interactive image' [JAVA]

I, basically, want to make an image a 'map'. Kind of like google maps, but with my own image. Here are a few of the issues I run into:
1.) Image is too large to fit into applet screen (Solution: click and drag to pan?)
2.) I have no clue how to make it so I can zoom in and out.
3.) I'd like to make it so when a person 'hovers' their mouse over a location, a text box shows up telling them about the area, but disappears when not 'hovering'
Here is my current code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class MapRender extends JApplet {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public MapRender() {
try {
img = ImageIO.read(new File("Mapv1Resize.PNG"));
} catch (IOException e) {
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new MapRender());
f.pack();
f.setVisible(true);
}
}
This code is part of a sample provided by another area, I just changed it to an applet.
Note: I understand whoever helps me can't run the program without the picture, but you can substitute any 2k*2k resolution picture for this.

Java Draw a GIF

I'm trying to draw a GIF using the Java Graphics API, but I'm not able to successfully draw a GIF using my below code. Only the first image or thumbnail of the GIF is drawn but it doesn't play.
public void paintComponent(Graphics g){
super.paintComponent(g);
BufferedImage img = null;
try {
URL url = new URL("GIF URL");
img = ImageIO.read(url);
} catch (Exception e) {
}
g.drawImage(img, 5, 5, this);
}
Essentially I am creating graphics for a login screen and I want to draw a GIF that loops.
EDIT: Updated my code and changed the question a bit.
You can load a gif into a BufferedImage object.
Then we paint the buffered image onto your swing component
Also one must better override the paintComponent method
It's perfectly possible to do this, you just need to have a proper way to load the frames for the image. The code I use to do this, is as so:
private static Image load(final String url) {
try {
final Toolkit tk = Toolkit.getDefaultToolkit();
final URL path = new URL(url); // Any URL would work here
final Image img = tk.createImage(path);
tk.prepareImage(img, -1, -1, null);
return img;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This uses the Toolkit to load a gif image, since ImageIO can't properly load gifs at this time, if I recall correctly.
From there, it's so simple as doing the following in a (for example) JPanel:
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g); // clear up render
//...
g.drawImage(IMAGE, x, y, this); // ImageObserver necessary here to update
//...
}
Example:
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class GifAnimation {
public GifAnimation(){
JFrame frame = new JFrame("Gif Animation");
GifPanel panel = new GifPanel(load("http://www.thisiscolossal.com/wp-content/uploads/2013/01/3.gif"));
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private static Image load(final String url) {
try {
final Toolkit tk = Toolkit.getDefaultToolkit();
final Image img = tk.createImage(new URL(url));
tk.prepareImage(img, -1, -1, null);
return img;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
public void run() {
new GifAnimation();
}
}
}
public class GifPanel extends JPanel {
private final Image image;
public GifPanel(Image image){
this.image = image;
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image, 10, 10, this);
}
#Override
public Dimension getPreferredSize(){
return new Dimension(660, 660);
}
}
}
GIF animation is not directly possible by using paint method of JPanel.
I would suggest inserting a JEditorPane in the panel whenever you want to display it and show GIF in it using HTML.
Refer showing images on jeditorpane (java swing)
Although some might criticize it as a crude way, the animation works perfectly.
Hope this helps.

Paint over applet loaded with classloader

I was wondering what would be the best/easiest way to render my own graphics over an applet that has been loaded with:
public class Game {
public static Applet applet = null;
public static URLClassLoader classLoader = null;
public static void load() {
try {
classLoader = new URLClassLoader(new URL[]{Jar.getJar().toURL()});
applet = (Applet) classLoader.loadClass("com.funkypool.client.PoolApplet").newInstance();
applet.setSize(new Dimension(800, 600));
applet.setBackground(Color.BLACK);
applet.setStub(new Stub());
applet.init();
applet.start();
JFrame loader = new JFrame("Loader");
loader.setPreferredSize(applet.getSize());
loader.add(applet);
loader.pack();
loader.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I would like it to render over the applet, but the applet still maintain all of its original functionality, I believe i would need to use reflection possibly? I was thinking about looking at the way Powerbot.org renders over the runescape client, as the client still maintains all its functionality etc.
If you have any questions or need to see more code, just ask.
Assuming this draws something (my applet-fu is rusty), then you can draw on top of it by placing it in a JFrame and subclassing the JFrames' void paint(Graphics g) so that it paints whatever it wants to, and then paints something else.
A modified JFrame that does this could be the following (warning: untested code):
public static class OverlayJFrame extends JFrame {
private JPanel overlay;
public OverlayJFrame(String title) { super(title); }
public void setOverlay(JPanel overlay) { this.overlay = overlay; }
public void paint(Graphics g) { super.paint(g); overlay.setSize(getSize()); overlay.paint(g)); }
}

Java LWJGL Slick UnicodeFont acting up

I'm having some problems displaying text on the screen, in the past I have just used sprite based text, however this time I want to use UnicodeFont. TrueTypeFonts draw perfectly however its deprecated.
When I try to draw the UnicodeFont it seems to be affected by the characters I use. for example If I draw the string "stackoverflow" the text and the box will draw, if I try "stackoverflowcom" the box will not draw.
A barebones version of my source code is below. On line ~74 I call uniFont.drawString(0, 0,"stackoverflow"); , if the com (or anything really) the box will not be drawn.
edit. > You can use the boolean tryUnicode to swap between true and unicode.
Ive tried sticking them in to seperate display lists but it made no difference.
Could anyone offer an insight in to why this is happening?
Thanks
import java.awt.Font;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import static org.lwjgl.opengl.GL11.*;
public class Game {
private UnicodeFont uniFont;
private TrueTypeFont truFont;
public static void main(String[] argv) {
Game game = new Game();
game.start();
}
public void start()
{
initGL(600, 600);
initFonts();
while(!Display.isCloseRequested()) //display not closed
{
render();
Display.update();
Display.sync(60);
}
Display.destroy();
System.exit(0);
}
private void render()
{
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(-0.25f,0.7f,0);
glScalef(0.001f,-0.001f,0.001f);
glEnable(GL_BLEND);
boolean tryUnicode = false;
if(tryUnicode)
{
uniFont.drawString(0, 0,"stackoverflow");
//EDIT.. glDisable texture is required here.
}else
{
glScalef(1.1f,1.1f,1f);
truFont.drawString(0, 0, "stackoverflow truFont");
}
glDisable(GL_BLEND);
glPopMatrix();
glPushMatrix();
glTranslatef(-0.25f,0,0);
glColor3f(0.5f, 0f, 0f);
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(0, 0,0.0f);
glVertex3f(0.5f, 0,0f);
glVertex3f(0f,0.5f,0f);
glVertex3f(0.5f, 0.5f,0f);
glEnd();
glPopMatrix();
}
private void initGL(int width, int height) {
try {
Display.setDisplayMode(new DisplayMode(width,height));
Display.create();
//Display.setVSyncEnabled(true);
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
glEnable(GL11.GL_TEXTURE_2D);
glShadeModel(GL11.GL_SMOOTH);
glEnable(GL11.GL_DEPTH_TEST);
glDisable(GL11.GL_LIGHTING);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1);
glEnable(GL_BLEND);
glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_BLEND);
glMatrixMode(GL11.GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
glMatrixMode(GL11.GL_MODELVIEW);
}
private void initFonts() {
Font awtFont = new Font("", Font.PLAIN,55);
truFont = new TrueTypeFont(awtFont, true);
uniFont = new UnicodeFont(awtFont, 128, false, false);
uniFont.addAsciiGlyphs();
uniFont.addGlyphs(400,600); // Setting the unicode Range
uniFont.getEffects().add(new ColorEffect(java.awt.Color.white));
try {
uniFont.loadGlyphs();
} catch (SlickException e) {};
}
}
It seems I have this error now, it will only draw the outlined rectangle before using the font. This seems to be a Slick error, and is a major problem so they should fix it before adding new features.
The only work-around is to render fonts last on your frame.
EDIT: Problem Solved!
add this line after you render your font:
GL11.glDisable(GL11.GL_TEXTURE_2D);
The Slick people should really add that line in as it causes so many bugs!
This is how I create fonts:
Font font = ...; //Your loaded font
float size = 20.0F;
UnicodeFont f = new UnicodeFont(font.deriveFont(0 /*normal*/, size));
f.addAsciiGlyphs();
ColorEffect e = new ColorEffect();
e.setColor(java.awt.Color.white);
f.getEffects().add(e);
try {
f.loadGlyphs();
} catch (SlickException e1) {
e1.printStackTrace();
}
return f;
Hope this helped!

Categories