How to create a JPanel for graphing - java

I'm making a function grapher that take 4 parameters and size for the Panel, but I don't know how to create a Panel class that will draw the information from the Grapher class. Can some one help please?(The parameters are not important, I just want to learn how to make a Graph Panel for later use)
Panel Class
import java.awt.BorderLayout;
public class Panel extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
}
/**
* Create the frame.
*/
public Panel(int w, int h) {
setVisible(true);
setSize(w,h);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, w, h);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setBackground(Color.WHITE);
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBorder(new EmptyBorder(0, 0, 0, 0));
panel.setBounds(0, 0, w, h);
contentPane.add(panel);
}
public void paint(Graphics g) {
super.paint(g);
//g.drawLine(110, 112,129, 132);
}
public Graphics getGraphics(Graphics g){
return g;
}
}
Grapher class
import java.awt.EventQueue;
public class Grapher {
private int panelWidth;
private int panelHeight;
int x1;
int x2;
int y1;
int y2;
int a;
int b;
int c;
int d;
private JFrame frmChinhsFunctionGrapher;
private JTextField textFieldXMin;
private JTextField textFieldXMax;
private JTextField textFieldYMin;
private JTextField textFieldYMax;
private JTextField textFieldA;
private JTextField textFieldB;
private JTextField textFieldC;
private JTextField textFieldD;
private JLabel lblPeriod;
private JLabel lblYIntercept;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Grapher window = new Grapher();
window.frmChinhsFunctionGrapher.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Grapher() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmChinhsFunctionGrapher = new JFrame();
frmChinhsFunctionGrapher.setTitle("Chinh's function grapher\r\n");
frmChinhsFunctionGrapher.setBounds(100, 100, 450, 300);
frmChinhsFunctionGrapher.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmChinhsFunctionGrapher.getContentPane().setLayout(null);
textFieldXMin = new JTextField();
textFieldXMin.setText("-200");
textFieldXMin.setBounds(66, 8, 86, 20);
frmChinhsFunctionGrapher.getContentPane().add(textFieldXMin);
textFieldXMin.setColumns(10);
JLabel lblXMin = new JLabel("X min");
lblXMin.setBounds(10, 11, 46, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblXMin);
JLabel lblXMax = new JLabel("X max");
lblXMax.setBounds(10, 42, 46, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblXMax);
textFieldXMax = new JTextField();
textFieldXMax.setText("200");
textFieldXMax.setBounds(66, 39, 86, 20);
frmChinhsFunctionGrapher.getContentPane().add(textFieldXMax);
textFieldXMax.setColumns(10);
textFieldYMin = new JTextField();
textFieldYMin.setText("-200");
textFieldYMin.setBounds(66, 70, 86, 20);
frmChinhsFunctionGrapher.getContentPane().add(textFieldYMin);
textFieldYMin.setColumns(10);
textFieldYMax = new JTextField();
textFieldYMax.setText("200");
textFieldYMax.setBounds(66, 101, 86, 20);
frmChinhsFunctionGrapher.getContentPane().add(textFieldYMax);
textFieldYMax.setColumns(10);
JLabel lblYMin = new JLabel("Y min");
lblYMin.setBounds(10, 73, 46, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblYMin);
JLabel lblYMax = new JLabel("Y max");
lblYMax.setBounds(10, 104, 46, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblYMax);
JLabel lblParameters = new JLabel("Parameters");
lblParameters.setBounds(320, 11, 93, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblParameters);
textFieldA = new JTextField();
textFieldA.setText("100");
textFieldA.setBounds(360, 39, 64, 20);
frmChinhsFunctionGrapher.getContentPane().add(textFieldA);
textFieldA.setColumns(10);
JLabel lblNewLabel = new JLabel("Graph's Height");
lblNewLabel.setBounds(263, 42, 72, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblNewLabel);
textFieldB = new JTextField();
textFieldB.setText("10");
textFieldB.setBounds(360, 70, 64, 20);
frmChinhsFunctionGrapher.getContentPane().add(textFieldB);
textFieldB.setColumns(10);
textFieldC = new JTextField();
textFieldC.setText("100");
textFieldC.setBounds(360, 101, 64, 20);
frmChinhsFunctionGrapher.getContentPane().add(textFieldC);
textFieldC.setColumns(10);
textFieldD = new JTextField();
textFieldD.setText("1");
textFieldD.setBounds(360, 132, 64, 20);
frmChinhsFunctionGrapher.getContentPane().add(textFieldD);
textFieldD.setColumns(10);
JButton btnGraph = new JButton("Graph");
btnGraph.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
getInput();
Panel pn = new Panel(panelWidth, panelHeight);
Graphics gs = pn.getGraphics();
gs.drawLine(100, 100, 200, 200);
}
});
btnGraph.setBounds(10, 228, 89, 23);
frmChinhsFunctionGrapher.getContentPane().add(btnGraph);
lblPeriod = new JLabel("Period");
lblPeriod.setBounds(263, 73, 46, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblPeriod);
lblYIntercept = new JLabel("Vertical shift");
lblYIntercept.setBounds(263, 104, 72, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblYIntercept);
JLabel lblHorizontalShift = new JLabel("Horizontal shift");
lblHorizontalShift.setBounds(263, 135, 86, 14);
frmChinhsFunctionGrapher.getContentPane().add(lblHorizontalShift);
}
public void getInput(){
x1 = Integer.parseInt(textFieldXMin.getText());
x2 = Integer.parseInt(textFieldXMax.getText());
y1 = Integer.parseInt(textFieldYMin.getText());
y2 = Integer.parseInt(textFieldYMax.getText());
a = Integer.parseInt(textFieldA.getText());
b = Integer.parseInt(textFieldB.getText());
c = Integer.parseInt(textFieldC.getText());
d = Integer.parseInt(textFieldD.getText());
panelWidth = Math.abs(x2 - x1);
panelHeight = Math.abs(y2 - y1);
}
}

There are quite some issues with your code
You should not use the null layout. You should not extent JFrame and even if you do it, you should not override the paint method of JFrame. You should create the GUI on the Event Dispatch Thread. You should have an idea of how you are going to define which area of the function is plotted into which area of the panel. (Plotting a function like sin(x) will result in a straight, horizontal line, because the values will alternate between -1 and 1, and thus, span a range of only 3 pixels...)
However, once I created a https://stackoverflow.com/help/mcve showing a very simple plotter that can be used to plot arbitrary functions. Maybe you find parts of it "inspiring".
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Main class of the simple function plotter. Contains the
* main method and creates the GUI
*/
public class SimplePlotMain
{
/**
* Entry point
*
* #param args not used
*/
public static void main(String[] args)
{
// Create the GUI on the Event-Dispatch-Thread
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
/**
* Creates the frame containing the simple plotter
*/
private static void createAndShowGUI()
{
// Create the main frame
JFrame frame = new JFrame("SimplePlot");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.setSize(800,600);
// Create the SimplePlotPanel and add it to the frame
SimplePlotPanel plotPanel = new SimplePlotPanel();
frame.getContentPane().add(plotPanel, BorderLayout.CENTER);
// Create the Function that should be plotted, and assign
// it to the SimplePlotPanel
Function function = new Function()
{
#Override
public double compute(double argument)
{
return Math.sin(argument)*argument;
}
};
plotPanel.setFunction(function);
// Create a simple control panel and add it to the frame
JComponent controlPanel = createControlPanel(plotPanel);
frame.getContentPane().add(controlPanel, BorderLayout.EAST);
// As the last action: Make the frame visible
frame.setVisible(true);
}
/**
* Creates a panel containing some Spinners that allow defining
* the area in which the function should be shown
*
* #param plotPanel The SimplePlotPanel, to which the settings
* will be transferred
* #return The control-panel
*/
private static JComponent createControlPanel(
final SimplePlotPanel plotPanel)
{
JPanel controlPanel = new JPanel(new BorderLayout());
JPanel panel = new JPanel(new GridLayout(0,2));
controlPanel.add(panel, BorderLayout.NORTH);
// Create spinners for the minimum and maximum
// X- and Y-values
final JSpinner minXSpinner = new JSpinner(
new SpinnerNumberModel(-1.0, -1000.0, 1000.0, 0.1));
final JSpinner maxXSpinner = new JSpinner(
new SpinnerNumberModel( 1.0, -1000.0, 1000.0, 0.1));
final JSpinner minYSpinner = new JSpinner(
new SpinnerNumberModel(-1.0, -1000.0, 1000.0, 0.1));
final JSpinner maxYSpinner = new JSpinner(
new SpinnerNumberModel( 1.0, -1000.0, 1000.0, 0.1));
// Add the spinners and some labels to the panel
panel.add(new JLabel("minX"));
panel.add(minXSpinner);
panel.add(new JLabel("maxX"));
panel.add(maxXSpinner);
panel.add(new JLabel("minY"));
panel.add(minYSpinner);
panel.add(new JLabel("maxY"));
panel.add(maxYSpinner);
// Create a ChangeListener that will be added to all spinners,
// and which transfers the settings to the SimplePlotPanel
ChangeListener changeListener = new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent event)
{
double minX = ((Double)minXSpinner.getValue()).doubleValue();
double maxX = ((Double)maxXSpinner.getValue()).doubleValue();
double minY = ((Double)minYSpinner.getValue()).doubleValue();
double maxY = ((Double)maxYSpinner.getValue()).doubleValue();
plotPanel.setRangeX(minX, maxX);
plotPanel.setRangeY(minY, maxY);
}
};
minXSpinner.addChangeListener(changeListener);
maxXSpinner.addChangeListener(changeListener);
minYSpinner.addChangeListener(changeListener);
maxYSpinner.addChangeListener(changeListener);
// Set some default values for the Spinners
minXSpinner.setValue(-10.0);
maxXSpinner.setValue( 10.0);
minYSpinner.setValue(-10.0);
maxYSpinner.setValue( 10.0);
return controlPanel;
}
}
/**
* Interface for a general function that may be plotted with
* the SimplePlotPanel
*/
interface Function
{
/**
* Compute the value of the function for the given argument
*
* #param argument The function argument
* #return The function value
*/
double compute(double argument);
}
/**
* The panel in which the function will be plotted
*/
class SimplePlotPanel extends JPanel
{
private static final long serialVersionUID = -6588061082489436970L;
/**
* The function that will be plotted
*/
private Function function;
/**
* The minimal x value that is shown
*/
private double minX = -1.0f;
/**
* The maximal x value that is shown
*/
private double maxX = 1.0f;
/**
* The minimal y value that is shown
*/
private double minY = -1.0f;
/**
* The maximal y value that is shown
*/
private double maxY = 1.0f;
/**
* Set the Function that should be plotted
*
* #param function The Function that should be plotted
*/
public void setFunction(Function function)
{
this.function = function;
repaint();
}
/**
* Set the x-range that should be plotted
*
* #param minX The minimum x-value
* #param maxX The maximum y-value
*/
public void setRangeX(double minX, double maxX)
{
this.minX = minX;
this.maxX = maxX;
repaint();
}
/**
* Set the y-range that should be plotted
*
* #param minY The minimum y-value
* #param maxY The maximum y-value
*/
public void setRangeY(double minY, double maxY)
{
this.minY = minY;
this.maxY = maxY;
repaint();
}
/**
* Overridden method from JComponent: Paints this panel - that
* is, paints the function into the given graphics object
*/
#Override
protected void paintComponent(Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D)gr;
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
paintAxes(g);
paintFunction(g);
}
/**
* Converts an x-coordinate of the function into an x-value of this panel
*
* #param x The x-coordinate of the function
* #return The x-coordinate on this panel
*/
private int toScreenX(double x)
{
double relativeX = (x-minX)/(maxX-minX);
int screenX = (int)(getWidth() * relativeX);
return screenX;
}
/**
* Converts an y-coordinate of the function into an y-value of this panel
*
* #param y The y-coordinate of the function
* #return The y-coordinate on this panel
*/
private int toScreenY(double y)
{
double relativeY = (y-minY)/(maxY-minY);
int screenY = getHeight() - 1 - (int)(getHeight() * relativeY);
return screenY;
}
/**
* Converts an x-coordinate on this panel into an x-coordinate
* for the function
*
* #param x The x-coordinate on the panel
* #return The x-coordinate for the function
*/
private double toFunctionX(int x)
{
double relativeX = (double)x/getWidth();
double functionX = minX + relativeX * (maxX - minX);
return functionX;
}
/**
* Paints some coordinate axes into the given Graphics
*
* #param g The graphics
*/
private void paintAxes(Graphics2D g)
{
int x0 = toScreenX(0);
int y0 = toScreenY(0);
g.setColor(Color.BLACK);
g.drawLine(0,y0,getWidth(),y0);
g.drawLine(x0,0,x0,getHeight());
}
/**
* Paints the function into the given Graphics
*
* #param g The graphics
*/
private void paintFunction(Graphics2D g)
{
g.setColor(Color.BLUE);
int previousScreenX = 0;
double previousFunctionX = toFunctionX(previousScreenX);
double previousFunctionY = function.compute(previousFunctionX);
int previousScreenY = toScreenY(previousFunctionY);
for (int screenX=1; screenX<getWidth(); screenX++)
{
double functionX = toFunctionX(screenX);
double functionY = function.compute(functionX);
int screenY = toScreenY(functionY);
g.drawLine(previousScreenX, previousScreenY, screenX, screenY);
previousScreenX = screenX;
previousScreenY = screenY;
}
}
}

First, I would say delete the main() method in the panel class. It has nothing to do with answering your question, but I think it'll cause problems and/or confusion.
What you need to do is
1) add a reference in the panel class to the Grapher class so that the panel paint method can call the Grapher class
2) set the reference to point to the instance of the Grapher class
3) have the Panel paint method invoke a method in the Grapher class to draw the graph.
1) Add a reference
public class Panel extends JFrame {
private Grapher myGrapher = null; //add this line
private JPanel contentPane;
2) Set the reference
public Panel(Grapher graph, int w, int h) { //change this line
myGrapher = graph; //add this line
setVisible(true);
and
public void actionPerformed(ActionEvent arg0) {
getInput();
Panel pn = new Panel(this, panelWidth, panelHeight); //change this line
//Graphics gs = pn.getGraphics(); //remove this line
//gs.drawLine(100, 100, 200, 200); //remove this line
}
3) Invoke the method
public void paint(Graphics g) {
super.paint(g);
//g.drawLine(110, 112,129, 132);
if(myGrapher != null) //add this line
{
myGrapher.drawGraph(g); //add this line
}
}
and in the Grapher class, add the method
void drawGraph(Graphics g) {
g.drawLine(100, 100, 200, 200);
//whatever else you need to draw the graph
}
Good luck!

Related

Minimizing/Maximizing java swing gui executes actionPerformed method

So I'm a complete beginner in Java swing gui. I am going through Head First Java as the starting book. I made a simple gui in which a button is there and pressing it creates different gradient on a circle above it. The code is all in the book. It works fine when i click the button. However, when i maximize/minimize the gui, it acts as if the button is pressed and gradient changes. Why does this happen?
GUI code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SimpleGuiC implements ActionListener {
JFrame frame;
public static void main(String[] args) {
SimpleGuiC gui=new SimpleGuiC();
gui.go();
}
public void go(){
frame=new JFrame();
frame.setTitle("Gradient changer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button=new JButton("Change colors");
button.addActionListener(this);
MyDrawPanel drawPanel=new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.getContentPane().add(BorderLayout.CENTER,drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
}
Random gradient generating code:
import java.awt.*;
import javax.swing.*;
public class MyDrawPanel extends JPanel{
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70,70,startColor, 150,150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(70,70,100,100);
}
}
Here's the implementation suggested in my comments:
public final class MyDrawPanel extends JPanel {
private Color startColor;
private Color endColor;
public MyDrawPanel() {
this.changeColors();
}
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(70, 70, 100, 100);
}
public void changeColors() {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
this.startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
this.endColor = new Color(red, green, blue);
this.repaint();
}
}
As you can see, the panel has a state (i.e. fields), containing the colors that the circle must have. These colors don't change in paintComponent(). They only change when the changeColors() method is called.
public class SimpleGuiC implements ActionListener {
private JFrame frame;
private MyDrawPanel drawPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleGuiC gui = new SimpleGuiC();
gui.go();
});
}
public void go() {
frame = new JFrame();
frame.setTitle("Gradient changer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Change colors");
button.addActionListener(this);
this.drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
this.drawPanel.changeColors();
}
}
And, as you can see here, the actionPerformed() method changes the state of the panel (i.e. the colors it must display). It does what the button says it does: change the colors. Each time the panel is repainted, it will always use the colors that were set the last time changeColors() has been called.
People in the comments told you why it happens. All you now have to do is create a boolean that will tell if it was pressed or not and then check.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SimpleGuiC implements ActionListener {
JFrame frame;
MyDrawPanel drawPanel;
public static void main(String[] args) {
SimpleGuiC gui=new SimpleGuiC();
gui.go();
}
public void go(){
frame=new JFrame();
frame.setTitle("Gradient changer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button=new JButton("Change colors");
button.addActionListener(this);
drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.getContentPane().add(BorderLayout.CENTER,drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
drawPanel.buttonPressed = true;
frame.repaint();
}
}
DrawPanel:
import java.awt.*;
import javax.swing.*;
public class MyDrawPanel extends JPanel{
public boolean buttonPressed = false;
private GradientPaint gradient;
public MyDrawPanel () {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endColor = new Color(red, green, blue);
gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
}
public void paintComponent(Graphics g) {
if (buttonPressed) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endColor = new Color(red, green, blue);
gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
buttonPressed = false;
}
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(gradient);
g2d.fillOval(70, 70, 100, 100);
}
}
Basically what this does is every time the button is pressed, the boolean will be set to true. Then when repainting, it will check if it's true and if yes, it will paint it and set it back to false so it can go again. Good Luck!
EDIT:
To make it not disappear. You need to separate the code for changing the gradient and for painting. So, paint every single time, but only change the gradient when the button is pressed. I hope this code I just updated will work.
EDIT 2:
Don't forget to encapsulate that variable, I didn't because I was in hurry, but just make it private and add getters and setters!

Why the subclass "TwoButtons" of JPanel didn't display on screen

It's my first post on StackOverflow. I'm a beginner in Java and I'm reading Head First Java recently. I have searched google for many times but I still can't find an answer to fix my doubt.
On chapter 12, I copy the code to Eclipse. My codes are executable, but after I click the button to change color of the circle, there's no any circle showed on the window. And another class "SimpleAnimation" has the same problem too. There is no any circle on the window. It has bothered me for two days. Please help this poor kid(TAT). Thanks!
Run TwoButtons
Here are the codes.
This is class TwoButtons:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class TwoButtons {
JFrame frame;
JLabel label;
public static void main(String[] args) {
TwoButtons gui = new TwoButtons();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelButton = new JButton("Change label");
labelButton.addActionListener(new LabelListener());
JButton colorButton = new JButton("Change circle");
colorButton.addActionListener(new ColorListener());
label = new JLabel("I'm a label");
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, label);
frame.setSize(500, 500);
frame.setVisible(true);
}
class LabelListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
label.setText("Ouch!");
}
}
class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
}
}
This is class MydrawPanel:
import javax.swing.JPanel;
import java.awt.*;
public class MyDrawPanel extends JPanel {
public void paintConponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(70, 70, 100, 100);
}
}
Run SimpleAnimation
This is class SimpleAnimation:
import javax.swing.*;
import java.awt.*;
public class SimpleAnimation {
int x = 70;
int y = 70;
public static void main(String[] args) {
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);
for(int i = 0; i < 130; i++) {
x++;
y++;
drawPanel.repaint();
try {
Thread.sleep(50);
} catch(Exception ex) {
}
}
}
class MyDrawPanel extends JPanel{
public void paintConponent(Graphics g) {
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
}
}
Thanks again!
For starters:
public void paintConponent(Graphics g) {
Should be:
#Override
public void paintComponent(Graphics g) {
Always use #Override notation when changing methods, to ensure the method name is spelled correctly and uses the correct method arguments. Or to put that another way, use the compiler flag to check that code is actually overriding a parent method, rather than defining a new one!
Other tips
Any custom painted component should:
Call the super method before custom painting, to ensure that older paints are erased & the BG color (etc.) of the component is painted.
Override the getPreferredSize() method to provide a hint to the layout manager.
You have not overridden the paintComponent method. There is a typo in the name. Please note the M in paintComponent. Your method, in each case, is named paintConponent.
The compiler will warn you if you try to override a method from a superclass but get the method signature wrong (the name or the number and types of parameters) if you use the #Override annotation on your method:
#Override
public void paintComponent(Graphics g) {
// . . .
}
You're missing the annulation override
import javax.swing.JPanel;
import java.awt.*;
public class MyDrawPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(70, 70, 100, 100);
this.setVisible(true);
}
}

java swing - painting multiple jpanels on the same jframe

Just to preface, I've looked for several hours trying to find a solution to this on here and several other sites. If you find a question I may have missed, please let me know.
Anywho, I'm trying to create a thumbnail viewer that displays 4 thumbnails (in jpanels) and 4 captions. I can draw out all 4 thumbnails, but they're all the same image (duplicates of the last one painted). I think it's part of how I'm trying to repaint them, but I can't figure out what to change. The imageAlbum is an ArrayList of jpg paths.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
//import MainFrame.ImageComponent;
import javax.swing.JLabel;
public class Thumbnails extends JFrame {
final int IMG_WIDTH = 80;
final int IMG_HEIGHT = 60;
private BufferedImage image;
private ImageAlbum imageAlbum;
private JPanel contentPane;
private JPanel thmbnl_1;
private JPanel thmbnl_2;
private JPanel thmbnl_3;
private JPanel thmbnl_4;
private JLabel thmbnl_1Label;
private JLabel thmbnl_2Label;
private JLabel thmbnl_3Label;
private JLabel thmbnl_4Label;
/**
* Create the frame.
*/
public Thumbnails(ImageAlbum album) {
imageAlbum = album;
String captionUnavailable = "Caption is not available";
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(4, 2, 0, 0));
thmbnl_1 = new JPanel();
thmbnl_1.setPreferredSize(new Dimension(80, 60));
panel.add(thmbnl_1);
thmbnl_2 = new JPanel();
thmbnl_2.setPreferredSize(new Dimension(80, 60));
panel.add(thmbnl_2);
thmbnl_1Label = new JLabel(captionUnavailable);
panel.add(thmbnl_1Label);
thmbnl_2Label = new JLabel(captionUnavailable);
panel.add(thmbnl_2Label);
thmbnl_3 = new JPanel();
thmbnl_3.setPreferredSize(new Dimension(IMG_WIDTH, IMG_HEIGHT));
panel.add(thmbnl_3);
thmbnl_4 = new JPanel();
thmbnl_4.setPreferredSize(new Dimension(IMG_WIDTH, IMG_HEIGHT));
panel.add(thmbnl_4);
thmbnl_3Label = new JLabel(captionUnavailable);
panel.add(thmbnl_3Label);
thmbnl_4Label = new JLabel(captionUnavailable);
panel.add(thmbnl_4Label);
setupThumbnails();
}// end Thumbnails(ImageAlbum album)
//
private void setupThumbnails() {
int albumSize = imageAlbum.getSize();
for(int i = 0; i < albumSize; i++) {
try {
image = resizeToThumbnail(ImageIO.read(new File(imageAlbum.getAlbum(i))));
switch(i) {
case 0:
thmbnl_1.setLayout(new BorderLayout());
thmbnl_1.add(new ImageComponent(image), BorderLayout.CENTER);
thmbnl_1Label.setText(imageAlbum.getCaption(i));
break;
case 1:
thmbnl_2.setLayout(new BorderLayout());
thmbnl_2.add(new ImageComponent(image), BorderLayout.CENTER);
thmbnl_2Label.setText(imageAlbum.getCaption(i));
break;
case 2:
thmbnl_3.setLayout(new BorderLayout());
thmbnl_3.add(new ImageComponent(image), BorderLayout.CENTER);
thmbnl_3Label.setText(imageAlbum.getCaption(i));
break;
case 3:
thmbnl_4.setLayout(new BorderLayout());
thmbnl_4.add(new ImageComponent(image), BorderLayout.CENTER);
thmbnl_4Label.setText(imageAlbum.getCaption(i));
break;
default:
break;
}// end switch-case
revalidate();
repaint();
}// end try-block
catch(IOException e) {
e.printStackTrace();
}// end catch-block
}// end for-loop
}// end setupCaptions()
//
public BufferedImage resizeToThumbnail(BufferedImage original) {
int type;
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, original.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(original, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
return resizedImage;
}// end resizeToThumbnail(...)
class ImageComponent extends JComponent {
/**
* Desc: constructor for ImageComponent
* #param: BufferedImage img
* #return: nothing
*/
public ImageComponent(BufferedImage img) {
image = img;
}// end ImageComponent()
/**
* Desc: draws out the image to the panel
* #param: Graphics g
* #return: void
*/
#Override
public void paintComponent(Graphics g) {
if(image == null)
return;
Graphics2D g2d = (Graphics2D) g;
// draw the image
g.drawImage(image, 0, 0, this);
g.dispose();
}// end paintComponents(Graphics g)
}// end class ImageComponent
}// end class class Thumbnails
EDIT
ImageAlbum class:
import java.util.*;
public class ImageAlbum {
private ArrayList imageAlbum;
private ArrayList imageCaptions;
private int size;
/**
* Desc: getter for album size
* #param: none
* #return: int
*/
public int getSize() {
return size;
}// end getSize()
/**
* Desc: getter for the image
* #param: int index
* #return: String
*/
public String getAlbum(int index) {
return imageAlbum.get(index).toString();
}// end getAlbum(int index)
/**
* Desc: getter for the image caption
* #param: int index
* #return: String
*/
public String getCaption(int index) {
return imageCaptions.get(index).toString();
}// end getCaption(int index)
/**
* Desc: default constructor for ImageAlbum
* #param: none
* #return: nothing
*/
public ImageAlbum() {
imageAlbum = new ArrayList();
imageCaptions = new ArrayList();
size = 0;
}// end ImageAlbum()
/**
* Desc: parameterized constructor for ImageAlbum
* #param: none
* #return: nothing
*/
public ImageAlbum(ArrayList tempImageAlbum, ArrayList tempImageCaptions) {
imageAlbum = tempImageAlbum;
imageCaptions = tempImageCaptions;
}// end ImageAlbum(...)
/**
* Desc: adds the image directory and caption to both array lists
* #param: String imageDirectory, String imageCaption
* #return: void
*/
public void add(String imageDirectory, String imageCaption) {
imageAlbum.add(imageDirectory);
imageCaptions.add(imageCaption);
size++;
}// end add(...)
/**
* Desc: clears imageAlbum and imageCaptions array lists
* #param: nothing
* #return: void
*/
public void clear() {
imageAlbum.clear();
imageCaptions.clear();
size = 0;
}// end clear()
}// end class ImageAlbum
FINAL EDIT
I'm obviously not understanding very well, so I've decided to take a different approach - I'm using JLabels and doing icons instead. Works great, thanks everyone for your help
Your panel is set for a BorderLayout, and you call panel.add() for each of your thumbnails. That method sets the given component into the middle of the BorderLayout, replacing whatever is there, so that's why you're just seeing the last one added. BorderLayout does not do what you want for the thumbnails.
I would expect you want GridLayout; it lays out components added to it in rows and columns. Set your panel to GridLayout (or whatever else you want to layout the thumbnails), and add the thumbnails to it. Then put panel wherever you want; by default, a JFrame has a Borderlayout on it, you probably want to put panel in the middle of that.

I need to update the graphics panel so the user can view the outcome

Right, so I've been given this new project where I have to create one of those turtle programs were the user inputs 'forward 10' and the turtle paints a line on the screen. We were given a big chunk of code to start off with which took a bit of the fun out of it and I also cant fully get my head around how to update what the actual graphics panel. Here's the code we were given:
`import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* Represents the graphics display panel within the turtle program. This panel contains an image which is updated to reflect user commands.
*
* #author mdixon
*
*/
#SuppressWarnings("serial")
public class GraphicsPanel extends JPanel {
int currentX = 0,currentY = 0;
JTextField commandLine;
/**
* The default BG colour of the image.
*/
private final static Color BACKGROUND_COL = Color.DARK_GRAY;
/**
* The underlying image used for drawing. This is required so any previous drawing activity is persistent on the panel.
*/
private BufferedImage image;
/**
* Draw a line on the image using the given colour.
*
* #param color
* #param x1
* #param y1
* #param x2
* #param y2
*/
public void createLine(int x2, int y2) {
System.out.println("current x position: " + currentX + "\ncurrent y position: " + currentY);
Graphics g = image.getGraphics();
g.drawLine(currentX, currentY, x2, y2);
//g.drawString("bloop" , currentX, currentY);
currentX = x2;
currentY = y2;
}
/**
* Clears the image contents.
*/
public void clear() {
Graphics g = image.getGraphics();
g.setColor(BACKGROUND_COL);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
public void setColour(Color colour){
Graphics g = image.getGraphics();
g.setColor(colour);
}
#Override
public void paint(Graphics g) {
super.paintComponent(g);
// render the image on the panel.
g.drawImage(image, 0, 0, null);
}
/**
* Constructor.
*/
GraphicsPanel() {
setPreferredSize(new Dimension(500, 300));
image = new BufferedImage(500, 300, BufferedImage.TYPE_INT_RGB);
// Set max size of the panel, so that is matches the max size of the image.
setMaximumSize(new Dimension(image.getWidth(), image.getHeight()));
clear();
createLine(currentX + 100,currentY); //THIS WORKS AND UPDATES THE GRAPHICS PANEL
}
}`
I have already done some changes to it but only minor.
From a different panel which contains a JtextField and a JButton
So I call the other panel using this:
GraphicsPanel graphic = new GraphicsPanel();
graphic.createLine(graphic.currentX + 100,graphic.currentY);
I know this actually gets to createLine because I added a console output which shows the change in current x and y positions.
So yeah, If anybody can help with updating the graphics panel when calling it from a different panel it would be greatly appriciated.
Update to code:
Main:
`
import java.awt.*;
import javax.swing.*;
public class driver {
public static void main(String[] args) {
JFrame frame = new JFrame("Turtle");
frame.setSize(525, 375);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WindowsPanel Window = new WindowsPanel();
frame.setJMenuBar(Window.createMenuBar());
frame.setContentPane(Window.createContentPane());
GraphicsPanel panel = new GraphicsPanel(); // creates panel
panel.setLayout(new BorderLayout());
frame.getContentPane().add(panel, BorderLayout.CENTER); // adds panel to frame
CommandPanel panel1 = new CommandPanel(); // creates panel
panel1.setLayout(new GridLayout(1, 2));
frame.getContentPane().add(panel1, BorderLayout.SOUTH); // adds panel to frame
frame.setVisible(true);
}
}
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class CommandPanel extends JPanel {
GraphicsPanel graphic = new GraphicsPanel();
private JTextField commandLine;
private JButton commandProcess;
CommandPanel() {
add(commandLine = new JTextField(40), Component.TOP_ALIGNMENT);
add(commandProcess = new JButton("Submit Command"),
Component.TOP_ALIGNMENT);
commandProcess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String commands = commandLine.getText();
try{
String[] userCommand = new String[2];
userCommand = commands.split(" ");
String action = userCommand[0];
int amount = Integer.parseInt(userCommand[1]);
switch (action) {
case ("forward"):
newX = graphic.currentX + amount;
newY = graphic.currentY - amount;
graphic.createLine(newX,newY);
break;
case ("blue"):
graphic.setColour(Color.BLUE);
break;
default:
System.out.println("Invalid command!");
}
} catch (ArrayIndexOutOfBoundsException e1){
System.out.println("both sides of the command mus be inputted");
}
}
});
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* Represents the graphics display panel within the turtle program. This panel contains an image which is updated to reflect user commands.
*
* #author mdixon
*
*/
#SuppressWarnings("serial")
public class GraphicsPanel extends JPanel {
int currentX = 0,currentY = 0;
/**
* The default BG colour of the image.
*/
private final static Color BACKGROUND_COL = Color.DARK_GRAY;
/**
* The underlying image used for drawing. This is required so any previous drawing activity is persistent on the panel.
*/
BufferedImage image;
/**
* Draw a line on the image using the given colour.
*
* #param color
* #param x1
* #param y1
* #param x2
* #param y2
*/
public void createLine(int x2, int y2) {
Graphics g = image.getGraphics();
g.drawLine(currentX, currentY, x2, y2);
currentX = x2;
currentY = y2;
}
/**
* Clears the image contents.
*/
public void clear() {
Graphics g = image.getGraphics();
g.setColor(BACKGROUND_COL);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
public void setColour(Color colour){
Graphics g = image.getGraphics();
g.setColor(colour);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g) {
super.paint(g);
// render the image on the panel.
g.drawImage(image, 0, 0, null);
}
/**
* Constructor.
*/
GraphicsPanel() {
setPreferredSize(new Dimension(500, 300));
image = new BufferedImage(500, 300, BufferedImage.TYPE_INT_RGB);
// Set max size of the panel, so that is matches the max size of the image.
setMaximumSize(new Dimension(image.getWidth(), image.getHeight()));
clear();
currentX = 200;
currentY = 200;
}
}
`
All the valid code, should work with copy/paste

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