I'm new to Java and as such I've been doing my own small projects to help my learning. The code below when run will launch a new window where I changed the colour background which is correct, but the text doesn't appear and I don't understand why as there are no error messages.
In trying to fix this I tried it as an applet instead of a frame but that failed to work due to an error with a missing class. My guess is I'm missing something here but I don't know what.
Any help appreciated
import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
public class Fonts extends Frame
{
public void paint(Graphics g)
{
setBackground(Color.blue);
g.setColor(Color.white);
Font quote = new Font("TimesRoman", Font.PLAIN, 30);
g.setFont(quote);
g.drawString("Hello World ", 10, 10);
}
public static void main (String args[])
{
Frame ff = new Fonts();
ff.resize(500,500);
ff.show();
}
}
Related
first I want to apologize for any mistakes, I'm not speaking english well, I'm new to Java and I'm new to Stackoverflow. Please be kind!
I keep failing to draw a simple image to screen. I tried everything, but I keep failing and I'm getting more and more confused. Here's my Sourcecode:
package com.Animation;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.awt.Graphics2D;
import java.awt.Point;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Class1 extends JFrame{
private BufferedImage backgroundImg;
public Class1(){
this.setTitle("Animation");
this.setSize(1080, 720);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
LoadContent();
}
public static void main(String[] args){
new Class1();
}
private void LoadContent()
{
try
{
URL backgroundImgUrl = this.getClass().getResource("Back.jpg");
backgroundImg = ImageIO.read(backgroundImgUrl);
}
catch (IOException ex) {
System.err.println("Fehler!");
}
}
public void Draw(Graphics2D g2d)
{
g2d.drawImage(backgroundImg, 0, 0, null);
}
}
So what happens is, that a JFrame window opens with nothing to see on it. I think that's beacuse the Draw() method doesn't get called. But when I add like "Draw(g2d);" somewhere, I keep getting a NullPointerException. The picture "Back.jpg" is located in the same package as the class. I'm using eClipse and the JRE JavaSE 1.7.
I really hope you can help me, im totally exhausted by all my tries to figure out what's the problem. It would be cool if you could write the correct code into the answers and explain what I've done wrong. Remember, I'm new to all this.
Thanks a lot!
There are a lot of ways to do that. Examples
1) JLabel. //Not recommended
Add the JLabel in your JFrame, then do label.setIcon(backgroundImg);
2) JPanel
Override the paint() method in JPanel(make sure you've added it to your JFrame).
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(backgroundImg, 0, 0, this);
}
Try this. Here I have set the image to a JPanel instead of directly setting it to JFrame.
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
/**
*
* #author Rumesh
*/
public class Test extends JFrame{
public static void main(String[] args) throws IOException {
JFrame frame = buildFrame();
final BufferedImage image = ImageIO.read(new File("1.jpg"));
JPanel pane = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
frame.add(pane);
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}
I don't know if this is what you're searching for:
ImageIcon image = new ImageIcon("src/media/Image.jpg");
JLabel lblImg = new JLabel("", image, JLabel.CENTER);
lblImg.setBounds(..., ..., ..., ...);
add(lblImg);
This way you'll add an image to a JLabel and than place it on the screen. I hope it helps in some way.
I have a quite simple question about laying out components in Java AWT program here.
What I want to achieve is, to set the background of the application to a specified image (from file systenm) and add a button on the UI.
What I have is
package javaapplication2;
import java.awt.*;
import java.awt.Container;
import java.awt.Color;
import java.awt.Font;
import java.awt.Button;
import java.util.HashSet;
public class JavaApplication2 extends Frame {
private Container gui;
private Button b;
public JavaApplication2() {
setSize(400,400); // set size to 400x400
gui = new Container() { // my own container that may write string (or draw image in the future)
public void paint(Graphics g) {
super.paint(g);
g.setFont(new Font(null, Font.PLAIN, 48));
g.setColor(new Color(10,10,10));
g.fillRect(20, 20, getWidth()-40, getHeight()-40);
g.setColor(new Color(24, 89, 245));
g.drawString("hello", 200,200);
}
};
// create a button
b = new Button("bu");
// add the button into the container?
gui.add(b);
b.setVisible(true);
// add gui into the root container
add(gui);
gui.setSize(400, 400);
//gui.setVisible(true);
validate();
}
public static void main(String[] args) {
// TODO code application logic heren
JavaApplication2 a = new JavaApplication2();
a.setVisible(true);
}
}
Then when I ran it, all I could see is black background (color(10,10,10)) and text "hello". I guess that's because although b is added into the container, the paint is called so the whole container is painted so I can't see the button.
I guess there should be some simple solution and hope someone can help me with it.
I am following the examples from Java : The complete reference 8th edition (JDK 7) on AWT and I cannot succeed to display a string on the window that appears. The size and title are set correctly and the window shows up. If I output a string on the console in the paint() method I see that it actually gets called a few times but the string does not appear on the window of my application. I can't see where I diverged from the example; I actually have a bit less code (they added a mouse listener and a key listener) :\
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Main {
public static void main(String[] args) {
Application app = new Application();
app.setSize(new Dimension(640, 480));
app.setTitle("This is a test");
app.setVisible(true);
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
class Application extends Frame {
public Application() {
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g) {
System.out.println("Hey hey !");
g.drawString("Test", 10, 10);
}
}
The problem you're having is the fact that you are painting directly on top of the frame. The frame also includes the frame border, so position 0, 0 (or in your case 10, 10) is actually hidden UNDER the frame border.
You can see more about that here.
Instead, you should draw onto a Canvas and add that to the frame
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class BadFrame {
public static void main(String[] args) {
new BadFrame();
}
public BadFrame() {
Application app = new Application();
app.setSize(new Dimension(640, 480));
app.setTitle("This is a test");
app.setLayout(new BorderLayout());
app.add(new MyCanvas());
app.setVisible(true);
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
public class MyCanvas extends Component {
#Override
public void paint(Graphics g) {
super.paint(g);
System.out.println("Hey hey !");
g.drawString("Test", 10, 10);
}
}
class Application extends Frame {
public Application() {
addWindowListener(new MyWindowAdapter());
}
}
}
The next question that comes to mind is, why AWT? The API has being moth balled in favor of Swing. If nothing else, it's automatically double buffered ;)
ps- You may also find 2D Graphics of some interest, especially the discussion on text
Your string gets drawn but is hidden under the title bar of the window. Just use e.g.
g.drawString("Test", 10, 200);
and you'll see it appear
I'm trying to make some shapes filled with colors. The shapes doesn't show up!
Somebody Help Please!
I have two classes "menu.java" and "draw.java"
Here is my code for the "menu.java"
import javax.swing.JFrame;
public class menu {
public static void main(String[] args) {
JFrame JF = new JFrame("Menu Bar");
JF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
draw DR = new draw();
JF.add(DR);
JF.setSize(500,300);
JF.setVisible(true);
JF.setLocationRelativeTo(null);
}
}
The code for "draw.java"
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class draw extends JPanel{
public void painComponent(Graphics GPHCS){
super.paintComponent(GPHCS);
this.setBackground(Color.WHITE);
GPHCS.setColor(Color.BLUE);
GPHCS.fillRect(25,25,100,30);
GPHCS.setColor(Color.GRAY);
GPHCS.fillRect(25,65,100,30);
GPHCS.setColor(new Color(190,81,215));
GPHCS.drawString("This is my text", 25, 120);
}
}
Here is a screenshot after running the program
Why does the shapes not showing up?!
Any answers would be appreciated. Thanks
The method is called paintComponent, not painComponent. So the method paintComponent does not get overridden as intended.
Use #Override tag before method to get notified of errors like these.
I'm trying to create a SWING application using Java 1.6 and I have a JLabel that uses a custom font from a .ttf file.
I thought 1.6 had anti-aliasing on by default, but my text is pretty pixelized.
Here's a code sample and an image showing the result:
package aceprobowler.test;
import java.awt.Color;
import java.awt.Font;
import java.io.InputStream;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import aceprobowler.options.OptionsValues;
public class TestAntialiasedText extends JFrame
{
private static final long serialVersionUID = 2411330284507353990L;
public TestAntialiasedText(String title)
{
super(title);
setSize(800,200);
Font titleFont = null;
try
{
InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
titleFont = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.PLAIN, 60);
}
catch (Exception ex)
{
ex.printStackTrace();
System.err.println("font not loaded. Using serif font.");
titleFont = new Font("serif", Font.PLAIN, 24);
}
JPanel panelWithText = new JPanel();
JLabel labelWithText = new JLabel("This is a test");
labelWithText.setFont(titleFont);
labelWithText.setBackground(Color.BLACK);
labelWithText.setForeground(Color.WHITE);
labelWithText.setOpaque(true);
panelWithText.add(labelWithText);
add(panelWithText);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TestAntialiasedText("Testing text anti-alias").setVisible(true);
}
});
}
}
Mostly apparent on the "T"s and on the "A"
I tried creating an inner class overriding paintComponent(Graphics g) and using
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
But it doesn't work. Can anyone help me out with this? I can't find any information on the internet about this since Javaj 1.6 is supposed to make everything SWING related Anti-aliased by default.
Thanks in advance!
When you override the paintComponent method of the JLabel instance, I believe that you'll need to use the following:
Graphics.drawString(String str, int x, int y)
RenderingHints.KEY_TEXT_ANTIALIASING
For an example, see:
RichJLabel
I believe that the default for font anti-aliasing varies by platform. You don't say what platform you are on. In any case, setting the text antialiasing rendering hint should fix it.
Another approach is to use TextLayout and supply a FontRenderContext that isAntiAliased, as shown here.