Java Choice Menu Difficulties, Colour and Draw_Line - java

I'm trying to create a MS Paint-like software with Java Choice Menus, but I'm experiencing some difficulties with two functions in particular
I get a massive wall of error text upon selecting a colour from my Colour Menu. What I wish to achieve is selecting the colour converts the string containing the option into lower case, before setting the PenColour into that option
Drawing Lines don't seem to work, despite the same code being functional in a different applet that didn't use Choice. I want it to select two points which then have a line drawn between them.
Here is my Code
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.Choice;
public class PockettProjectTest1 extends Applet implements ActionListener, MouseListener, MouseMotionListener{
//Coordinates and sizes used to draw GUI
private final int GUI_HEIGHT = 100;
private final int GUI_START_X = 10;
private final int GUI_START_Y = 10;
private final int FIELD_SIZE = 11; //Numbers of characters for text field display
////////////////////////GLOBAL VARIABLES////////////////////////
private Dimension appletSize; //used to encapsulate the Applets dimensions
private int x, y, appletHeight, appletWidth, PenThick, PenMode, ShapeMode, ClickXO, ClickYO, ClickXN, ClickYN, ClickCount;
private String SizeString;
//a Panel is a container used here to hold and position the GUI components
private Panel guiPanel;
private Color PenColour;
//GUI components cv
public void init(){
//Disables the applet layout manager and stops automatic GUI component positioning
setLayout(null);
setBackground(Color.white);
addMouseListener(this);
addMouseMotionListener(this);
addMouseListener(this);
ClickCount = 0;
ClickXO = 0;
ClickYO = 0;
ClickXN = 0;
ClickYN = 0;
PenMode = 0;
ShapeMode = 0;
appletSize = this.getSize(); //captures the Applet dimensions
appletHeight = appletSize.height; //captures the Applet height
appletWidth = appletSize.width; //captures the Applet width
//Set up the Panel ready to hold the GUI components
guiPanel = new Panel();
guiPanel.setLocation(0, 0);
guiPanel.setSize(appletWidth,GUI_HEIGHT);
guiPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 40));
guiPanel.setBackground(Color.lightGray);
add(guiPanel);
Choice mode = new Choice();
Choice size = new Choice();
Choice color = new Choice();
Choice shape = new Choice();
mode.add("Pen");
mode.add("Eraser");
mode.add("Fill");
mode.add("Shape");
size.add("01px");
size.add("02px");
size.add("03px");
size.add("05px");
size.add("10px");
size.add("15px");
size.add("20px");
size.add("30px");
size.add("50px");
shape.add("N/A");
shape.add("Line");
shape.add("Oval");
shape.add("Oblong");
shape.add("Square");
shape.add("Circle");
shape.add("FillOval");
shape.add("FillOblong");
shape.add("FillSquare");
shape.add("FillCircle");
//add choice or combobox
guiPanel.add(mode);
guiPanel.add(size);
guiPanel.add(shape);
PenThick = 1;
PenColour = Color.black;
mode.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
PenMode = mode.getSelectedIndex();
}
});
size.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
SizeString = size.getSelectedItem();
PenThick = Integer.parseInt(SizeString.substring(0,2));
Graphics g = getGraphics();
}
});
//// Start of Issue 1:
colour.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
ColourString = colour.getSelectedItem();
ColourString.toLowerCase();
Color PenColour.getColor(ColourString);
}
});
/// End of Issue 1
shape.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
ShapeMode = shape.getSelectedIndex();
}
});
}
public void actionPerformed(ActionEvent e) {
}
////Issue 2:
public void mouseReleased(MouseEvent me){
if (PenMode == 3) {
if (ClickCount == 0) {
ClickXO = me.getX();
ClickYO = me.getY();
ClickCount ++;
System.out.println(ClickCount);
return;
}
if (ClickCount == 1) {
ClickXN = me.getX();
ClickYN = me.getY();
System.out.println(ClickCount);
Graphics g = getGraphics();
g.setColor(Color.black);
g.drawLine(ClickXO, ClickYO, ClickXN, ClickYN);
System.out.println(ClickXO);
System.out.println(ClickYO);
System.out.println(ClickXN);
System.out.println(ClickYN);
ClickCount = 0;
}
}
}
/// End of Issue 2
public void mousePressed(MouseEvent e){
}
public void mouseDragged(MouseEvent e){
if (PenMode == 0){
Graphics g = getGraphics();
g.setColor(Color.black);
g.fillOval(e.getX(), e.getY(), PenThick, PenThick);
}
if (PenMode == 1){
Graphics g = getGraphics();
g.setColor(Color.white);
g.fillRect(e.getX(), e.getY(), PenThick, PenThick);
}
}
public void mouseMoved(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseClicked(MouseEvent e){
}
}
I have to have this code due by the end of Friday, so I hope I can get the issue solved by then.

Related

Movement stuck when clicking buttons

Created a Program similar to paint where there is a rectangle whose movement inside the screen can be controlled by "w,a,s,d" keys and its size increased or decreased using the scroller on the mouse. There are also several buttons of various colours which when pressed fills the rectangular shape with the respective colours. Now the problem is after clicking any colour button the movement is stopped ie. the rectangle doesn't move. You can increase and decrease its size but you can't move with "w,a,s,d" keys. Please do help me with that.
And also as an optional request, I'm also trying to paint with this rectangle ie. when I press the space bar I want to fill the colour which is selected at the specified area. Now even though I can do that. The next action I do ie. either pressing "w,a,s,d" keys or the scroller, the colour disappears. Now I know that the colour or fillRect() has to be saved somehow so that the next action doesn't affect it, but I've tried several ways but it isn't happening. I've commented the code for the painting below.
My first request is my main request, the second one if you are unable to understand what I mean or don't know the solution just leave it.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Animation extends Frame implements KeyListener,MouseWheelListener,ActionListener {
int x,y,a,b;
char choice1;
int draw=1;
int n=0;
int color1,color2,color3;
Button button1,button2,button3,button4,button5,button6,button7,button8,button9,button10;
Animation() {
setSize(1000, 1000);
setVisible(true);
x = 500;
y = 500;
a = 20;
b = 50;
addKeyListener(this);
addMouseWheelListener(this);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
button1 = new Button("Black");
button2 = new Button("Blue");
button3 = new Button("Green");
button4 = new Button("Orange");
button5 = new Button("Red");
button6 = new Button("Yellow");
button7 = new Button("Gray");
button8 = new Button("Cyan");
button9 = new Button("Magenta");
button10 = new Button("Pink");
add(button1);add(button2);add(button3);add(button4);add(button5);
add(button6);add(button7);add(button8);add(button9);add(button10);
button1.setBounds(50,680,50,20); button2.setBounds(120,680,50,20);
button3.setBounds(190,680,50,20); button4.setBounds(260,680,50,20);
button5.setBounds(330,680,50,20); button6.setBounds(400,680,50,20);
button7.setBounds(470,680,50,20); button8.setBounds(540,680,50,20);
button9.setBounds(610,680,50,20); button10.setBounds(680,680,50,20);
button1.addActionListener(this);button2.addActionListener(this);
button3.addActionListener(this);button4.addActionListener(this);
button5.addActionListener(this);button6.addActionListener(this);
button7.addActionListener(this);button8.addActionListener(this);
button9.addActionListener(this);button10.addActionListener(this);
addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
});
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
choice1 = e.getKeyChar();
if (choice1 == 'w') {
y = y - 10;
}
if (choice1 == 's') {
y = y + 10;
}
if (choice1 == 'a') {
x = x - 10;
}
if (choice1 == 'd') {
x = x + 10;
}
if(choice1 == ' '){
draw=2;
}
repaint();
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
double p = e.getPreciseWheelRotation();
if(p>0){
a=a+5;
b=b+5;
} else{
a=a-5;
b=b-5;
}
repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Black")){
color1 = 0;
color2 = 0;
color3 = 0;
}
if(e.getActionCommand().equals("Blue")){
color1 = 0;
color2 = 0;
color3 = 255;
}
if(e.getActionCommand().equals("Green")){
color1 = 0;
color2 = 255;
color3 = 0;
}
if(e.getActionCommand().equals("Orange")){
color1 = 255;
color2 = 165;
color3 = 0;
}
if(e.getActionCommand().equals("Red")){
color1 = 255;
color2 = 0;
color3 = 0;
}
if(e.getActionCommand().equals("Yellow")){
color1 = 255;
color2 = 255;
color3 = 0;
}
if(e.getActionCommand().equals("Gray")){
color1 = 169;
color2 = 169;
color3 = 169;
}
if(e.getActionCommand().equals("Cyan")){
color1 = 0;
color2 = 255;
color3 = 255;
}
if(e.getActionCommand().equals("Magenta")){
color1 = 255;
color2 = 0;
color3 = 255;
}
if(e.getActionCommand().equals("Pink")){
color1 = 255;
color2 = 192;
color3 = 203;
}
repaint();
}
public void paint(Graphics g) {
if(draw==1) {
g.drawRect(x, y, a, b);
g.setColor(new Color(color1,color2,color3));
g.fillRect(x,y,a,b);
}
// if(draw==2){
// fillColor(g);
// draw=1;
// }
}
// public void fillColor(Graphics g){
// g.setColor(Color.red);
// int[] temp1 = new int[50];
// temp1[n] = x;
// int[] temp2 = new int[50];
// temp2[n] = y;
// int[] temp3 = new int[50];
// temp3[n] = a;
// int[] temp4 = new int[50];
// temp4[n] = b;
//
//
// n++;
// for (int i=0;i<n;i++){
// System.out.println("abcd");
// g.fillRect(temp1[n],temp2[n],temp3[n],temp4[n]);
// }
//
// }
public static void main(String[] args) {
Animation animation = new Animation();
}
}
First of all there are basic design issues:
Don't extend Frame. There is no need to extend any class.
Don't use AWT components in a Swing application. JFrame is Swing. "Button" is AWT. For Swing your should be using JButton.
Don't use a null layout for the entire frame. Keep the default BorderLayout. Read the section from the Swing tutorial on How to Use BorderLayout.
For the buttons you should create a JPanel (which by default uses a FlowLayout) and add your buttons to this panel.
Then you add this panel to your frame using:
frame.add(buttonPanel, BorderLayout.PAGE_END);
Custom painting is done by extending JPanel and then you override the paintComponent(...) method. So you need to create a DrawingPanel to paint your rectangle. Read the Swing tutorial on Custom Painting for working examples to help you structure your code better.
Then you add the drawing panel to the frame using:
frame.add(drawingPanel, BorderLayout.CENTER):
Don't use a WindowListener to close the frame.
When you create the frame you can set the close property:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Using multiple nested if statements, like you do in the ActionListner is poor design. As you continue to support more colors the code just grows and grows. An alternative approach might be:
a) create a HashMap as an instance variable to contain the buttons and colors:
private HashMap<JButton, Color> buttonColors = new HashMap<>();
private Color rectangleColor = Color.BLACK;
b) now when you create each button you can update the hash map:
buttonColors.put(button1, Color.BLACK);
c) now the code in your ActionListener becomes:
JButton button = (JButton)e.getSource();
Color color = buttonColors.get(button);
rectangleColor = color;
repaint();
d) and the code in your paintComponent() method becomes:
//g.setColor(new Color(color1,color2,color3));
g.setColor( rectangleColor );
Don't create your buttons by brute force. Create a method.
Code to invoke method
buttonsPanel.add( createButton("Black", Color.BLACK) );
buttonsPanel.add( createButton("Blue", Color.BLUE) );
and the createButton(..) method would look something like:
public JButton (String text, Color color)
{
JButton button = new JButton( text );
button.addActionListener(this);
buttonColors.put(button, color);
return button;
}
A lot of suggestions here. The code is posted without testing, so understand each concept and make a change one at a time and test to make sure you implement each step correctly.
Now the problem is after clicking any colour button the movement is stopped ie. the rectangle doesn't move.
A KeyEvent is only passed to the component with focus. When you click on a button the painting panel loses focus and no longer responds to events.
The better solution is to use Key Bindings. Key bindings will work even when a component doesn't have focus. See: Motion Using the Keyboard for more information and working examples.
Short answer for the first. Add:
button1.setFocusable(false);
button2.setFocusable(false);
button3.setFocusable(false);
button4.setFocusable(false);
button5.setFocusable(false);
button6.setFocusable(false);
button7.setFocusable(false);
button8.setFocusable(false);
button9.setFocusable(false);
button10.setFocusable(false);

Java Array Loop Graphics page not functioning

edit 2: I decided that it would be easier to understand if I just put the entire code up, so that you can test it.
edit: I realize that what I said was unclear, so I will explain this as best as I can. Basically, I am drawing rectangles on a Graphics page using the fillRect method. The problem is that when I change the size of one, they all change, as they are all being redrawn everytime a new one is drawn. To correct this, I added an array that stores all of the sizes which are input via the scrollwheel in another part of the problem. Anyways, I know that the problem is isolated to the loop that supposedly draws them all a certain size, so I added a loop that in theory should give me a temporary variable each time to use that redraws all of the rectangle's sizes starting at 0 each time the main loop is run. The problem is that this does not in fact redraw the rectangles to their individual sizes, and instead draws them to the current size. I have updated the code part as well.
I am having trouble with a project in Java. What it is supposed to do is change the size of each individual rectangle object by storing it in an array, and then recreating the rectangles based off the length from the array. I (at least I think) do this by creating a variable that should be equal to the SIZE that is changed in another part of the program, and then set that equal to the particular element in the array at i. Anyhow, when I do this, I change all of the lengths to whatever the current length is when I draw a rectangle. I know that the problem is by me using i in the size part, but what would I use? Thanks in advance for any help!
Here is the code:
public class Dots
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Array Rectangles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DotsPanel dotsPanel = new DotsPanel();
frame.getContentPane().add(dotsPanel);
//buttons
JButton btnNewButton = new JButton("RED");
btnNewButton.setHorizontalAlignment(SwingConstants.LEFT);
btnNewButton.setVerticalAlignment(SwingConstants.BOTTOM);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton.setForeground(Color.RED);
dotsPanel.add(btnNewButton);
JButton btnNewButton_1 = new JButton("GREEN");
btnNewButton_1.setForeground(Color.GREEN);
btnNewButton_1.setVerticalAlignment(SwingConstants.BOTTOM);
dotsPanel.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("BLUE");
btnNewButton_2.setForeground(Color.BLUE);
dotsPanel.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("BLACK");
btnNewButton_3.setForeground(new Color(0, 0, 0));
dotsPanel.add(btnNewButton_3);
frame.pack();
frame.setVisible(true);
}
}
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class DotsPanel extends JPanel
{
// radius of each dot
private int SIZE = 25;
private int SIZEAccess;
private static final Random generator = new Random();
//used to count amount of dots
private ArrayList<Point> pointList;
int[] sizes = new int [10000];
//Sets up this std. sized panel to listen for mouse events.
public DotsPanel()
{
pointList = new ArrayList<Point>();
addMouseListener (new DotsListener());
addMouseMotionListener(new DotsListener());
addMouseWheelListener(new DotsListener());
setBackground(Color.white);
setPreferredSize(new Dimension(1024, 768));
}
//used to generate a random color
public static Color randomColor() {
return new Color(generator.nextInt(256), generator.nextInt(256), generator.nextInt(256));
}
// Draws all of the dots stored in the list.
public void paintComponent(Graphics page)
{
super.paintComponent(page);
//draws a centered dot of random color
int i = 0;
for (Point spot : pointList)
{
sizes[i] = SIZE;
//SIZEAccess = SIZE;
//sizes[i] = SIZEAccess;
//page.fillRect(spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
for (int temp = 0; temp <= i; temp++)
page.fillRect(spot.x-sizes[temp], spot.y-sizes[temp], sizes[temp]*2, sizes[temp]*2);
//page.fillRect(spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
//page.setColor(randomColor());
//page.setColor(c)
i++;
}
//displays the amount of rectangles drawn at the top left of screen
page.drawString("Count: " + pointList.size(), 5, 15);
page.drawString("To change the size of the squares, use mouse scroll wheel.", 350, 15);
page.drawString("Size: " + SIZE, 950, 15);
}
// Represents the listener for mouse events.
private class DotsListener implements MouseListener, MouseMotionListener, MouseWheelListener
{
// Adds the current point to the list of points and redraws
// the panel whenever the mouse button is pressed.
public void mousePressed(MouseEvent event)
{
pointList.add(event.getPoint());
repaint();
}
// Provide empty definitions for unused event methods.
public void mouseClicked(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {}
// Adds the current point to the list of points and redraws
// the panel whenever the mouse button is dragged.
public void mouseDragged(MouseEvent event) {
pointList.add(event.getPoint());
repaint();
}
public void mouseMoved(MouseEvent event) {
}
public void mouseWheelMoved(MouseWheelEvent event)
{
int notches = 0;
notches = event.getWheelRotation();
//int
if (notches > 0)
{
SIZE = SIZE + notches;
notches = 0;
}
else if (notches < 0)
{
int tempSIZE = SIZE;
tempSIZE = tempSIZE + notches;
//prevents the program from having dots that increase due to multiplying negatives by negatives
//by making anything less than 1 equal 1
if(tempSIZE < 1)
tempSIZE = 1;
SIZE = tempSIZE;
notches = 0;
}
}
}
//SIZE = SIZE + notches;
}
You appear to have ArrayList's interacting with arrays in a confusing mix that makes it hard for us to follow your logic. This suggests that your logic may be too complex for your own good and that your code might benefit from simplification. Why not instead create a List<Rectangle> such as an ArrayList<Rectangle>, and then simply loop through this list in your paintComponent method, and draw each Rectangle using the Graphics2D object's draw(...) or fill(...) method:
private List<Rectangle> rectangleList = new ArrayList<>();
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Rectangle rectangle : rectangleList) {
g2.fill(rectangle);
}
}
For example:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Foo extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color BACKGROUND = Color.black;
private static final Color FILL_COLOR = Color.pink;
private static final Color DRAW_COLOR = Color.red;
private static final Stroke STROKE = new BasicStroke(3);
private List<Rectangle> rectangleList = new ArrayList<>();
private Point pressPoint = null;
private Point dragPoint = null;
public Foo() {
setBackground(BACKGROUND);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Stroke oldStroke = g2.getStroke();
g2.setStroke(STROKE);
for (Rectangle rectangle : rectangleList) {
g2.setColor(FILL_COLOR);
g2.fill(rectangle);
g2.setColor(DRAW_COLOR);
g2.draw(rectangle);
}
g2.setStroke(oldStroke);
if (pressPoint != null && dragPoint != null) {
g2.setColor(FILL_COLOR.darker());
int x = Math.min(pressPoint.x, dragPoint.x);
int y = Math.min(pressPoint.y, dragPoint.y);
int width = Math.abs(pressPoint.x - dragPoint.x);
int height = Math.abs(pressPoint.y - dragPoint.y);
g2.drawRect(x, y, width, height);
}
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
pressPoint = e.getPoint();
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
dragPoint = e.getPoint();
int x = Math.min(pressPoint.x, dragPoint.x);
int y = Math.min(pressPoint.y, dragPoint.y);
int width = Math.abs(pressPoint.x - dragPoint.x);
int height = Math.abs(pressPoint.y - dragPoint.y);
Rectangle rect = new Rectangle(x, y, width, height);
rectangleList.add(rect);
pressPoint = null;
dragPoint = null;
repaint();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Foo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Adding JPanel after removing it from JFrame

I'm developing a Java Game. I'm stuck at a point,where I need to restart the whole game again after GameOver. Here is the skeleton of my program:
package projectflappy;
import java.awt.*;
public final class TheGame extends JFrame implements MouseListener{
JPanel jp;
//declaration of the varibles
int x_width = 500;
int y_height = 500;
int count = 5 ;
Ellipse2D Ball;
int x_ball;
int y_ball;
int cord_xup1,cord_xdown1;
int cord_xup2,cord_xdown2;
int cord_xup3,cord_xdown3;
int cord_xup4,cord_xdown4;
int cord_xup5,cord_xdown5;
Boolean flag = true;
RoundRectangle2D up1,down1,up2,down2,up3,down3,up4,down4;
Font font = new Font("Matura MT Script Capitals",Font.ROMAN_BASELINE,40);
Font font1 = new Font("Matura MT Script Capitals",Font.ROMAN_BASELINE,20);
Font font3 = new Font("Matura MT Script Capitals",Font.ROMAN_BASELINE,20);
float das[] = {10.0f};
BasicStroke color = new BasicStroke(10,BasicStroke.CAP_ROUND,BasicStroke.JOIN_BEVEL,20.0f,das,0.0f);
GradientPaint gp2 = new GradientPaint(20, 0,
Color.DARK_GRAY, 0, 10, Color.GRAY, true);
GradientPaint gp3 = new GradientPaint(30, 0,
Color.BLACK, 0, 20, Color.GREEN, true);
Toolkit kit = Toolkit.getDefaultToolkit();
//Getting the "background.jpg" image we have in the folder
Image background = kit.getImage("D:\\College\\Programs\\ProjectFLAPPY\\src\\projectflappy\\1.png");
JLabel a = new JLabel("Get Ready ! Click to Start.");
JLabel retry = new JLabel(new ImageIcon("D:\\College\\Programs\\ProjectFLAPPY\\src\\projectflappy\\unnamed.png"));
int score = 0;
//constructor
public TheGame() throws IOException
{
super("Simple Drawing");
setSize(x_width, y_height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
jp = new DrawingPanel();
add(jp);
addMouseListener(this);
}
ActionListener action = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
update();
repaint();
}
};
Timer t = new Timer(50,action);
public void init()
{
x_ball = 30;
y_ball = 200;
cord_xup1 = 175; cord_xdown1 = 175;
cord_xup2 = 320; cord_xdown2 = 320;
cord_xup3 = 460; cord_xdown3 = 460;
cord_xup4 = 585; cord_xdown4 = 585;
cord_xup5 = 700; cord_xdown5 = 700;
retry.setVisible(false);
retry.setBounds(175,260,46,46);
a.setForeground(Color.YELLOW);
a.setFont(font1);
a.setVisible(true);
a.setBounds(105,200,300,100);
}
#Override
public void mouseClicked(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
a.setVisible(false);
if( flag == false)
{
t.stop();
}
else
{
t.start();
}
y_ball = y_ball - 40;
count--;
}
#Override
public void mousePressed(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseReleased(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseEntered(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseExited(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
// for drawing on the panel
class DrawingPanel extends JPanel{
private static final long serialVersionUID = 1L;
public DrawingPanel() {
setPreferredSize(new Dimension(300, 300));
setLayout(null);
init();
add(a);
add(retry);
// addMouseListener(this);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D d = (Graphics2D)g;
d.drawImage(background, -270,-30, this);
Ball = new Ellipse2D.Double(x_ball,y_ball,30,30);
d.setColor(Color.green);
d.setFont(font3);
up1 = new RoundRectangle2D.Double(cord_xup1,-5,30,175,20,20);
down1 = new RoundRectangle2D.Double(cord_xdown1,310,30,155,20,20);
up2 = new RoundRectangle2D.Double(cord_xup2,-5,30,200,20,20);
down2 = new RoundRectangle2D.Double(cord_xdown2,310,30,175,20,20);
up3 = new RoundRectangle2D.Double(cord_xup3,-5,30,230,20,20);
down3 = new RoundRectangle2D.Double(cord_xdown3,350,30,135,20,20);
up4 = new RoundRectangle2D.Double(cord_xup4,-5,30,115,20,20);
down4 = new RoundRectangle2D.Double(cord_xdown4,240,30,115,20,20);
d.setPaint(gp2);
d.setStroke(color);
d.fill(up1);
d.fill(down1);
d.fill(up2);
d.fill(down2);
d.fill(up3);
d.fill(down3);
d.fill(up4);
d.fill(down4);
d.setPaint(gp3);
d.setStroke(color);
d.fill(Ball);
d.setColor(Color.BLACK);
d.setFont(font1);
d.drawString(""+score ,200,50);
if( Ball.intersects(up1.getBounds()) || Ball.intersects(down1.getBounds()) || Ball.intersects(up2.getBounds()) || Ball.intersects(down2.getBounds()) || Ball.intersects(up3.getBounds()) || Ball.intersects(down3.getBounds()) || Ball.intersects(up4.getBounds()) || Ball.intersects(down4.getBounds()))
{
t.stop();
flag = false;
d.setColor(Color.red);
d.setFont(font);
d.drawString("Game Over : "+score ,100,250);
retry.setVisible(true);
}
retry.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent event) {
init(); //reset properties
}
//...
#Override
public void mousePressed(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseReleased(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseEntered(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseExited(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
}
public void update()
{
cord_xdown1 -= 5;
cord_xup1 -= 5;
cord_xdown2 -= 5;
cord_xup2 -= 5;
cord_xdown3 -= 5;
cord_xup3 -= 5;
cord_xdown4 -= 5;
cord_xup4 -= 5;
cord_xdown5 -= 5;
cord_xup5 -= 5;
if( cord_xup1 <=-20)
{
cord_xup1 = 500;
cord_xdown1 = 500;
}
if( cord_xup2 <=-20)
{
cord_xup2 = 500;
cord_xdown2 = 500;
}
if( cord_xup3 <=-20)
{
cord_xup3 = 500;
cord_xdown3 = 500;
}
if( cord_xup4 <=-20)
{
cord_xup4 = 500;
cord_xdown4 = 500;
}
if( cord_xup5 <=-20)
{
cord_xup5 = 500;
cord_xdown5 = 500;
}
if(count >= 0)
{
y_ball = y_ball - 7;
count--;
if( y_ball == y_height)
{
t.stop();
}
}
else
{
y_ball = y_ball + 7;
if( y_ball == y_height-70)
{
t.stop();
}
}
if(cord_xdown1 == x_ball || cord_xdown2 == x_ball || cord_xdown3 == x_ball || cord_xdown4 == x_ball)
{
score = score+1;
}
}
public static void main(String[] args) throws IOException {
new TheGame();
}
}
here retry is a JLabel in which I'm using a MouseListener to do things.
When I run,the JPanel gets completely removed from the JFrame but the new JPanel really doesn't seem to work. But only one component i.e, a.setVisble(true) works.
This is the frame when the Players gets out.
This Frames when the Player clicks on the retry button.
The reason your new panel is not showing is due to the component hierarchy being invalid. You attempt to revalidate, but you did it before adding the panel. You need to do it AFTER you add a component to an already visible container. Check out invalidate():
This method is called automatically when any layout-related information changes (e.g. setting the bounds of the component, or adding the component to a container).
So you must validate after adding the component, not before. revalidate() invalidates then revalidates the component hierarchy.
The proper way to handle this would be to revert your game back to it's original form; just change everything back to how it was. No need to create a new panel.
You could create a method, init(), which sets your game to how it should be:
//Contains the properties that will change during gameplay
void init() {
retry.setVisible(false);
a.setForeground(Color.YELLOW);
//...
}
Which you can then call when you create the board (in the constructor) and when you press retry (in the listener):
public DrawingPanel() {
setPreferredSize(new Dimension(300, 300));
setPreferredSize(new Dimension(300, 300));
setLayout(null);
init(); //sets properties
a.setFont(font1);
a.setVisible(true);
a.setBounds(105,200,300,100);
add(a);
retry.setBounds(175,260,46,46);
retry.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent event) {
init(); //reset properties
}
//...
});
add(retry);
}
You shouldn't add a listener to a component in your update() method, since update() will be called multiple times. Add it in your constructor.
If retry is a JButton, you should use an ActionListener. I wasn't sure, so I kept it as a mouse listener.
You should avoid using null layout (absolute positioning). Layout Managers position and size components using specific calculations to ensure your resulting GUI looks the same on all platforms. There are a few uses where absolute positioning is a viable option, as mentioned in the tutorials, but it's always best to prefer a Layout Manager. IMO, null layout is bad practice, and the only reason one would use it is if they didn't understand layout managers, which is a problem in itself.
To learn more about layout managers, check out the Visual Guide to Layout Managers trail. Not only does the JDK come bundled with layouts, but you can also create your own or use a third party layout, like MigLayout
EDIT:
Post Swing code to the Event Dispatch Thread. Swing event handlers (painting, listeners) are executed on the Event Dispatch Thread. To ensure the Swing code you write is in sync with the EDT, post any Swing code that isn't already being executed on the EDT to the EDT by using invokeLater or invokeAndWait.
Do not size your frame directly. Allow your frame to size based off the contents inside of it. Your DrawingPanel (the game canvas) should determine the size of the frame.
TheGame should not extend JFrame, since it's not a frame itself, rather than something contained within a frame. Having it extend JPanel would be a little easier on you (you won't be forced to create a new class to override the paint method). Although, TheGame shouldn't extend anything, it should HAVE these things (has-a relationship, not is-a). But since you're still a beginner, I don't wanna overwhelm you with a completely new design, so I considered TheGame to be the actual game canvas (where things will be draw; TheGame will extend JPanel), so you'll no longer need DrawingBoard.
As mentioned before, you should NOT add listeners (or do any task that is only needed once) in the paint method. Keep in mind that the paint method is for painting, not initializing or setting values. You should attempt to keep logic out of that method if possible.
Stay consistent. You use a JLabel for "Click to start!", yet you use drawString for "Game Over". Pick one or the other. This choice is really up to you. For this example, I chose to use drawString, since it's consistent with the rest of your rendering methods (how you paint the background, ball and obstacles)
DO NOT CREATE NEW OBJECTS IN YOUR PAINT METHOD. You're creating a ton of new objects every 50 milliseconds. This is NOT needed, and will harm performance critically. When you use the new keyword, you create a new object. Instead of creating a new object to change it (or revert it back), just change it's state.
Take advantage of Object Orientation. It'll help keep you organized, and allow you to easily manage and scale up your application. Don't shove a bunch of variables into one class to represent a ton of different things (cordx_up1, cordx_up2... it's definitely not scalable).
Look into some of the Adapter classes like MouseAdapter and KeyAdapter; they allow you to handle events without needing to declare methods you might not use.
Use access modifiers. If you aren't familiar with them, get to know them. It makes managing code a lot easier if you know where it can be used ahead of time.
Your paths point to a specific drive with a specific name. This should not be the case, since not everyone uses that drive and/or folder name. Package your images with your project, then refer to them locally.
With that said, you have a lot of studying to do.
What I did was create a Ball class and an Obstacle class, to get a little more organized. ball_x and ball_y are now inside the Ball class, as well as the gradient for it. The objects we create from this class will now have these properties (states). I create 1 ball object for your game.
Instead of creating new variables for each pole (cordx_up1), the Obstacle class has 2 RoundRectangle2D, top and bottom, which are the poles your ball is supposed to avoid. Each obstacle also has a gradient, which is used for both top and bottom. Now I can create 1 obstacle object for 2 aligned poles. You can change the starting x position of the obstacle (although I don't recommend allowing this; x should be set dynamically based on other obstacles' positions), as well as the size for top and bottom. I create 5 obstacle objects.
To keep your game labels organized (by color, message, location, font) while using drawString instead of JLabel, I created a GameLabel class.
I separated the main method into it's own class, named Launcher, which creates a JFrame and adds your game to it; all on the Event Dispatch Thread:
public class Launcher {
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(new TheGame());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
Your Game class now extends JPanel, so you can override the paint method to render the game. I created 1 Ball and a LinkedList for your obstacles. I chose a LinkedList since inserting/removing from front/end is guaranteed constant time, meaning it'll take the same amount of time to remove/insert no matter how many obstacles are in the list. When the ball passes an obstacle, I remove it from the front of the list and add it to the back. The first obstacle in the list is always the next obstacle.
I saw how some Strings were being re-used, so I created final variables for them, which you can easily change. There's also the currentlyPlaying and isAlive booleans. currentlyPlaying is set to true when the user first clicks (to start the game), and set to false once the user has clicked to restart the game (after he lost).
readyToJump is the flag I use to forward mouse events to your update() method (technically your updatePlayerPostion() method, but it's still "centeralized" within your update() method). It's best to keep all your logic in one place. readyToJump = true would have been the only statement in your listener's method if you weren't relying on calling timer.start() in it. Since update() can't be called unless the timer has started, and mouseEvent starts the timer, we must still handle starting the game in your listener's method.
#SuppressWarnings("serial")
public final class TheGame extends JPanel implements MouseListener, ActionListener {
public static final int WIDTH = 500, HEIGHT = 500;
private final String START_SCORE = "0",
START_MESSAGE = "Get Ready ! Click to Start.",
BACKGROUND_URL = "/res/flappy.png";
private boolean currentlyPlaying, readyToJump, isAlive = true;
private int score;
private Timer timer;
private Image background;
private GameLabel messageLabel, scoreLabel;
private Collection<Obstacle> obstaclesInOrder;
private LinkedList<Obstacle> obstacles;
private Ball ball;
public TheGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
addMouseListener(this);
timer = new Timer(50, this);
background = loadBackgroundImage();
messageLabel = new GameLabel(START_MESSAGE, 150, 240);
scoreLabel = new GameLabel(START_SCORE, 250, 60);
obstacles = new LinkedList<>();
obstacles.removeAll(obstacles);
obstaclesInOrder = Arrays.asList(new Obstacle(175, 20, 45), new Obstacle(320), new Obstacle(460), new Obstacle(585), new Obstacle(700));
obstacles.addAll(obstaclesInOrder);
ball = new Ball(30, 100);
}
#Override
public void mouseClicked(MouseEvent e) {
if (!currentlyPlaying) {
startGame();
} else if (!isAlive) {
reset();
}
readyToJump = true;
}
private void startGame() {
currentlyPlaying = true;
messageLabel.update("");
timer.start();
}
private void endGame() {
isAlive = false;
scoreLabel.update("");
messageLabel.update("Game Over. Your score was " + Integer.toString(score));
timer.stop();
}
private void reset() {
ball.reset();
for (Obstacle obstacle : obstacles)
obstacle.reset();
messageLabel.update(START_MESSAGE, 150, 240);
scoreLabel.update(START_SCORE, 250, 60);
obstacles.removeAll(obstacles);
obstacles.addAll(obstaclesInOrder);
score = 0;
isAlive = true;
currentlyPlaying = false;
repaint();
}
#Override
public void actionPerformed(ActionEvent ae) {
update();
repaint();
}
private void update() {
if (isAlive) {
updateBallPosition();
updateObstaclePositions();
if(ballOutOfBounds() || playerCollidedWithObstacle()) {
endGame();
} else if(ballPassedObstacle()) {
addToScore();
setupNextObstacle();
}
}
}
private void updateBallPosition() {
if (readyToJump) {
readyToJump = false;
ball.jump();
} else {
ball.fall();
}
}
private void updateObstaclePositions() {
for (Obstacle obstacle : obstacles) {
if (obstacle.getX() <= -obstacle.getWidth()) {
obstacle.moveToBack();
continue;
}
obstacle.moveForward();
}
}
private void addToScore() {
scoreLabel.update(Integer.toString(++score));
}
private void setupNextObstacle() {
obstacles.addLast(obstacles.removeFirst());
}
private boolean ballOutOfBounds() {
return ball.getY() >= HEIGHT || ball.getY() <= 0;
}
private boolean ballAtObstacle() {
Obstacle currentObstacle = obstacles.getFirst();
return ball.getX() + ball.getWidth() >= currentObstacle.getX() && ball.getX() <= currentObstacle.getX() + currentObstacle.getWidth();
}
private boolean ballPassedObstacle() {
Obstacle currentObstacle = obstacles.getFirst();
return ball.getX() >= (currentObstacle.getX() + currentObstacle.getWidth());
}
private boolean playerCollidedWithObstacle() {
boolean collided = false;
if(ballAtObstacle()) {
for (Obstacle obstacle : obstacles) {
RoundRectangle2D top = obstacle.getTop();
RoundRectangle2D bottom = obstacle.getBottom();
if (ball.intersects(top.getX(), top.getY(), top.getWidth(), top.getHeight()) || ball.intersects(bottom.getX(), bottom.getY(), bottom.getWidth(), bottom.getHeight())) {
collided = true;
}
}
}
return collided;
}
private Image loadBackgroundImage() {
Image background = null;
URL backgroundPath = getClass().getResource(BACKGROUND_URL);
if(backgroundPath == null) {
background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
} else {
try {
background = ImageIO.read(backgroundPath);
} catch (IOException e) {
e.printStackTrace();
}
}
return background;
}
#Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
g.drawImage(background, 0, 0, null);
ball.paint(g);
for (Obstacle obstacle : obstacles)
obstacle.paint(g);
scoreLabel.paint(g);
messageLabel.paint(g);
}
//...
}
loadBackgroundImage() loads and returns an image. If a problem occurs (image probably isn't there), it returns a black image.
(Most of) The game logic is in the update() method. Although it should all be in there, we can't due to a design flaw (from you using Timer which manages update(), and you start the timer in a listener, therefore we needed some logic in the listener). Your logic should be easy to read, and every execution step should be monitored and set by highest priority to lowest.
First, I check to make sure the ball hasn't collided with anything or gone out of bounds. If one of those things occur, I end the game.
If not, I check to see if the player has passed an obstacle. If the player passes an obstacle, I add to the score:
private void update() {
if (ballOutOfBounds() || playerCollidedWithObstacle()) {
endGame();
} else if (ballPassedObstacle()) {
addToScore();
setupNextObstacle();
}
updateBallPosition();
updateObstaclePositions();
}
I then finally update the positions.
To avoid constantly comparing the player's position and the obstacle's position (to see if the player has passed it), I created a boolean ballAtObstacle() method, which checks if the player is at an obstacle. Only then do I compare positions:
private boolean playerCollidedWithObstacle() {
boolean collided = false;
if (ballAtObstacle()) {
for (Obstacle obstacle : obstacles) {
RoundRectangle2D top = obstacle.getTop();
RoundRectangle2D bottom = obstacle.getBottom();
if (ball.intersects(top.getX(), top.getY(), top.getWidth(), top.getHeight()) || ball.intersects(bottom.getX(), bottom.getY(), bottom.getWidth(), bottom.getHeight())) {
collided = true;
}
}
}
return collided;
}
The ball.intersects method call is a bit messy. I did this so the shape didn't have to be specific, although you could declare the intersects method as boolean intersects(Shape shape).
Finally, I gave it a more flappy bird feel by increasing the fall speed as you fall. When you jump again, it goes back to normal. The longer it takes you to jump, the faster you'll fall. If you don't like this feature, and don't know how to remove it, let me know and I'll show you how.
The other classes involved:
GameLabel.java
public class GameLabel {
private String message;
private Font font;
private Color color;
private int x, y;
public GameLabel(String message, int x, int y, Color color, Font font) {
update(message, x, y, color, font);
}
public GameLabel(String message, int x, int y) {
this(message, x, y, Color.BLACK, new Font("Matura MT Script Capitals", Font.ROMAN_BASELINE, 20));
}
public GameLabel() {
this("", 0, 0);
}
public void setMessage(String message) {
this.message = message;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setColor(Color color) {
this.color = color;
}
public void setFont(Font font) {
this.font = font;
}
public final void update(String message, int x, int y, Color color, Font font) {
this.message = message;
this.x = x;
this.y = y;
this.color = color;
this.font = font;
}
public void update(String message, int x, int y) {
update(message, x, y, color, font);
}
public void update(String message) {
update(message, x, y);
}
public void paint(Graphics2D g) {
g.setFont(font);
g.setColor(color);
g.drawString(message, x, y);
}
public Font getFont() {
return font;
}
public Color getColor() {
return color;
}
public String getMessage() {
return message;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Obstacle.java
public class Obstacle {
public static final int DEFAULT_TOP_HEIGHT = 175;
public static final int DEFAULT_BOTTOM_HEIGHT = 175;
public static final int DEFAULT_WIDTH = 30;
public static final int DEFAULT_ARCH_WIDTH = 20;
public static final int DEFAULT_ARCH_HEIGHT = 20;
public static final int DEFAULT_TOP_INSET = -5;
public static final int DEFAULT_BOTTOM_INSET = TheGame.HEIGHT + 5;
private RoundRectangle2D top, bottom;
private BasicStroke stroke;
private GradientPaint gradient;
private int initialX, x, width;
public Obstacle(int x, int width, int topHeight, int bottomHeight) {
this.x = initialX = x;
this.width = width;
top = new RoundRectangle2D.Double(x, DEFAULT_TOP_INSET, width, topHeight, DEFAULT_ARCH_WIDTH, DEFAULT_ARCH_HEIGHT);
bottom = new RoundRectangle2D.Double(x, DEFAULT_BOTTOM_INSET-bottomHeight, width, bottomHeight, DEFAULT_ARCH_WIDTH, DEFAULT_ARCH_HEIGHT);
stroke = new BasicStroke(10, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL, 20.0f, new float[] { 10.0f }, 0.0f);
gradient = new GradientPaint(20, 0, Color.DARK_GRAY, 0, 10, Color.GRAY, true);
}
public Obstacle(int x, int topHeight, int bottomHeight) {
this(x, DEFAULT_WIDTH, topHeight, bottomHeight);
}
public void reset() {
x = initialX;
top.setRoundRect(initialX, top.getY(), top.getWidth(), top.getHeight(), top.getArcWidth(), top.getArcHeight());
bottom.setRoundRect(initialX, bottom.getY(), bottom.getWidth(), bottom.getHeight(), bottom.getArcWidth(), bottom.getArcHeight());
}
public Obstacle(int x, int width) {
this(x, width, DEFAULT_TOP_HEIGHT, DEFAULT_BOTTOM_HEIGHT);
}
public Obstacle(int x) {
this(x, DEFAULT_WIDTH);
}
public void moveToBack() {
x = 600;
}
public void moveForward() {
x -= 5;
top.setRoundRect(x, top.getY(), top.getWidth(), top.getHeight(), top.getArcWidth(), top.getArcHeight());
bottom.setRoundRect(x, bottom.getY(), bottom.getWidth(), bottom.getHeight(), bottom.getArcWidth(), bottom.getArcHeight());
}
public RoundRectangle2D getTop() {
return top;
}
public RoundRectangle2D getBottom() {
return bottom;
}
public int getX() {
return x;
}
public int getWidth() {
return width;
}
public void paint(Graphics2D g) {
g.setPaint(gradient);
g.setStroke(stroke);
g.fill(top);
g.fill(bottom);
}
}
Ball.java
public class Ball {
public static final int DEFAULT_DROP_SPEED = 7;
private Ellipse2D ball;
private GradientPaint gradient;
private int initialY, x, y, width = 30, height = 30, dropSpeed = DEFAULT_DROP_SPEED;
public Ball(int x, int y) {
this.x = x;
this.y = initialY = y;
width = height = 30;
ball = new Ellipse2D.Double(x, y, width, height);
gradient = new GradientPaint(30, 0, Color.BLACK, 0, 20, Color.GREEN, true);
}
public void reset() {
y = initialY;
updateBall();
}
public void jump() {
dropSpeed = DEFAULT_DROP_SPEED;
y -= 40;
updateBall();
}
public void fall() {
y += dropSpeed++;
updateBall();
}
private void updateBall() {
ball.setFrame(x, y, width, height);
}
public boolean intersects(double x, double y, double w, double h) {
return ball.intersects(x, y, w, h);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return width;
}
public void paint(Graphics2D g) {
g.setPaint(gradient);
g.fill(ball);
}
public void moveForward() {
x += 7;
}
}
Reinitialize all the components by adding the initialization code to one method(resetAll) and call that method when u want to reinitailize
Below is an example:
import java.awt.*;
import java.awt.event.*;
public class ResetTest extends Frame{
Button b;
TextField tf;
Frame f;
Panel p;
public ResetTest(){
f=this; //intialize frame f to this to have access to our frame in event handler methods
resetAll(); //first time call to resetAll will initialize all the parameters of the frame
f.pack();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
this.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
this.setVisible(true);
}
/**
This method will be called on click of button to
reset all the parameters of the frame so that we
get fresh new frame, everything as it was before.
**/
public void resetAll(){
b=new Button("Reset");
p=new Panel(new FlowLayout(FlowLayout.CENTER,20,20));
p.add(b);
tf = new TextField("Edit And Reset");
p.add(tf);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
remove(p); //remove the panel that contains all our components
resetAll(); // reset all the components
f.pack(); //refreshes the view of frame when everything is reset.
}
});
add(p);
}
}
class NewClass{
public static void main(String[] args) {
ResetTest fReset = new ResetTest();
}
}

JFrame background color flashes but then reverts

Lately I've been attempting to replicate Space Invaders in java to help with learning about developing applications with java and the programming language in general. However I've run into a little problem with JFrame: the background color that I declared for the window doesn't stay, it just flashes and then reverts to the default. Here's my code:
import javax.imageio.ImageIO;`
import java.io.*;`
import javax.swing.*;`
import java.awt.*;`
import java.awt.image.*;`
import java.awt.image.ImageObserver;`
import java.awt.event.*;`
public class Invaders extends JPanel{
public static int x = 40;
public static int y = 345;
public static int h = 20;
public static int k = 180;
public static int move = 1;
static final Invaders m = new Invaders();
public static void main(String[] args){
final JFrame frame = new JFrame("Movement of 2d Shapes");
frame.setSize(404,390);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(m);
frame.setBackground(Color.BLACK);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Action actionRight = new AbstractAction(){
public void actionPerformed(ActionEvent actionRightEvent){
if(x <= 350){
x += 10;
m.repaint();
};
}
};
Action actionLeft = new AbstractAction(){
public void actionPerformed(ActionEvent actionLeftEvent){
if(x >= 10){
x -= 10;
m.repaint();
};
}
};
KeyStroke right = KeyStroke.getKeyStroke("RIGHT");
KeyStroke left = KeyStroke.getKeyStroke("LEFT");
InputMap inputMap = m.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(right, "RIGHT");
inputMap.put(left, "LEFT");
m.getActionMap().put("RIGHT", actionRight);
m.getActionMap().put("LEFT", actionLeft);
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
draw(g);
cpu_move(m);
}
public void cpu_move(Invaders m){
if(h == 0){
move = 0;
}else if(h == 375){
move = 1;
}
if(move == 0){
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
h += 5;
m.repaint();
}else if(move == 1){
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
h -= 5;
m.repaint();
};
}
public void draw(Graphics g){
try{
g.drawImage(ImageIO.read(getClass().getResource(
"images/Ship.jpg")), x, y, 35, 23, Color.BLACK, null);
g.drawImage(ImageIO.read(getClass().getResource(
"images/Alien.jpg")), h, k, 28, 20, Color.BLACK, null);
}catch(IOException k){
Component temporaryLostComponent = null;
JOptionPane.showMessageDialog(temporaryLostComponent,
"one or more image files missing or corrupt");
}
}
}
What's wrong with the declaration of the background color? there are no errors when compiling, but it still does this. What am I doing wrong?
Try next :
frame.getContentPane().add(m);
m.setBackground(Color.BLACK);
instead of frame.setBackground(Color.BLACK); because Invaders m fills all frame.
Your backgound will be black with image.
frame.getContentPane().add(m);
//frame.setBackground(Color.BLACK);
frame.getContentPane().setBackground( Color.BLACK );
Read the section from the Swing tutorial on Using Top Level Containters to understand the structure of a frame. The content pane is painted on top of the frame.

java jlabel click / drag

The blue label is meant to move when you click and drag it. This works but the x / y position then jumps in a funny way.
Here's the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class test extends JFrame implements MouseListener, MouseMotionListener {
private JPanel panel = new JPanel(null);
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
private int mouseX = 200;
private int mouseY = 100;
private boolean drag = false;
public test() {
this.add(panel);
panel.setBackground(Color.WHITE);
panel.add(label1);
label1.setOpaque(true);
label1.setBackground(Color.BLUE);
label1.setBounds(mouseX, mouseY, 100, 50);
label1.addMouseMotionListener(this);
label1.addMouseListener(this);
panel.add(label2);
label2.setOpaque(true);
label2.setBackground(Color.RED);
label2.setBounds(mouseX + 200, mouseY, 100, 50);
label2.addMouseMotionListener(this);
label2.addMouseListener(this);
}
#Override
public void mousePressed(MouseEvent e) {
if (e.getSource() == label1) {
drag = true;
}
}
#Override
public void mouseReleased(MouseEvent e) {
drag = false;
}
#Override
public void mouseDragged(MouseEvent e) {
if (drag == true) {
mouseX = e.getX();
mouseY = e.getY();
label1.setBounds(mouseX, mouseY, 100, 50);
}
}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public static void main(String[] args) {
test frame = new test();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Just put this on your MouseDragged method:
public void mouseDragged(MouseEvent e)
{
if (drag == true)
{
JComponent jc = (JComponent)e.getSource();
jc.setLocation(jc.getX()+e.getX(), jc.getY()+e.getY());
}
}
The coordinates returned by MouseEvent::getX() and MouseEvent::getY() represent the location of the event relative to the event's subject (i.e. relative to the label itself), which explains why your solution results in the label erratically jumping.
By using MouseEvent::getComponent() to grab the label and then querying its position (possibly relative to the position when dragging commenced), you can devise a working solution.
Your problem is your setting your bounds based on the mouse location in the MouseListener, but the MouseListener has its location relative to the JLabel itself, but the JLabel's location should be set relative to the panel. You'll need to do some simple vector addition to figure this out.
edit: oops, I didn't see that this was already answered, and they say the same thing... sorry.
Maybe try adding something like that
The red one will do it better
private int clicX = 0;
private int clicY = 0;
public void mousePressed(MouseEvent e) {
drag = true;
if (e.getSource() == label1) {
}
if (e.getSource() == label2) {
clicX = e.getX();
clicY = e.getY();
}
}
public void mouseDragged(MouseEvent e) {
if (e.getSource() == label2) {
JComponent jc = (JComponent)e.getSource();
jc.setLocation(jc.getX()+e.getX()-clicX, jc.getY()+e.getY()-clicY);
}
Create two global variables:
int x_pressed = 0;
int y_pressed = 0;
then create two events (mousePressed and mouseDragged over JLabel):
lbl_banner.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e) {
//catching the current values for x,y coordinates on screen
x_pressed = e.getX();
y_pressed = e.getY();
}
});
lbl_banner.addMouseMotionListener(new MouseMotionAdapter(){
#Override
public void mouseDragged(MouseEvent e){
//and when the Jlabel is dragged
setLocation(e.getXOnScreen() - x_pressed, e.getYOnScreen() - y_pressed);
}
});

Categories

Resources