This is my code, I want to add functionality to the Rect that I made, like when you click on it, a window pops up
public class codetwo extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.LIGHT_GRAY);
g.setColor(Color.RED);
g.fillRect(110,110, 120, 120);
}
public static void main(String args[]) {
codetwo cd = new codetwo();
JFrame frame = new JFrame("Title");
frame.add(cd);
frame.setSize(440,350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You need to use Mouselistener for this.
public class codetwo extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.LIGHT_GRAY);
g.setColor(Color.RED);
g.fillRect(110,110, 120, 120);
}
public static void main(String args[]) {
codetwo cd = new codetwo();
cd.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if (e.getX() >= 110 && e.getX() <= 230 && e.getY() >= 110 && e.getY() <= 230) {
JOptionPane.showMessageDialog(cd, "Some one clicked here ?", "Listening", JOptionPane.INFORMATION_MESSAGE);
}
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
JFrame frame = new JFrame("Title");
frame.add(cd);
frame.setSize(440,350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Related
I'm attempting to use KeyListener to interact with the arrow keys, when I run it, it doesn't give me an error, but the rectangle I am trying to move left or right does not move. Am I missing something? I'm trying to simulate the game for bricks, so My only issue right now is getting the panel to move across the screen
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
import org.w3c.dom.css.Rect;
public class tools extends JPanel implements KeyListener, ActionListener {
Timer t = new Timer(5,this);
double x = 350, y=920,velx=0,vely=0;
public tools() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D)g;
g.setColor(Color.BLUE);
g2.fill(new Ellipse2D.Double(x, y, 300, 10));
//ball
/*
g.setColor(Color.WHITE);
g.fillOval(350, 700, 20, 20);
*/
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
x+= velx;
y+= vely;
}
public void left() {
velx = -1.5;
vely=0;
}
public void right() {
velx=1.5;
vely=0;
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
right();
}
else if(keyCode == KeyEvent.VK_LEFT)
{
left();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
You need to call repaint() to redraw the canvas. Have a look at the example below.
public class Bricks extends JPanel implements KeyListener, ActionListener {
Timer t = new Timer(5, this);
double x = 150, y = 320, velx = 0, vely = 0;
public Bricks() {
t.start();
setFocusable(true);
requestFocus();
addKeyListener(this);
//setFocusTraversalKeysEnabled(false);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.BLUE);
g2.fill(new Ellipse2D.Double(x, y, 300, 10));
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
x += velx;
y += vely;
}
public void left() {
velx = -1.5;
vely = 0;
}
public void right() {
velx = 1.5;
vely = 0;
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_RIGHT) {
System.out.println("RIGHT");
right();
repaint();
} else if (keyCode == KeyEvent.VK_LEFT) {
System.out.println("LEFT");
left();
repaint();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Bricks bricks = new Bricks();
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(1078, 800);
frame.getContentPane().add(bricks, BorderLayout.CENTER);
}
});
}
}
I am trying to create some kind of Paint program. I created a BufferedImage and an Graphics2D but i cant draw on it. All what I can see is the BufferedImage itself without any changes.
public class paintapp implements ActionListener, MouseListener, MouseMotionListener
{
public static final int WIDTHBUFF=300;
public static final int HEIGHTBUFF=300;
BufferedImage buffimage=new BufferedImage(WIDTHBUFF,HEIGHTBUFF,BufferedImage.TYPE_INT_BGR);
JLabel imagelabel=new JLabel(new ImageIcon(buffimage));
int s=3;
Color curr_color=Color.BLACK;
int x,y;
public static final int WIDTH=700;
public static final int HEIGHT=700;
public paintapp()
{
Graphics2D g2d=buffimage.createGraphics();
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, WIDTHBUFF,HEIGHTBUFF);
JFrame frame=new JFrame("Painter");
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
Panel buttonpanel=new Panel();
Panel colors=new Panel();
Panel draw=new Panel();
draw.add(imagelabel);
frame.add(draw);
frame.pack();
}
public static void main(String[]args)
{
paintapp paint1=new paintapp();
}
#Override
public void mouseDragged(MouseEvent e) {
Graphics2D g2=buffimage.createGraphics();
g2.setColor(curr_color);
g2.setStroke(new BasicStroke(s));
g2.drawLine(x, y, e.getX(), e.getY());
x=e.getX();
y=e.getY();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
x=e.getX();
y=e.getY();
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
I see you are poking through and you got things in jumbled up order. If you read the guides you will see how things go.
The first main thing is to add a MouseMotionListener to the drawing thing - be that JLabel JPanel whatever.
The second thing is that once you go outside of the constructor the JFrame is lost (unless you do some fancy things) and cant be accessed to be refreshed, so the system decides when to refresh and you will see - after you add the mouse listener - that your drawing will appear once you hide and show again the drawing window.
So you need to have JFrame as global - why dont you have you class extend JFrame and so no need to have some extra JFrame.
I am creating a costume component in Model UIDelegate using DrawPad example. However, for some reason I get the error UIDefaults.getUI() failed: no ComponentUI class. I am not even sure if I am implementing Model UIDelegate properly. But why am I getting that error?
Main
public class Main {
static JFrame frame;
static JButton clearButton;
static DrawPad drawPad;
public static void main(String[] args) {
UIManager.put("DrawPadUI", "BasicDrawPadUI");
frame = new JFrame();
drawPad = new DrawPad();
clearButton = new JButton("Clear");
frame.add(drawPad, BorderLayout.CENTER);
clearButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Graphics g = frame.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
}
});
frame.add(clearButton, BorderLayout.SOUTH);
frame.setSize(280, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
BasicDrawPadUI
public class BasicDrawPadUI extends ComponentUI implements MouseListener, MouseMotionListener {
Image image;
Graphics2D graphics2D;
int currentX, currentY, oldX, oldY;
JFrame frame;
JButton clearButton;
public static ComponentUI createUI(JComponent c) {
return new BasicDrawPadUI();
}
public void paintComponent(Graphics g, JComponent c) {
if (image == null) {
image = c.createImage(c.getWidth(), c.getHeight());
graphics2D = (Graphics2D) image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
clear(c);
}
g.drawImage(image, 0, 0, null);
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
currentX = e.getX();
currentY = e.getY();
if (graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
//repaint();
oldX = currentX;
oldY = currentY;
}
public void clear(JComponent c) {
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, c.getWidth(), c.getHeight());
graphics2D.setPaint(Color.black);
c.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
oldX = e.getX();
oldY = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
DrawPad
class DrawPad extends JComponent {
private final static String ID = "DrawPadUI";
public DrawPad() {
updateUI();
}
public void updateUI() {
setUI(UIManager.getUI(this));
}
#Override
public String getUIClassID() {
return ID;
}
}
Change UIManager.put("DrawPadUI", "BasicDrawPadUI"); to UIManager.put("DrawPadUI", "drawpad.BasicDrawPadUI");
You need to specify the full qualified class name of the UI class, including the package name
I'll need to have a look to be sure, but when it calls createUI, you could grab a reference to the component
Override the installUI method from ComponentUI and when it's called, maintain a reference to the component that is passed to you.
private DrawPad drawPad;
//...
#Override
public void installUI(JComponent c) {
drawPad = (DrawPad) c;
// Install required listeners and other functionality
}
Equally, in uninstallUI, you should dereference any strong references you have and uninstall your listeners
#Override
public void uninstallUI(JComponent c) {
// Uninstall any listeners
drawPad = null;
}
Have a look at custom java Swing component Model, UIDelegate, component format for a complete implementation.
Also, you should NEVER maintain a reference to a Graphics2D context that you did not create yourself
I have no Idea why my JFrame keeps freezeing after I type Letters into the JTextField "Username" and "Password" :/ Could anyone look thru my code and tell my why and fix it please ?
public class Main
{
public static void main(String [ ] args)
{
LoginWindow loginframe = new LoginWindow();
loginframe.setVisible(true);
loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginframe.initialize();
while(true)
{
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
loginframe.Repaint();
}
}
}
FrameClass:
public class LoginWindow extends JFrame implements MouseListener, KeyListener, MouseMotionListener{
public LoginWindow(){
setSize(806, 629);
setResizable(false);
setLayout(new BorderLayout());
background = new JLabel(ResourceLoader.Iconload("/main_01.jpg"));
background.setBounds(0, 0, 800, 600);
add(background);
background.setLayout(null);
Username = new JTextField("", 20);
Username.setForeground(Color.WHITE);
Username.setBounds(312, 433, 170, 40);
Username.setFont(new Font("Impact", Font.BOLD, 25));
Username.setBackground(Color.BLACK);
Username.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.BLACK));
background.add(Username);
Password = new JPasswordField("", 20);
Password.setForeground(Color.WHITE);
Password.setBounds(312, 489, 170, 40);
Password.setBackground(Color.BLACK);
Password.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.BLACK));
Password.setFont(new Font("Serif", Font.BOLD, 25));
background.add(Password);
}
public void initialize()
{
makestrat();
addKeyListener(this);
requestFocus();
addMouseListener(this);
addMouseMotionListener(this);
}
public void makestrat()
{
createBufferStrategy(2);
strat = getBufferStrategy();
}
public void Repaint()
{
//System.out.println(mouseX + " " + mouseY);
Graphics g = strat.getDrawGraphics();
paintComponents(g);
Draw(g);
g.dispose();
strat.show();
}
public void Update()
{
}
public void Draw(Graphics g)
{
if(((mouseX >= 499) && (mouseX <= 669)) && ((mouseY >= 433)&&( mouseY <= 530))){
g.drawImage(ResourceLoader.ImageLoad("/login_02.jpg"), 502, 459, null);
}else{
g.drawImage(ResourceLoader.ImageLoad("/login_01.jpg"), 502, 459, null);
}
}
private class thehandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
}
}
public void mouseMoved(MouseEvent event)
{
mouseY = event.getY()-26;
mouseX = event.getX()-3;
}
#Override
public void mouseClicked(MouseEvent e) {
PointerInfo a = MouseInfo.getPointerInfo();
Point point = new Point(a.getLocation());
SwingUtilities.convertPointFromScreen(point, e.getComponent());
double mouseX = (int) point.getX();
double mouseY = (int) point.getY();
System.out.println("(ContainerPos) Mouse clicked! X: " + mouseX + " Y: " + mouseY);
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
You don't need the while loop with the Thread.sleeap(). It's screwing with your program.
What you're trying to achieve here, a call to repaint continuously, can easily be accomplished with a javax.swing.Timer
Don't explicitly call paintComponent. An actual call to the real repaint() method will do that for you. No need to create an imitation Repaint()
Use a JPanel for painting instead of trying to paint on a JFrame
I would initialize, then set visible
Your code doesn't even compilable, so I can try and make fixes for you.
Use Java naming convention: methods and variable start with lower case letters.
Here's an example of a simple Login Window, using a modal JDialog
Learn how to use Layout Managers instead of relying on setBounds()
Point 2. Your main should look like this
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
LoginWindow loginframe = new LoginWindow();
loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginframe.initialize();
loginframe.setVisible(true);
}
});
}
And in your constructor, have a javax.swing.Timer instead of your while loop
private Timer timer = null;
private DrawPanel drawPanel = new DrawPanel(); // see below for DrawPanel
public LoginWindow() {
// add drawPanel somewhere
...
timer = new Timer (50, new ActionListener(){
public void actionPerformed(ActionEvent e) {
drawPanel.repaint();
}
});
timer.start();
}
Point 4. Have an inner JPanel class that you do all your painting in, and add that component to the frame. You'll need to override the paintComponent method.
private DrawPanel extends JPanel {
#Override
protected void paintComponent(Graophics g) {
super.paintComponent(g);
Draw(g);
}
}
The obvious thing is that you shouldn't use Swing (or AWT really) off of the AWT Event Dispatch Thread (EDT). Fix with java.awt.EventQueue.invokeLater and java.swing.Timer (not java.util!). Diagnose with jstack(and jps) or the relevant key sequence in the terminal window (um, ctrl-break in Windows, ctrl-3 in Linux).
I have a menu button that is supposed to transition into the game state once you click on it, but it won't work. Here is my MouseInput class. Ignore all of the methods except for the MousePressed method.
package com.game.src.main;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseInput implements MouseListener
{
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e)
{
int mx = e.getX();
int my = e.getY();
/**
public Rectangle playButton = new Rectangle(Game.WIDTH/2 + 120, 150, 100, 50);
public Rectangle helpButton = new Rectangle(Game.WIDTH/2 + 120, 250, 100, 50);
public Rectangle quitButton = new Rectangle(Game.WIDTH/2 + 120, 350, 100, 50);
*/
if (mx >= Game.WIDTH/2 + 120 && mx <= Game.WIDTH/2 + 220)
{
if (my >= 150 && mx <= 200)
Game.State = Game.STATE.GAME;
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
Here is the init method, which is part of the Game class. I bolded and italicized the line of code where I supposedly use the addMouseListener method to enable the mouse functionality (but clearly it doesn't work).
public static enum STATE
{
MENU,
GAME
};
public static STATE State = STATE.MENU;
public void init()
{
requestFocus();
BufferedImageLoader loader = new BufferedImageLoader();
try
{
spriteSheet = loader.loadImage("/spritesheettemplate.png");
background = loader.loadImage("/bkg.png");
}
catch(IOException e)
{
e.printStackTrace();
}
addKeyListener(new KeyInput(this));
***addMouseListener(new MouseInput());***
tex = new Textures(this);
p = new Player(WIDTH/2*SCALE - 16, HEIGHT/2*SCALE - 16, tex);
c = new Controller(this, tex);
menu = new Menu();
eA = c.getEntityA();
eB = c.getEntityB();
c.addEnemy(enemyCount);
}
Any help would be greatly appreciated. This is the final step in my game. I'm following a tutorial series on Youtube, but the uploader never responds to questions, so you guys are my only hope (I guess I'm being a little dramatic). If you need me to post more parts of my code, I can do that.
Just add an ActionListener to that menu button without dealing with MouseListener.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Game.State = Game.STATE.GAME;
}
});