Centering a String on a custom component - java

So I have a custom JComponent (An almost completed button, if you will). Here is the source code to the class:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LukeButton extends JComponent implements MouseListener{
//ArrayList of listeners
private final ArrayList<ActionListener> listeners = new ArrayList<ActionListener>();
Shape rec = new RoundRectangle2D.Float(10, 10, 110, 60, 50, 75);
BasicStroke border = new BasicStroke(5);
SpringLayout layout = new SpringLayout();
private String text;
public LukeButton(String text){
this.text = text;
this.setLayout(layout);
this.addMouseListener(this);
}
//Adds a listeners to the list
public void addActionListener(ActionListener e){
listeners.add(e);
}
//Called when button is provoked
public void fireActionListeners(){
if(!listeners.isEmpty()){
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "LukeButton");
for(ActionListener l: listeners){
l.actionPerformed(evt);
}
}
}
//Listens for click on my component
public void mousePressed(MouseEvent e){
if(rec.contains(e.getPoint())){
rec = new RoundRectangle2D.Float(10, 10, 100, 55, 50, 75);
repaint();
fireActionListeners();
}
}
public void mouseReleased(MouseEvent e){
if(rec.contains(e.getPoint())){
rec = new RoundRectangle2D.Float(10, 10, 110, 60, 50, 75);
repaint();
}
}
//When mouse enters, make border bigger
public void mouseEntered(MouseEvent e){
border = new BasicStroke(8);
repaint();
}
//When mouse leaves, make border smaller
public void mouseExited(MouseEvent e){
border = new BasicStroke(5);
repaint();
}
public Dimension getPreferredSize(){
return new Dimension(130, 80);
}
//Draws my button
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLACK);
g2.setStroke(border);
g2.draw(rec);
g2.setColor(new Color(0, 204, 204));
g2.fill(rec);
g2.setColor(Color.BLACK);
g2.drawString(text, 47, 45);
}
//Methods that must be over written.
public void mouseClicked(MouseEvent e){
}
}
My problem is that I do not know how to center the text variable (More or less what the variable consists of) based on the size of the String. The beggining of the String is always in a fixed point. For example if the text variable is equal to something short, the string is going to be far on the left. But if the string is too long, it goes far off the right side of the component. Does anyone know how to center my text variable so it changes it's position based on the size of the string(or a different/better solution of coarse)? Thanks for taking your time to read :)

You can get the Rectangle required to paint the text by using:
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D rect = fm.getStringBounds(text, g2d);
Then to center the text you would get the x/y positions using something like:
int x = (getSize().width - rect.width) / 2;
int y = ((getSize().height - rect.height / 2) + rect.height;

Related

How Can This Stickman Be Made to Be Interactive?

So, I need to make the stick-man movable by a user-input. When the user clicks on a part (Head, hands, feet and posterior) and he should move, and have no idea how to go about this..
If possible, there also needs to be a confine around the character, likely rectangular, so that there is a limit to how far each part can be pulled.
See below for my code;
// Created by Charlie Carr - (28/11/17 - /11/17)
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
//Imports complete
//Suppress warning about undeclared static final serialVersionUID field in VS Code
#SuppressWarnings("serial")
public class Animator extends JPanel {
public static class AnimatorWindow extends JPanel {
public void paint(Graphics page) {
setBackground(Color.gray);
setForeground(Color.white);
super.paintComponent(page);
page.drawString("Stickmen Animation Station", 150, 15);
//draw the head
//x1, y1, x2, y2
page.drawOval(90, 60, 20, 20);
// draw the body
page.drawLine(100, 80, 100, 110);
// draw the hands
page.drawLine(100, 90, 80, 105);
page.drawLine(100, 90, 120, 105);
//draw the legs, he hasn't a leg to stand on..
page.drawLine(100, 110, 85, 135);
page.drawLine(100, 110, 115, 135);
}
}
public static void main(String[] args) {
AnimatorWindow displayPanel = new AnimatorWindow();
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
//declare window size
int x = 480;
int y = 240;
JFrame window = new JFrame("GUI");
window.setContentPane(content);
window.setSize(x, y);
window.setLocation(101, 101);
window.setVisible(true);
}
}
Use MouseListenerto deal with mouse events.
Also, you should override the paintComponent() method instead of paint(), because paint() also paints the border and other stuff.
public static class AnimatorWindow extends JPanel implements MouseListener{
public AnimatorWindow(){
setBackground(Color.gray);
setForeground(Color.white);
//add the listener
addMouseListener(this);
}
public void paintComponent(Graphics page) {
super.paintComponent(page);
//You should not alter the Graphics object passed in
Graphics2D g = (Graphics2D) page.create();
//draw your stuff with g
g.drawString("Stickmen Animation Station", 150, 15);
.......
//finish
g.dispose();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){
//implement your clicking here
//Use e.getX() and e.getY() to get the click position
}
}
For more on swing events, check this site
EDIT: Your problem also includes animation, and you can use a javax.swing.Timer to do that.

Transparent JFrame doesn't clear on repaint

When I try to repaint a transparent window, and draw a rectangle on it, the previous rectangle will stay. The goal is to select an area on your screen by clicking and moving your mouse. It'll look like this if you move your mouse for a while
By removing the transparency it works just fine.
I tried everything I could find on Stack Overflow about this topic, But I wasn't able to get it working on both Windows and Linux.
Main class
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class Main {
private JFrame frame;
private boolean pressing = false;
private boolean selected = false;
private ScreenSelectPanel p;
public Main() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("ScreenSelection");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(dim);
frame.setUndecorated(true);
frame.setContentPane(p = new ScreenSelectPanel());
registerListeners();
frame.getContentPane().setBackground(new Color(255, 255, 255, 0));
frame.setBackground(new Color(255, 255, 255, 0));
frame.setLayout(new BorderLayout());
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
private void registerListeners() {
p.setFocusable(true);
p.requestFocusInWindow();
p.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (selected)
return;
setLoc(e);
p.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
if (selected)
return;
setLoc(e);
if (!pressing)
setStartLoc(e);
p.repaint();
}
});
p.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
setLoc(e);
setStartLoc(e);
p.repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
setLoc(e);
setStartLoc(e);
p.repaint();
}
});
}
public void setStartLoc(MouseEvent e) {
p.mouseStartX = e.getX();
p.mouseStartY = e.getY();
}
public void setLoc(MouseEvent e) {
p.mouseX = e.getX();
p.mouseY = e.getY();
}
public static void main(String[] args) {
new Main();
}
}
ScreenSelectPanel class
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
public class ScreenSelectPanel extends JPanel {
public int mouseX = 0;
public int mouseY = 0;
public int mouseStartX = 0;
public int mouseStartY = 0;
private Color borderColor;
public ScreenSelectPanel() {
setOpaque(false);
borderColor = Color.BLACK;
}
public void setBorderColor(Color c) {
this.borderColor = c;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(borderColor);
Rectangle rect = new Rectangle();
rect.setFrameFromDiagonal(new Point2D.Float(mouseStartX, mouseStartY), new Point2D.Float(mouseX, mouseY));
Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);
g2d.setStroke(dashed);
g2d.drawRect(rect.x, rect.y, rect.width, rect.height);
g2d.dispose();
}
}
Thanks :)
You can't use transparency with Swing components. A transparent background causes these types of painting problems. A Swing component is either opaque or non-opaque.
Check out Backgrounds With Transparency for more information on this problem. However in this cause it is not the problem because you are trying to use full transparency on the Swing panel.
When I try to repaint a transparent window, and draw a rectangle on it, the previous rectangle will stay.
The code you posted does anything (at least on Windows). When you set a frame to be completely transparent then the MouseEvents are no longer handled by Swing and instead are handled by the application below the frame.
I made the following changes to your code and it seems to work for me:
//frame.getContentPane().setBackground(new Color(255, 255, 255, 0));
//frame.setBackground(new Color(255, 255, 255, 0));
frame.setBackground(new Color(255, 255, 255, 10));

Jbutton issues within my code

i have been working on a flashing beacon on java using Jpanel, paint component and timers, however i am having trouble trying to get the buttons within the code to function. when the code is run, the flash button is supposed to prompt the beacon to start blinking/flashing whereas the steady button keeps it on the same colour. the alternating colours for the beacon are orange and grey.As well as this i cant seem to get rid of a button that keeps appearing in the top left of the window when the code is run. so far, this is what i have
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
/**
* Created by Enoch on 26/03/2015.
*/
class BelishaBeacon extends JPanel {
Color startLight, stopLight, color;
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(color);
Ellipse2D firstOval = new Ellipse2D.Double(130, 70, 50, 50);
g2.draw(firstOval);
g2.fill(firstOval);
g2.setColor(Color.BLACK);
Rectangle rect1 = new Rectangle(150, 119, 10, 35);
g2.draw(rect1);
g2.fill(rect1);
g2.setColor(Color.WHITE);
Rectangle rect2 = new Rectangle(150, 150, 10, 35);
g2.draw(rect2);
g2.fill(rect2);
g2.setColor(Color.BLACK);
Rectangle rect3 = new Rectangle(150, 180, 10, 35);
g2.draw(rect3);
g2.fill(rect3);
g2.setColor(Color.WHITE);
Rectangle rect4 = new Rectangle(150, 210, 10, 35);
g2.draw(rect4);
g2.fill(rect4);
g2.setColor(Color.BLACK);
Rectangle rect5 = new Rectangle(150, 240, 10, 35);
g2.draw(rect5);
g2.fill(rect5);
g2.setColor(Color.WHITE);
Rectangle rect6 = new Rectangle(150, 270, 10, 35);
g2.draw(rect6);
g2.fill(rect6);
g2.setColor(Color.BLACK);
Rectangle rect7 = new Rectangle(150, 300, 10, 35);
g2.draw(rect7);
g2.fill(rect7);
g2.setColor(Color.WHITE);
Rectangle rect8 = new Rectangle(150, 330, 10, 35);
g2.draw(rect8);
g2.fill(rect8);
g2.setColor(Color.BLACK);
Rectangle rect9 = new Rectangle(150, 360, 10, 35);
g2.draw(rect9);
g2.fill(rect9);
g2.setColor(Color.WHITE);
Rectangle rect10 = new Rectangle(150, 390, 10, 35);
g2.draw(rect10);
g2.fill(rect10);
}
public BelishaBeacon() {
startLight = Color.ORANGE;
stopLight = Color.LIGHT_GRAY;
color = startLight;
new Blinker(this);
setBackground(Color.white);
}
public void blink()
{
color = (color == startLight ? stopLight : startLight);
repaint();
}
}
//
class Blinker
{
BelishaBeacon blinkPanel;
public Blinker(BelishaBeacon bp)
{
blinkPanel = bp;
new Timer(500, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
blinkPanel.blink();
}
}).start();
}
}
//
class BelishaBeaconViewer extends JFrame {
JButton jbtFlash = new JButton("Flash");
JButton jbtSteady = new JButton("Steady");
JPanel bPanel = new JPanel();
BelishaBeacon bBPanel = new BelishaBeacon();
public BelishaBeaconViewer() {
bPanel.add(jbtFlash);
this.add(bPanel, BorderLayout.SOUTH);
bPanel.add(jbtSteady);
this.add(bBPanel, BorderLayout.CENTER);
jbtFlash.addActionListener(new FlashListener());
jbtSteady.addActionListener(new SteadyListener());
}
class FlashListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
}
}
class SteadyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
}
}
public static void main(String[] args) {
JFrame bBFrame = new BelishaBeaconViewer();
bBFrame.setTitle("Belisha Beacon");
bBFrame.setSize(300, 300);
bBFrame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
bBFrame.setVisible(true);
}
}
i cant seem to get rid of a button that keeps appearing in the top left of the window
//super.paintComponents(g); // typo
super.paintComponent(g); // should be
Don't start the Timer automatically.
The FlashListener should start the Timer, no need for the repaint
The SteadyListner should stop the Timer, no need for the repaint.

Java window doesn't repaint properly until I resize the window manually

I am using a quite basic setup with a class extending JPanel, which I add to a JFrame.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
public class PinTestMCVE extends JPanel implements ActionListener{
BufferedImage loadedImage;
JButton calcButton;
public static void main(String[] args) {
new PinTestMCVE();
}
public PinTestMCVE() {
loadedImage = getTestImage();
JPanel toolbarPanel = new JPanel();
calcButton = new JButton("calcButton...");
toolbarPanel.add(calcButton);
calcButton.addActionListener(this);
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(toolbarPanel, BorderLayout.NORTH);
jf.getContentPane().add(this, BorderLayout.CENTER);
jf.setSize(1250, 950);
jf.setVisible(true);
}
public void paintComponent(Graphics g) {
g.drawImage(loadedImage, 0, 0, this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent " + e.getActionCommand());
if(e.getSource().equals(calcButton)){
this.repaint();
}
}
//Please ignore the inner workings of this
public static BufferedImage getTestImage(){
BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setPaint(Color.GRAY);
g2d.fillRect ( 0, 0, image.getWidth(), image.getHeight() );
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(Color.gray);
int x = 5;
int y = 7;
GradientPaint redtowhite = new GradientPaint(x, y, Color.red, 200, y, Color.blue);
g2d.setPaint(redtowhite);
g2d.fill(new RoundRectangle2D.Double(x, y, 200, 200, 10, 10));
return image;
}
}
What happens is that INITIALLY the window is painted properly, but once paintComponent is called, a strip of the old image (with the same height as the toolbar panel) is visible below the newly painted images - similar to playing card sticking out from a deck. But then, if I manually resize the window by for instance dragging the border, the background is grayed out as it should.
What is going on and how do I fix this?
As outlined here, you need to pack() the frame before calling setVisible(). You can override getPreferredSize() to specify a suitable initial Dimension. Also consider using a Border. See also Initial Threads.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.*;
public class PinTestMCVE extends JPanel implements ActionListener{
private static final int SIZE = 200;
BufferedImage loadedImage;
JButton calcButton;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new PinTestMCVE();
}
});
}
public PinTestMCVE() {
loadedImage = getTestImage();
JPanel toolbarPanel = new JPanel();
calcButton = new JButton("calcButton...");
toolbarPanel.add(calcButton);
calcButton.addActionListener(this);
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(toolbarPanel, BorderLayout.NORTH);
jf.add(this, BorderLayout.CENTER);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(loadedImage, 0, 0, this);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent " + e.getActionCommand());
if(e.getSource().equals(calcButton)){
this.repaint();
}
}
//Please ignore the inner workings of this
public static BufferedImage getTestImage(){
BufferedImage image = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setPaint(Color.GRAY);
g2d.fillRect ( 0, 0, image.getWidth(), image.getHeight() );
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(Color.gray);
GradientPaint redtowhite = new GradientPaint(5, 5, Color.red, SIZE, 5, Color.blue);
g2d.setPaint(redtowhite);
g2d.fill(new RoundRectangle2D.Double(5, 5, SIZE - 10, SIZE - 10, 10, 10));
return image;
}
}

Images not showing up on the screen at the right moment - Java

I am working on an applet, I don't have experience with this..
I want to paint two objects, insert an image and change the background color to black. If I don't change the color, everything works just fine, the problem came when I decided to change the background color as well.
What I get is a black screen without the drawings and picture. If I minimize or re-size the window, then I get everything.
Below is my code, a simplify version.
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class JAlienHunt extends JApplet implements ActionListener {
private JButton button = new JButton();
JLabel greeting = new JLabel("Welcome to Alien Hunt Game!");
JLabel gameOverMessage = new JLabel(" ");
JPanel displayPanel = new JPanel(new GridLayout(2, 4));
private int[] alienArray = new int[8];
int countJ = 0, countM = 0;
private ImageIcon image = new ImageIcon("earth.jpg");
private int width, height;
Container con = getContentPane();
Font aFont = new Font("Gigi", Font.BOLD, 20);
public void init() {
/** Setting the Layout and adding the content. */
width = image.getIconWidth();
height = image.getIconHeight();
greeting.setFont(aFont);
greeting.setHorizontalAlignment(SwingConstants.CENTER);
con.setLayout(new BorderLayout());
con.add(greeting, BorderLayout.NORTH);
con.add(displayPanel, BorderLayout.CENTER);
/** Add Buttons to the Applet */
displayPanel.add(button);
String text = Integer.toString(i+1); // convert button # to String adding 1.
buttons.setText(text);
buttons.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
/** Shows the Alien representing the selected button and deactivate the button. */
if(event.getSource() == buttons)
button.setText("Jupiterian");
else
buttons[i].setText("Martian");
button.setEnabled(false);
con.remove(greeting);
displayPanel.remove(button);
displayPanel.setLayout(new FlowLayout());
gameOverMessage.setHorizontalAlignment(SwingConstants.CENTER);
con.add(gameOverMessage, BorderLayout.NORTH);
repaint();
}
public void paint(Graphics gr) {
super.paint(gr);
/** Condition when user loses the game. Two Jupiterians will be painted on the screen*/
Jupiterian jupit = new Jupiterian();
displayPanel.setBackground(Color.BLACK);
gameOverMessage.setFont(new Font ("Calibri", Font.BOLD, 25));
gameOverMessage.setText("The Earth has been destroyed!");
jupit.draw(gr, 250, 120);
gr.copyArea(190, 40, 465, 300, 500, 0);
gr.drawImage(image.getImage(), 400, 400, width, height, this); //+
}
}
---------------- method draw() from Jupiterian class
public void draw(Graphics g, int x, int y) {
g.setColor(Color.WHITE);
g.drawOval(x, y, 160, 160); // Body of the alien
g.drawLine(x, y + 80, x - 40, y + 170); // Left hand
g.drawLine(x - 40, y + 170, x - 40, y + 180); // Left hand fingers
g.drawLine(x - 40, y + 170, x - 55, y + 180);
Font aFont = new Font ("Chiller", Font.BOLD, 30); // Description text.
g.setFont(aFont);
g.drawString(toString(), 230, 60);
}
--- Abstract class
public abstract class Aliena {
protected String name;
protected String planet;
/** Constructor for the class. Creates the Alien object with the parameters provided */
public Aliena(String nam, int eyes, String hair, String plan){
name = nam;
planet = plan;
}
/** Method that returns a String with a complete description of the Alien. */
public String toString(){
String stringAlien = "I am " + name + " from " + planet;
return stringAlien;
}
}
Thanks in advance!
Don't call displayPanel.setBackground(Color.BLACK);, gameOverMessage.setFont(new Font("Calibri", Font.BOLD, 25));, gameOverMessage.setText("The Earth has been destroyed!"); or any update any other UI component from within any paint method.
This will simply cause a repaint to rescheduled and a vicious cycle of updates will start that will consume your CPU and suck the world into a black hole of doom...
Instead, change the state of the components before you call repaint
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class JAlienHunt extends JApplet implements ActionListener {
private JButton button = new JButton();
JLabel greeting = new JLabel("Welcome to Alien Hunt Game!");
JLabel gameOverMessage = new JLabel(" ");
JPanel displayPanel = new JPanel(new GridLayout(2, 4));
private int[] alienArray = new int[8];
int countJ = 0, countM = 0;
private ImageIcon image = new ImageIcon("earth.jpg");
private int width, height;
Container con = getContentPane();
Font aFont = new Font("Gigi", Font.BOLD, 20);
public void init() {
/**
* Setting the Layout and adding the content.
*/
width = image.getIconWidth();
height = image.getIconHeight();
greeting.setFont(aFont);
greeting.setHorizontalAlignment(SwingConstants.CENTER);
con.setLayout(new BorderLayout());
con.add(greeting, BorderLayout.NORTH);
con.add(displayPanel, BorderLayout.CENTER);
/**
* Add Buttons to the Applet
*/
displayPanel.add(button);
// String text = Integer.toString(i + 1); // convert button # to String adding 1.
button.setText("!");
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
/**
* Shows the Alien representing the selected button and deactivate the
* button.
*/
// if (event.getSource() == buttons) {
// button.setText("Jupiterian");
// } else {
//// buttons[i].setText("Martian");
// }
button.setEnabled(false);
con.remove(greeting);
displayPanel.remove(button);
displayPanel.setLayout(new FlowLayout());
gameOverMessage.setHorizontalAlignment(SwingConstants.CENTER);
con.add(gameOverMessage, BorderLayout.NORTH);
displayPanel.setBackground(Color.BLACK);
gameOverMessage.setFont(new Font("Calibri", Font.BOLD, 25));
gameOverMessage.setText("The Earth has been destroyed!");
repaint();
}
public void paint(Graphics gr) {
super.paint(gr);
/**
* Condition when user loses the game. Two Jupiterians will be painted on
* the screen
*/
Jupiterian jupit = new Jupiterian();
// displayPanel.setBackground(Color.BLACK);
// gameOverMessage.setFont(new Font("Calibri", Font.BOLD, 25));
// gameOverMessage.setText("The Earth has been destroyed!");
jupit.draw(gr, 250, 120);
// gr.copyArea(190, 40, 465, 300, 500, 0);
gr.drawImage(image.getImage(), 400, 400, width, height, this); //+
}
public class Jupiterian {
public void draw(Graphics g, int x, int y) {
g.setColor(Color.WHITE);
g.drawOval(x, y, 160, 160); // Body of the alien
g.drawLine(x, y + 80, x - 40, y + 170); // Left hand
g.drawLine(x - 40, y + 170, x - 40, y + 180); // Left hand fingers
g.drawLine(x - 40, y + 170, x - 55, y + 180);
Font aFont = new Font("Chiller", Font.BOLD, 30); // Description text.
g.setFont(aFont);
g.drawString(toString(), 230, 60);
}
}
}

Categories