JButton does not appear until moused over - java

When i run my program everything works as planned except that the button i have to change the cards on the screen does not appear until it is moused over. Im assuming this is because whatever container that is holding the images is over it but i dont know how to move it into the background or even what kind of container i can use to add images to.
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class oneplayer extends JFrame {
BufferedImage image1, image2, image3, image4;
Random gen = new Random();
public void redo() {
int p1, p2, p3, p4;
p1 = gen.nextInt(13) + 1;
p2 = gen.nextInt(13) + 14;
p3 = gen.nextInt(13) + 27;
p4 = gen.nextInt(13) + 40;
try {
File input1 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p1 + ".png");
File input2 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p2 + ".png");
File input3 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p3 + ".png");
File input4 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p4 + ".png");
image1 = ImageIO.read(input1);
image2 = ImageIO.read(input2);
image3 = ImageIO.read(input3);
image4 = ImageIO.read(input4);
} catch (IOException ie) {
System.out.println("Error:"+ie.getMessage());
}
repaint();
}
public oneplayer() {
JPanel buttonPanel = new JPanel();
setLayout(new BorderLayout());
JButton refresh = new JButton("Refresh");
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
redo();
}
});
add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(refresh, BorderLayout.CENTER);
redo();
}
public void paint(Graphics g) {
g.drawImage(image1, 20, 55, null);
g.drawImage(image2, 96, 55, null);
g.drawImage(image3, 172, 55, null);
g.drawImage(image4, 248, 55, null);
}
public static void main(String args[]) {
oneplayer frame = new oneplayer();
frame.setTitle("Random Cards");
frame.setSize(350, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Don't override paint() method. Instead override paintComponent() of main container.
Call super.paintComponent(g)
Don't extend JFrame but e.g. JPanel, add all you content to the panel and set the panel as a content pane of usual JFrame instance.

You'll need to call super.paint(g) inside your paint(Graphics) function to ensure that the Swing components inside the frame are properly displayed.

Haven't tested this with your sample, but I think you need to call the parent class's paint when overriding paint on your Frame in order for the Frame's components to show up. Like so:
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 20, 55, null);
g.drawImage(image2, 96, 55, null);
g.drawImage(image3, 172, 55, null);
g.drawImage(image4, 248, 55, null);
}

Related

How to keep the center of a JComponent at the same spot when resizing it?

I have program that resizes a button.
I just want to keep the center point in the center.
Perhaps by moving it by the distance between the center and…the upper left corner
Like when I resize the box in JSwing.
I want the center point to remain in the same spot.
How can I change the x, y of the upper left coordinates as the box increases
while keeping the center point in the same spot?
What woulf be the steps to get this done?
I guess my using the distance between the center and the upper left corner but how would that help
https://pastebin.com/0r8Vhez7
here's the code for context.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Buttons
{
public static void main(String[] args)
{
//Buttons.JLabelExperiments JE = new Buttons().new JLabelExperiments();
//JE.ASY();
Buttons.JButtonExperiments JEB = new Buttons().new JButtonExperiments();
JEB.Print();
}
class JLabelExperiments
{
public static void ASY()
{
JFrame frame = new JFrame();
frame.setSize(1200, 1200);
JLabel lol = new JLabel(new Scanner(System.in).nextLine());
lol.setBounds(500, 400, 380, 200);
lol.setBorder(BorderFactory.createLineBorder(Color.BLACK));
frame.add(lol);
JSlider J = new JSlider(JSlider.VERTICAL, 0, 200, 0);
J.setMinorTickSpacing(2);
J.setMajorTickSpacing(10);
J.setPaintLabels(true);
J.setPaintTicks(true);
J.setPaintTrack(true);
J.addChangeListener(e ->
{
{
lol.setHorizontalAlignment(J.getValue());
JLabel LOL = new JLabel(String.valueOf(J.getValue()));
LOL.setBounds(700, 700, 100, 150);
frame.add(LOL);
}
});
frame.add(J);
JSlider j = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
j.setMajorTickSpacing(10);
j.setMinorTickSpacing(2);
j.setPaintTrack(true);
j.setPaintTicks(true);
j.setPaintLabels(true);
j.setBounds(200, 700, 400, 100);
j.addChangeListener(e ->
{
lol.setVerticalAlignment(j.getValue());
JLabel HUH = new JLabel(String.valueOf(j.getValue()));
HUH.setBounds(950, 700, 100, 150);
frame.add(HUH);
});
System.out.printf("%1$s, %2$s", J.getChangeListeners(), j.getChangeListeners());
frame.add(j);
frame.setVisible(true);
}
public static void asy()
{
}
}
class JButtonExperiments
{
public static void Print()
{
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setSize(1200, 1200);
JButton B = new JButton("w");
B.setBounds(600, 600, 160, 160);
B.setText(new Scanner(System.in).nextLine());
frame.add(B);
JSlider width = new JSlider(SwingConstants.VERTICAL, 0, 0, 100);
JSlider height = new JSlider(JSlider.VERTICAL, 0, 0, 100);
width.setLocation(200, 600);
JLabel widthBox = new JLabel("Width");
widthBox.setBounds(20, 500, 120, 120);
height.setLocation(1000, 600);
JLabel heightBox = new JLabel("Height");
heightBox.setBounds(1180, 500, 120, 120);
width.setSize(100, 600);
height.setSize(100, 600);
frame.setVisible(true);
AtomicInteger counter = new AtomicInteger();
B.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
counter.getAndIncrement();
if(counter.get() == 1)
{
frame.add(width, height);
}
if(counter.get() == 3)
{
width.addChangeListener(E ->
{
B.setSize(B.getWidth()+width.getValue(), B.getHeight());
}
);
height.addChangeListener(E ->
{
B.setSize(B.getWidth(), B.getHeight()+height.getValue());
}
);
}
}
});
}
}
}
This was just a practice project but it seems this information may be more useful so please before forgive any lack of readability.
This code when run will make a button if you click it twice it will activate sliders that allow you to change the width and height of the button. By adding the value of the sliders to the value of the Button's width and height.
Use an appropriate layout manager, get it for free...
Now your button is always in the middle...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(new Insets(50, 50, 50, 50)));
setLayout(new GridBagLayout());
JButton btn = new JButton("Button in the middle");
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx = 100;
gbc.ipady = 100;
add(btn, gbc);
}
}
}
Change the text and see what happens ... for free
See Laying Out Components Within a Container

Why doesn't JPanel get rendered

I am trying to work with grid layout, and im trying to put few panels there that has some data, but nothing gets rendered at all.
Here is the current code that I have:
package main.cache.test;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ImageView {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ImageView window = new ImageView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ImageView() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JFrame frmSpitePicker = new JFrame("Title");
frmSpitePicker.setSize(658, 395);
frmSpitePicker.setResizable(false);
frmSpitePicker.setLocationRelativeTo(null);
frmSpitePicker.getContentPane().setLayout(null);
frmSpitePicker.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 35, 620, 303);
frmSpitePicker.getContentPane().add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
File file = new File("images/");
panel.setLayout(new GridLayout((file.listFiles().length / 6), 6));
int i = 0;
// getting files name from folder
for (String name : file.list()) {
JPanel panel_1 = new JPanel();
panel_1.setBounds(209, 362, 82, 87);
frmSpitePicker.getContentPane().add(panel_1);
panel_1.setLayout(null);
// create label
JLabel lblNewLabel = new JLabel((i++) + "");
lblNewLabel.setBounds(12, 13, 56, 16);
lblNewLabel.setIcon(new ImageIcon(new ImageIcon("images/" + name).getImage().getScaledInstance(8, 8, 1)));
lblNewLabel.setHorizontalTextPosition(JLabel.CENTER);
lblNewLabel.setVerticalTextPosition(JLabel.BOTTOM);
panel_1.add(lblNewLabel);
// create button
JButton btnNewButton = new JButton("btn");
btnNewButton.setBounds(12, 42, 58, 25);
panel_1.add(btnNewButton);
// add to the panel
panel.add(panel_1);
}
}
}
I don't know what is wrong with this, and why Jpanel when being added, it doesn't get rendered but when adding a JLabel would work.
Thanks in advance!
Using layouts correctly, we can easily get something like this:
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
public class ImageView {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
ImageView window = new ImageView();
} catch (Exception e) {
e.printStackTrace();
}
});
}
public ImageView() {
initialize();
}
private void initialize() {
int num = 32; // number of images to show..
JFrame frmSpitePicker = new JFrame("Title");
frmSpitePicker.setResizable(false);
JPanel panel = new JPanel(new GridLayout(0, 6));
JScrollPane scrollPane = new JScrollPane(panel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
frmSpitePicker.getContentPane().add(scrollPane);
for (int ii = 1; ii <= num; ii++) {
JPanel panel_1 = new JPanel(new BorderLayout());
// create label
JLabel lblNewLabel = new JLabel(ii + "");
lblNewLabel.setIcon(new ImageIcon(getImage()));
lblNewLabel.setHorizontalTextPosition(JLabel.CENTER);
lblNewLabel.setVerticalTextPosition(JLabel.BOTTOM);
panel_1.add(lblNewLabel, BorderLayout.CENTER);
// create button
JButton btnNewButton = new JButton("btn");
panel_1.add(btnNewButton, BorderLayout.PAGE_END);
// add to the panel
panel.add(panel_1);
// hack to ensure our scroll bar is active
// we require 3 rows to be visible..
if (ii==18) frmSpitePicker.pack();
}
frmSpitePicker.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Normally we'd call pack() here!
//frmSpitePicker.pack();
frmSpitePicker.setLocationRelativeTo(null);
frmSpitePicker.setVisible(true);
}
java.util.Random r = new java.util.Random();
private BufferedImage getImage() {
int s = 16;
BufferedImage bi = new BufferedImage(
s, s, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(new Color(
r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.fillRect(0, 0, s, s);
g.dispose();
return bi;
}
}
Note that I would tend to use a JList for this type of case. The panel_1 would become a renderer for a POJO what encapsulates the label and button. But the button might not be needed, in that a list can have listeners for selection and activation. If that's what the button does, it'd be redundant in a list, and lblNewLabel could replace the entire panel_1.
BTW - please make sure all resources needed, are available to run the code. When it comes to images, we might hot link (load by URL) to images available on the net1 or generate them in the code (as done here).
One way to get image(s) for an example is to hot link to images seen in this Q&A. E.G. This answer hot links to an image embedded in this question.

setBounds method isn't working properly?

Well the title explains it, basically the setBounds(int x, int y, int width, int height) method isn't working like I want it too as nothing is being displayed. The point of this code is to get the text from some text fields then close that window and and convert them to JLabel objects to be displayed on the screen but it doesn't do that. Here are some code fragments:
public class Create implements ActionListener {
private JTextArea t1, t2, t3;
private String s1 = t1.getText();
private String s2 = t2.getText();
private String s3 = t3.getText();
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
dispose();
setVisible(false);
t1 = new JTextArea(7, 17);
t2 = new JTextArea(7, 17);
t3 = new JTextArea(7, 17);
JFrame frame2 = new JFrame();
frame2.add(new Test(s1,s2,s3));
frame2.setTitle("Title");
frame2.setSize(700,500);
frame2.setResizable(true);
frame2.setLocationRelativeTo(null);
frame2.setVisible(true);
}
}
}
New class Test:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
#SuppressWarnings("serial")
public class Test extends JPanel implements ActionListener {
private int w = 250, velx = 2, x = 330;
Timer tm = new Timer(50,this);
public Test(String s1, String s2, String s3) {
setText(s1, s2, s3);
}
public void setText(String s1, String s2, String s3) {
JLabel label1 = new JLabel(s1);
label1.setBounds(100, 100, 500, 500);
JLabel label2 = new JLabel(s2);
label2.setBounds(75, 20, 100, 20);
JLabel label3 = new JLabel(s3);
label3.setBounds(100, 20, 100, 20);
}
}
*****String won't draw on top of rectangle*****
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("something", 300, 50);
g.drawString("something", 50, 100);
g.drawString("something", 50, 150);
}
public void paint(Graphics g){
tm.setInitialDelay(10000);
super.paint(g);
Graphics2D graph2 = (Graphics2D)g;
Shape Rect1 = new Rectangle2D.Float(330, 30, 250, 390);
graph2.setColor(Color.CYAN);
graph2.fill(Rect1);
Shape Rect2 = new Rectangle2D.Float(x, 30, w, 390);
graph2.setColor(Color.RED);
graph2.fill(Rect2);
tm.start();
}
You actually need to add those label to your JPanel , So that they can get Displayed
public void setText(String s1, String s2, String s3) {
JLabel label1 = new JLabel(s1);
label1.setBounds(100, 100, 500, 500);
JLabel label2 = new JLabel(s2);
label2.setBounds(75, 20, 100, 20);
JLabel label3 = new JLabel(s3);
label3.setBounds(100, 20, 100, 20);
add(label1);// Add the label to your current JPanel
add(label2);
add(label3);
}
When you need absolute positioning , you need to explicitly set the Layout to Null
JPanel#setLayout(null)
Update
How to draw Rectangle on JLabel .
override the paintComponent method of the JLabel. It should first call super.paintComponent, so you get whatever the JLabel contains, then add your own drawing code after that.
#override
public void paintComponent(Graphics g){
super.paintComponent(g)
Rectangle r = new Rectangle(xPos,yPos,width,height);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}

Drawing Graphics (g) into jpanel

Im trying to draw some bars that have random intergers into the java applet bellow but the overrides have an error im new to java i tried to makr the two areas in code the draw method is at the very bottom the other is the 2nd panel area
What im aiming for
sizes x,y not coordinates
-total size = 200,250
-location gui =200,50
-image = 140,150
-precip = 100,20
-temp = 20,100
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.util.*;
public class Final2 extends JFrame
{
//Panels
JPanel locationGui = new JPanel ();
JPanel temp = new JPanel ();
JPanel percip = new JPanel ();
JPanel image = new JPanel ();
//Location gui components
JButton Enter, Exit;
JTextField location;
JLabel city;
JRadioButton time;
JComboBox Seasons;
//bar # genertor
Random rand = new Random ();
int P = rand.nextInt (100) + 1; //Random Precipitation
int H = rand.nextInt (50) + 1; //Random Heat
public Final2 ()
{
init ();
}
public void init ()
{
Font font = new Font ("impact", Font.PLAIN, 20);
//________________________________________________new panel____________________
locationGui.setBackground (Color.RED);
JLabel guiLabel = new JLabel ("");
guiLabel.setFont (font);
Enter = new JButton ("Enter");
Exit = new JButton ("exit");
city = new JLabel ("What city?");
location = new JTextField (20); //location entry field
Seasons = new JComboBox ();
Seasons.addItem ("Summer");
Seasons.addItem ("Fall");
Seasons.addItem ("Winter");
Seasons.addItem ("Spring");
time = new JRadioButton ("check if night?");
locationGui.add (city);
locationGui.add (location);
locationGui.add (Seasons);
locationGui.add (time);
locationGui.add (guiLabel);
//________________________________________________new panel____________________
temp.setBackground (Color.BLUE);
temp.setLayout (new GridBagLayout ());
JLabel tempLabel = new JLabel ("Temp");
tempLabel.setFont (font);
temp.add (tempLabel);
//________________________________________________new panel____________________
percip.setBackground (Color.GREEN);
JLabel pLabel = new DrawingPanel (); //where it should be
percip.add (pLabel);
//________________________________________________new panel____________________
image.setBackground (Color.ORANGE);
image.setLayout (new GridBagLayout ());
JLabel imageLabel = new JLabel ("Image");
imageLabel.setFont (font);
image.add (imageLabel);
Container contentPane = getContentPane ();
contentPane.setLayout (new BorderLayout ());
contentPane.add (locationGui, BorderLayout.NORTH);
contentPane.add (temp, BorderLayout.EAST);
contentPane.add (percip, BorderLayout.SOUTH);
contentPane.add (image, BorderLayout.CENTER);
setContentPane (contentPane);
setDefaultCloseOperation (EXIT_ON_CLOSE);
setSize (400, 400);
setLocationRelativeTo (null);
setVisible (true);
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
new Final2 ();
}
}
);
}
private class DrawingPanel extends javax.swing.JPanel {//area i have issues with atm
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawPercip(g);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
}
public void drawPercip (Graphics g)
{
//Precipitation Bar
g.setColor (Color.black);
g.drawRect (40, 170, 100, 20); //outline of bar
g.setColor (Color.blue);
g.fillRect (40 + 1, 170 + 4, P, 14); //indicator bar (+4 puts space beetween outline bar)
}
public void drawTemp (Graphics g)
{
//Temparature Bar
g.setColor (Color.red);
g.fillRect (170 + 4, 50, 14, 100); //Covers in
g.setColor (Color.black);
g.drawRect (170, 50, 20, 100); //outline of bar
g.setColor (Color.white);
g.fillRect (170 + 4, 50 + 1, 16, 100 - H); //indicator bar (+4 puts space beetween outline bar)
}
}
my current Errors (4) are happening in this block of code at the #override the only message provided are "illegal token" and "unexpected symbols ignored" idk why it doesn't give more information
private class DrawingPanel extends javax.swing.JPanel {//area i have issues with atm
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawPercip(g);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
First I seen no applet,
Second, DrawingPanel is not a JLabel
JLabel pLabel = new DrawingPanel(); //where it should be
Change the pLable type to JComponent or JPanel or DrawingPanel depending on what you want to be able to access out of each class.
Third, you should not rely on magic numbers
public void drawPercip(Graphics g) {
//Precipitation Bar
g.setColor(Color.black);
g.drawRect(40, 170, 100, 20); //outline of bar
g.setColor(Color.blue);
g.fillRect(40 + 1, 170 + 4, P, 14); //indicator bar (+4 puts space beetween outline bar)
}
public void drawTemp(Graphics g) {
//Temparature Bar
g.setColor(Color.red);
g.fillRect(170 + 4, 50, 14, 100); //Covers in
g.setColor(Color.black);
g.drawRect(170, 50, 20, 100); //outline of bar
g.setColor(Color.white);
g.fillRect(170 + 4, 50 + 1, 16, 100 - H); //indicator bar (+4 puts space beetween outline bar)
}
There is no guarantee that the height and width of the panel is what you think it might be. Make use of the getWidth and getHeight methods
Fourth, if you intend to have more the one DrawingPanel, you should make
int P = rand.nextInt(100) + 1; //Random Precipitation
int H = rand.nextInt(50) + 1; //Random Heat
Part of the DrawingPanel.
You should also make the time to read through Code Conventions for the Java Programming Language

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