Related
I want to write a custom subclass of JLabel that would have two images attached to the border, that can be moved by moving the mouse. Real effects like this:
Here's my subclass, how could I add these attached images?
public class Rect extends JLabel{
private int width,height;
public Rect (int width,int height){
this.width = width;
this.height = height;
setText("b1");
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(0, 0, this.width, this.height);
}
public void reDraw(){
this.repaint();
}
public void setWidth(int width) {
this.width = width;
repaint();
}
public void setHeight(int height) {
this.height = height;
repaint();
}
}
To do this there are 4 things you should to do:
Extend an AbstractBorder not a Jlabel, then you can easily add your custom border to any component, not just a jLabel.
Override the paintBorder method so that you can draw your border.
Add an mouse action listeners to keep track of your border images.
And lastly you need a bit of logic to manage your border images.
I found this question interesting so I took a crack at making something as a test. It came out well, and does what you want, but will need a bit of work to get it looking correct. See below for a break down of each point.
Example image before we look at the code:
Extend an AbstractBorder:
public class MyCustomBorder extends AbstractBorder
{
private Color borderColour;
private int borderThickness = 10;
private Point firstSlider = new Point(0, 0);
private Point secondSlider = new Point(0, 0);
private BufferedImage firstSliderImage;
private BufferedImage secondSliderImage;
Boolean draggingFirst = false;
Boolean draggingSecond = false;
//See usage info
public MyCustomBorder(Color colour, int thickness, Point firstSlider, BufferedImage firstSliderImage, Point secondSlider, BufferedImage secondSliderImage)
{
borderColour = colour;
borderThickness = thickness;
this.firstSlider = firstSlider;
this.secondSlider = secondSlider;
this.firstSliderImage = firstSliderImage;
this.secondSliderImage = secondSliderImage;
}
Override the paintBorder method and insets:
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
{
super.paintBorder(c, g, x, y, width, height);
Graphics2D g2d = null;
if (g instanceof Graphics2D)
{
g2d = (Graphics2D) g;
//Draw border fill (currently hard coded to white, but can be changed)
g2d.setColor(Color.white);
//Top
g2d.fill(new Rectangle2D.Double(0, 0, width, borderThickness));
//Left
g2d.fill(new Rectangle2D.Double(0, 0, borderThickness, height));
//Bottom
g2d.fill(new Rectangle2D.Double(0, height-borderThickness, width, borderThickness));
//Right
g2d.fill(new Rectangle2D.Double(width-borderThickness, 0, borderThickness, height));
//draw black seperator
g2d.setColor(borderColour);
//Top
g2d.fill(new Rectangle2D.Double(borderThickness, borderThickness, width-(borderThickness*2), 1));
//Left
g2d.fill(new Rectangle2D.Double(borderThickness, borderThickness, 1, height-(borderThickness*2)));
//Bottom
g2d.fill(new Rectangle2D.Double(borderThickness, height-borderThickness-1, width-(borderThickness*2), 1));
//Right
g2d.fill(new Rectangle2D.Double(width-borderThickness-1, borderThickness, 1, height-(borderThickness*2)));
//draw sliders an custom position
g2d.drawImage(scale(secondSliderImage), null, secondSlider.x, secondSlider.y);
g2d.drawImage(scale(firstSliderImage), null, firstSlider.x, firstSlider.y);
}
}
#Override
public Insets getBorderInsets(Component c)
{
return (getBorderInsets(c, new Insets(borderThickness, borderThickness, borderThickness, borderThickness)));
}
#Override
public Insets getBorderInsets(Component c, Insets insets)
{
insets.left = insets.top = insets.right = insets.bottom = borderThickness;
return insets;
}
#Override
public boolean isBorderOpaque()
{
return false;
}
}
Add mouse action listeners:
//listeners for dragging
void addListeners(Component button)
{
button.addMouseMotionListener(new java.awt.event.MouseMotionAdapter()
{
public void mouseDragged(java.awt.event.MouseEvent evt)
{
//Only drag if a slider was selected
if (draggingFirst)
{
//update position of silder
firstSlider = snapToEdge(evt.getPoint(), evt.getComponent());
evt.getComponent().repaint();
}
else if (draggingSecond)
{
//update position of silder
secondSlider = snapToEdge(evt.getPoint(), evt.getComponent());
evt.getComponent().repaint();
}
}
});
button.addMouseListener(new java.awt.event.MouseAdapter()
{
//check if a slider was selected
public void mousePressed(java.awt.event.MouseEvent evt)
{
if (isInside(evt.getPoint(), firstSlider))
{
draggingFirst = true;
}
else if (isInside(evt.getPoint(), secondSlider))
{
draggingSecond = true;
}
}
public void mouseReleased(java.awt.event.MouseEvent evt)
{
//cancel selected slider
draggingFirst = false;
draggingSecond = false;
}
});
}
Logic:
//check if a slider was selected
private Boolean isInside(Point clicked, Point toCheck)
{
if (clicked.x > toCheck.x && clicked.x < toCheck.x + borderThickness)
{
if (clicked.y > toCheck.y && clicked.y < toCheck.y + borderThickness)
{
return true;
}
}
return false;
}
//snap a sliders co-ords to as edge
private Point snapToEdge(Point dragged, Component label)
{
//work out how close to each edge
int topEdge = dragged.y;
int leftEdge = dragged.x;
int rightEdge = label.getWidth()- dragged.x;
int bottomEdge = label.getHeight() - dragged.y;
//snap to slider co-ords to closest edge
if (topEdge < leftEdge && topEdge < rightEdge && topEdge < bottomEdge)
{
dragged.y = 0;
}
else if (leftEdge < rightEdge && leftEdge < bottomEdge)
{
dragged.x = 0;
}
else if (rightEdge < bottomEdge)
{
dragged.x = label.getWidth()-borderThickness;
}
else
{
dragged.y = label.getHeight()-borderThickness;
}
return dragged;
}
//scale slider images to fit border size
public BufferedImage scale(BufferedImage image)
{
BufferedImage resizedImage = null;
if (image != null)
{
double border = borderThickness;
resizedImage = new BufferedImage(borderThickness, borderThickness, TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance(border / (double)image.getWidth(), border / (double)image.getHeight());
g.drawRenderedImage(image, at);
}
return resizedImage;
}
The full code to copy and paste can be found here:
https://github.com/sorifiend/customBorder/blob/master/MyCustomBorder.java
Usage Example:
You can put this code in your form class to add a border to most swing components. In this example I added it to a jLabel called my_jLabel:
//Create border
MyCustomBorder border = new MyCustomBorder(Color.BLACK, 10, new Point(0, 0), img1, new Point(0, 0), img2);
//Add border to component called my_jLabel
my_jLabel.setBorder(border);
//Add action listeners for dragging sliders (very important)
border.addListeners(my_jLabel);
I'm kinda new to java and have been trying to make a simple paint program, I have gotten everything to work except the color of the paint brush. Rigth now I set the color to blue but I want to make the color of the paint brush the same color as the color selected by the color slider.
Here's the code I got so far
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Paint extends JFrame implements ChangeListener{
PaintPanel color;
PaintPanel2 paint;
JSlider red;
JSlider green;
JSlider blue;
public Paint(){
super("Paint");
setSize(300,290);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
color = new PaintPanel();
paint = new PaintPanel2();
red = new JSlider(0,255,255);
green = new JSlider(0,255,0);
blue = new JSlider(0,255,0);
red.setMajorTickSpacing(50);
red.setMinorTickSpacing(10);
red.setPaintTicks(true);
red.setPaintLabels(true);
red.addChangeListener(this);
green.setMajorTickSpacing(50);
green.setMinorTickSpacing(10);
green.setPaintTicks(true);
green.setPaintLabels(true);
green.addChangeListener(this);
blue.setMajorTickSpacing(50);
blue.setMinorTickSpacing(10);
blue.setPaintTicks(true);
blue.setPaintLabels(true);
blue.addChangeListener(this);
JLabel redLabel = new JLabel("Red: ");
JLabel greenLabel = new JLabel("Green: ");
JLabel blueLabel = new JLabel("Blue: ");
GridLayout grid = new GridLayout(5,1);
FlowLayout flow = new FlowLayout(FlowLayout.RIGHT);
setLayout(grid);
JPanel redPanel = new JPanel();
redPanel.setLayout(flow);
redPanel.add(redLabel);
redPanel.add(red);
add(redPanel);
JPanel greenPanel = new JPanel();
greenPanel.setLayout(flow);
greenPanel.add(greenLabel);
greenPanel.add(green);
add(greenPanel);
JPanel bluePanel = new JPanel();
bluePanel.setLayout(flow);
bluePanel.add(blueLabel);
bluePanel.add(blue);
add(bluePanel);
add(color);
add(paint);
setVisible(true);
}
public void stateChanged(ChangeEvent e){
JSlider source = (JSlider) e.getSource();
if(source.getValueIsAdjusting() != true){
Color mainColor = new Color(red.getValue(),
green.getValue(),
blue.getValue());
color.changeColor(mainColor);
color.repaint();
}
}
public static void main(String[] args){
Paint p = new Paint();
}
}
class PaintPanel extends JPanel{
Color background;
public PaintPanel(){
background = Color.red;
}
public void paintComponent(Graphics comp){
Graphics2D comp2D = (Graphics2D) comp;
comp2D.setColor(background);
comp2D.fillRect(0,0,getSize().width,getSize().height);
}
void changeColor(Color newBackground){
background = newBackground;
}
}
class PaintPanel2 extends JPanel{
Image image;
Graphics2D comp2D;
int currentX, currentY, oldX, oldY;
PaintPanel color;
public PaintPanel2(){
color = new PaintPanel();
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentX = e.getX();
currentY = e.getY();
if(comp2D != null)
comp2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
});
}
public void paintComponent(Graphics comp){
if(image == null){
image = createImage(getSize().width, getSize().height);
comp2D = (Graphics2D)image.getGraphics();
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
comp2D.setPaint(Color.white);
comp2D.fillRect(0, 0, getSize().width, getSize().height);
comp2D.setPaint(Color.blue);
repaint();
}
comp.drawImage(image, 0, 0, null);
}
}
The problem was that you weren't setting the chosen color in PaintPanel2. I changed the stateChanged method and the PaintPanel2 as follows, and now it works as I assume you intended:
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (source.getValueIsAdjusting() != true) {
Color mainColor = new Color(red.getValue(),
green.getValue(),
blue.getValue());
color.changeColor(mainColor);
paint.setPaintColor(mainColor);
color.repaint();
}
}
class PaintPanel2 extends JPanel {
Image image;
Graphics2D comp2D;
int currentX, currentY, oldX, oldY;
public PaintPanel2() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
if (comp2D != null) {
comp2D.drawLine(oldX, oldY, currentX, currentY);
}
repaint();
oldX = currentX;
oldY = currentY;
}
});
}
public void paintComponent(Graphics comp) {
if (image == null) {
image = createImage(getSize().width, getSize().height);
comp2D = (Graphics2D) image.getGraphics();
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
comp2D.setPaint(Color.white);
comp2D.fillRect(0, 0, getSize().width, getSize().height);
comp2D.setPaint(Color.blue);
repaint();
}
comp.drawImage(image, 0, 0, null);
}
public void setPaintColor(Color color) {
comp2D.setColor(color);
}
}
I have a JPanel with the code here. I want the panel to zoom in towards the center of what's in the panel when I scroll with the mousewheel. Currently, whenever I zoom in/out with the mouse wheel, the corner in the top left of the image stays in the same place. I've had a difficult time finding a correct algorithm.
To zoom into the picture, the code uses an AffineTransform object which scales the image according to a double value which increases or decreases based on the movement of the mouse wheel.
What also adds to the complexity is that the image can also be clicked and dragged around the panel. If it is clicked and dragged, the zoom must still zoom in on what's in the center of the PANEL, and not the center of the actual image necessarily.
Once again, the zooming should be done relative to the center point of the currently visible area. That is, as zooming occurs, the point at the center of the view should remain fixed.
This is the code (and it's executable):
package clientgui;
import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.swing.border.TitledBorder;
public class MoveImageExample extends JFrame {
ShowCanvas canvas;
public MoveImageExample() throws Exception {
super();
Container container = getContentPane();
canvas = new ShowCanvas(
"http://cdn.smosh.com/sites/default/files/bloguploads/funny-iphone-5-bruce-lee.jpg");
container.setPreferredSize(new Dimension(canvas.getWidth(), canvas
.getHeight()));
System.out.println("width = " + canvas.getWidth() + " height = "
+ canvas.getHeight());
container.add(canvas);
pack();
setVisible(true);
}
public static void main(String arg[]) throws Exception {
new MoveImageExample();
}
}
#SuppressWarnings("serial")
class ShowCanvas extends JPanel {
int imageX = 0, imageY = 0;
int lastMouseX = 0, lastMouseY = 0;
int centerX = 225;
int centerY = 225;
int canvasWidth = 450;
int canvasHeight = 450;
double scaleFactor = 1.0;
boolean firstMouseDrag = true;
BufferedImage image;
public ShowCanvas(String imagePath) throws Exception {
setBackground(Color.white);
MouseMotionHandler mouseHandler = new MouseMotionHandler();
addMouseMotionListener(mouseHandler);
addMouseListener(mouseHandler);
addMouseWheelListener(mouseHandler);
URL url = new URL(imagePath);
Image rawImage = ImageIO.read(url);
image = new BufferedImage(rawImage.getWidth(this),
rawImage.getHeight(this), BufferedImage.TYPE_INT_ARGB);
setSize(image.getWidth(), image.getHeight());
Graphics2D g2 = image.createGraphics();
g2.drawImage(rawImage, imageX, imageY, this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(Color.gray);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
AffineTransform transformer = new AffineTransform();
// translate the image back (using new scale factor)
transformer.scale(scaleFactor, scaleFactor); // scale by 2x on x and y
// axes.
transformer.translate(imageX / scaleFactor, imageY / scaleFactor);
g2D.drawImage(image, transformer, this);
}
class MouseMotionHandler extends MouseMotionAdapter implements
MouseListener, MouseWheelListener {
public void mousePressed(MouseEvent e) {
lastMouseX = e.getX();
lastMouseY = e.getY();
}
public void mouseDragged(MouseEvent e) {
int xDiff = e.getX() - lastMouseX;
int yDiff = e.getY() - lastMouseY;
imageX = imageX + xDiff;
imageY = imageY + yDiff;
lastMouseX = e.getX();
lastMouseY = e.getY();
repaint();
}
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
scaleFactor = scaleFactor + notches / 10.0;
if (scaleFactor < 0.5) {
scaleFactor = 0.5;
} else if (scaleFactor > 3.0) {
scaleFactor = 3.0;
}
repaint();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
}
}
So, the basic idea, is when you change the scale, rather then allowing the entire change to be added/subtracted from the width/height, you need to divide it between the location and the size...
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
// Get the current/old size...
double oldWidth = image.getWidth() * scaleFactor;
double oldHeight = image.getHeight() * scaleFactor;
scaleFactor = scaleFactor + notches / 10.0;
if (scaleFactor < 0.5) {
scaleFactor = 0.5;
} else if (scaleFactor > 3.0) {
scaleFactor = 3.0;
}
// Get the new size
double newWidth = image.getWidth() * scaleFactor;
double newHeight = image.getHeight() * scaleFactor;
// Calculate the difference (and divide it by 2)
double difWidth = (oldWidth - newWidth) / 2;
double difHeight = (oldHeight - newHeight) / 2;
// Add it to the image position...
imageX += difWidth;
imageY += difHeight;
revalidate();
repaint();
}
Updated with working example
Okay, so the basic idea is you're dealing with a virtual space, where the image sits. This virtual space has a size (the component size x the scale factor). This allows you to center the virtual space within the actual space.
After that, you simply need to calculate the x/y offset of the virtual space (within the real space) and the virtual location of the image.
In this example, I removed the AffineTransformation#setLocation in favor of generating a scaled instance of the image, it simply made it easier to place the image.
import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.net.URL;
public class MoveImageExample extends JFrame {
ShowCanvas canvas;
public MoveImageExample() throws Exception {
super();
Container container = getContentPane();
canvas = new ShowCanvas(
"http://cdn.smosh.com/sites/default/files/bloguploads/funny-iphone-5-bruce-lee.jpg");
container.add(canvas);
pack();
setVisible(true);
}
public static void main(String arg[]) throws Exception {
new MoveImageExample();
}
}
#SuppressWarnings("serial")
final class ShowCanvas extends JPanel {
int imageX = 0, imageY = 0;
int lastMouseX = 0, lastMouseY = 0;
int centerX = 225;
int centerY = 225;
int canvasWidth = 450;
int canvasHeight = 450;
double scaleFactor = 1.0;
boolean firstMouseDrag = true;
BufferedImage image;
private BufferedImage scaled;
public ShowCanvas(String imagePath) throws Exception {
setBackground(Color.white);
MouseMotionHandler mouseHandler = new MouseMotionHandler();
addMouseMotionListener(mouseHandler);
addMouseListener(mouseHandler);
addMouseWheelListener(mouseHandler);
URL url = new URL(imagePath);
Image rawImage = ImageIO.read(url);
image = new BufferedImage(rawImage.getWidth(this),
rawImage.getHeight(this), BufferedImage.TYPE_INT_ARGB);
setSize(image.getWidth(), image.getHeight());
Graphics2D g2 = image.createGraphics();
g2.drawImage(rawImage, imageX, imageY, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension((int) (image.getWidth()), (int) (image.getHeight()));
}
protected BufferedImage getScaledInstance() {
if (scaled == null) {
int width = (int) (image.getWidth() * scaleFactor);
int height = (int) (image.getHeight() * scaleFactor);
scaled = new BufferedImage(width, height, image.getType());
Graphics2D g2d = scaled.createGraphics();
AffineTransform transformer = new AffineTransform();
transformer.scale(scaleFactor, scaleFactor); // scale by 2x on x and y
g2d.setTransform(transformer);
g2d.drawImage(image, 0, 0, this);
g2d.dispose();
}
return scaled;
}
public Dimension getVirtualSize() {
return new Dimension(
(int)(getWidth() * scaleFactor),
(int)(getHeight() * scaleFactor));
}
public Point getVirtualPoint(int x, int y) {
return new Point(
(int)(x * scaleFactor),
(int)(y * scaleFactor));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension vitualSize = getVirtualSize();
int xOffset = (getWidth() - vitualSize.width) / 2;
int yOffset = (getHeight() - vitualSize.height) / 2;
Graphics2D g2D = (Graphics2D) g.create();
g2D.setColor(Color.gray);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g2D.setColor(Color.GREEN);
g2D.drawRect(xOffset, yOffset, vitualSize.width, vitualSize.height);
g2D.setColor(Color.RED);
g2D.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
g2D.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
Point virtualPoint = getVirtualPoint(imageX, imageY);
System.out.println(virtualPoint);
g2D.drawImage(getScaledInstance(), virtualPoint.x + xOffset, virtualPoint.y + yOffset, this);
g2D.dispose();
}
class MouseMotionHandler extends MouseMotionAdapter implements
MouseListener, MouseWheelListener {
public void mousePressed(MouseEvent e) {
lastMouseX = e.getX();
lastMouseY = e.getY();
}
public void mouseDragged(MouseEvent e) {
int xDiff = e.getX() - lastMouseX;
int yDiff = e.getY() - lastMouseY;
imageX = imageX + xDiff;
imageY = imageY + yDiff;
lastMouseX = e.getX();
lastMouseY = e.getY();
repaint();
}
public void mouseWheelMoved(MouseWheelEvent e) {
scaled = null;
int notches = e.getWheelRotation();
scaleFactor = scaleFactor + notches / 10.0;
if (scaleFactor < 0.5) {
scaleFactor = 0.5;
} else if (scaleFactor > 3.0) {
scaleFactor = 3.0;
}
repaint();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
}
}
I have a custom button that is not being drawn properly. It shows up as a dot in the upper left hand corner. I have three classes. One for the button, one for the menu or drawing of several buttons and a main class that calls the menu.
Class 1 - button
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.white);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, this.x, this.y,this.getWidth(), this.getHeight(), null);
g2d.setFont(this.font);
g2d.drawString(this.label, x, y);
}
Class 2 - menu
public void draw(Graphics g, int width, int height) {
int x, y;
for(int i = 0; i < buttons.length; i++) {
x = (int) (width / 2 - buttons[i].getWidth() / 2);
y = (int) (height / 2 - buttons[i].getHeight() / 2);
buttons[i].setBounds(x, y + (i*60), buttons[i].getWidth(), buttons[i].getHeight());
buttons[i].paintComponent(g);
}
}
Class 3 - main
if(gMenu != null) {
gMenu.draw(g, gWindow.getWidth(), gWindow.getHeight());
}
Edit: To clarify what I'm trying to do is create a popup menu with a few custom buttons (components).
Edit: I got them to draw, but the mouse listener doesn't work.
here is the menu class
public class Menu extends JComponent {
GameWindow window;
public Menu(GameWindow window) {
this.window = window;
this.setVisible(true);
}
public void addChildToPanel(JComponent child) {
int width = (int) getWidth();
if(child.getWidth() > width) {
width = child.getWidth();
}
int height = (int) getHeight();
height += child.getHeight();
setSize(width, height);
Dimension screen = new Dimension(window.getWidth(), window.getHeight());
int x = (screen.width - width) / 2;
int y = (screen.height - height) / 2;
setBounds(x, y, width, height);
}
}
Here is the button class
public class MenuButton extends JComponent implements MouseListener {
private BufferedImage img;
private BufferedImage img_h;
private int x, y;
private String label;
private Font font;
private int state = 0;
// state 0 = normal
// state 1 = highlight
// state 2 = pressed
public MenuButton(BufferedImage img, BufferedImage img_h, String label, Font font) {
this.setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
this.img_h = img_h;
this.img = img;
this.label = label;
this.font = font;
setVisible(true);
setBounds(0, 0, img.getWidth(), img.getHeight());
this.addMouseListener(this);
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.white);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
switch (state) {
case 0:
g2d.drawImage(img, this.getBounds().x, this.getBounds().y,this.getWidth(), this.getHeight(), null);
break;
case 1:
g2d.drawImage(img_h, this.getBounds().x, this.getBounds().y,this.getWidth(), this.getHeight(), null);
break;
case 2:
g2d.drawImage(img, this.x, this.y,this.getWidth(), this.getHeight(), null);
break;
}
g2d.setFont(this.font);
int size = g2d.getFontMetrics(font).stringWidth(this.label);
int x = this.getBounds().x + this.getWidth() - 20 - size;
int y = this.getBounds().y + 29;
g2d.drawString(this.label,x, y);
}
public void setState(int state) {
this.state = state;
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
setState(1);
}
#Override
public void mouseExited(MouseEvent e) {
setState(0);
}
#Override
public void mousePressed(MouseEvent e) {
setState(2);
}
#Override
public void mouseReleased(MouseEvent e) {
setState(1);
}
}
Child class that I call draw on
public class PauseMenu extends Menu {
private int width;
private int height;
private MenuButton[] buttons = new MenuButton[4];
public PauseMenu(GameWindow window) {
super(window);
Font font = null;
BufferedImage img = null;
BufferedImage img_h = null;
try {
InputStream is = getClass().getResourceAsStream("/fonts/ALDOPC.ttf");
font = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.PLAIN, 24f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
img = ImageIO.read(getClass().getResourceAsStream("/gui/bg_menu_button_round.png"));
img_h = ImageIO.read(getClass().getResourceAsStream("/gui/bg_menu_button_round_highlight.png"));
}
catch(Exception e)
{
System.out.print("Failed to load resources");
System.out.println();
}
MenuButton resume = new MenuButton(img, img_h, "CONTINUE", font);
final MenuButton quit = new MenuButton(img, img_h, "QUIT", font);
MenuButton vid = new MenuButton(img, img_h, "VIDEO", font);
MenuButton sound = new MenuButton(img, img_h, "SOUND", font);
buttons[0] = resume;
buttons[1] = vid;
buttons[2] = sound;
buttons[3] = quit;
for(int i = 0; i < buttons.length; i++) {
int x = (window.getWidth() - img.getWidth()) / 2;
int y = (window.getHeight() - img.getHeight()) / 2;
buttons[i].setBounds(x, y + (i * img.getHeight()), img.getWidth(), img.getHeight());
this.addChildToPanel(buttons[i]);
}
}
public void draw(Graphics g) {
for(int i = 0; i < buttons.length; i++)
buttons[i].paintComponent(g);
}
}
Here i have a code which draws a rectangle on the mouseClicked position using the paintComponent.I can get the output message but anything related to graphics and .draw() wont work.
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public final class testclass extends JFrame {
static JPanel p;
Timer t;
int x = 1;
int y = 1;
int xspeed = 1;
int yspeed = 1;
public testclass() {
initComponents();
this.setBounds(100, 300, 500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.start();
this.add(p);
}
public void initComponents() {
final ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Hello!");
p.repaint();
}
};
t = new Timer(50, action);
p = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
final Graphics2D gD = (Graphics2D) g;
moveBALL();
gD.drawOval(x, y, 25, 25);
p.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("a");
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("b");
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println("c");
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("d");
}
#Override
public void mouseClicked(MouseEvent e) {
gD.drawRect(e.getX(), e.getY(), 10, 60);
gD.setColor(Color.green);
System.out.println("clicked");
}
});
}
void moveBALL() {
x = x + xspeed;
y = y + yspeed;
if (x < 0) {
x = 0;
xspeed = -xspeed;
} else if (x > p.getWidth() - 20) {
x = p.getWidth() - 20;
xspeed = -xspeed;
}
if (y < 0) {
y = 0;
yspeed = -yspeed;
} else if (y > p.getHeight() - 20) {
y = p.getHeight() - 20;
yspeed = -yspeed;
}
}
};
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new testclass().setVisible(true);
p.setBackground(Color.WHITE);
}
});
}
}
What is the proper way to implement a mouseListener() in this program?
Thanks.
Some suggestions on current code:
Watch class naming scheme i.e testclass should be TestClass or even better Test (but thats nit picking). All class names begin with capital letter and each new word thereafter is capitalized.
Dont extend JFrame unnecessarily.
Dont call setBounds on JFrame rather use appropriate LayoutManager and/or override getPreferredSize() of JPanel and return dimensions which fits its content.
Always call pack() on JFrame before setting it visible (taking above into consideration).
Use MouseAdapter vs MouseListener
Dont call moveBall() in paintComponent rather call it in your Timer which repaints the screen, not only slightly better design but we also should not do possibly long running tasks in paint methods.
As for your problem I think your logic is a bit skewed.
One approach would see the Rectangle (or Rectangle2D) get replaced by its own custom class (which will allow us to store attributes like color etc). Your ball would also have its own class which has the method moveBall() and its attributes like x and y position etc. On every repaint() your JPanel would call the method to move the ball, the JPanel itself could wrap the moveBall() in its own public method which we could than call from the timer which repaints the screen.
Here is an example of your code with above fixes implemented (please analyze it and if you have any questions let me know):
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.*;
public class Test {
private MyPanel p;
private Timer t;
public Test() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
frame.add(p);
frame.pack();
frame.setVisible(true);
t.start();
}
private void initComponents() {
final ActionListener action = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
p.moveEntities();//moves ball etc
p.repaint();
}
};
t = new Timer(50, action);
p = new MyPanel();
p.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
p.addEntity(e.getX(), e.getY(), 10, 50, Color.GREEN);
System.out.println("clicked");
}
});
p.setBackground(Color.WHITE);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
}
class MyPanel extends JPanel {
int width = 300, height = 300;
ArrayList<MyRectangle> entities = new ArrayList<>();
MyBall ball = new MyBall(10, 10, 25, 25, Color.RED, width, height);
void addEntity(int x, int y, int w, int h, Color c) {
entities.add(new MyRectangle(x, y, w, h, c));
}
void moveEntities() {
ball.moveBALL();
}
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(ball.getColor());
g2d.fillOval((int) ball.x, (int) ball.y, (int) ball.width, (int) ball.height);
for (MyRectangle entity : entities) {
g2d.setColor(entity.getColor());
g2d.fillRect((int) entity.x, (int) entity.y, (int) entity.width, (int) entity.height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
}
class MyRectangle extends Rectangle2D.Double {
Color color;
public MyRectangle(double x, double y, double w, double h, Color c) {
super(x, y, w, h);
color = c;
}
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
}
class MyBall extends Ellipse2D.Double {
int xspeed = 1;
int yspeed = 1;
Color color;
private final int maxWidth;
private final int maxHeight;
public MyBall(double x, double y, double w, double h, Color c, int maxWidth, int maxHeight) {
super(x, y, w, h);
color = c;
this.width = w;//set width and height of Rectangle2D
this.height = h;
//set max width and height ball can move
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
}
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
void moveBALL() {
x = x + xspeed;
y = y + yspeed;
if (x < 0) {
x = 0;
xspeed = -xspeed;
} else if (x > maxWidth - ((int) getWidth() / 2)) {// i dont like hard coding values its not good oractice and resuaibilty is diminshed
x = maxWidth - ((int) getWidth() / 2);
xspeed = -xspeed;
}
if (y < 0) {
y = 0;
yspeed = -yspeed;
} else if (y > maxHeight - ((int) getHeight() / 2)) {
y = maxHeight - ((int) getHeight() / 2);
yspeed = -yspeed;
}
}
}
First of all the paint component is called every time swing needs to redraw the component.
And you are adding a new instance of mouse listener to the panel every time the paint is called.
Just move the line
p.addMouseListener(new MouseListener() {...}
out of the paint component, preferably after the initialization of the panel.
default template is
JPanel p = new JPanel(){
#Override
public void paintComponent(Graphics g) {
}
};
p.addMouseListener(new MouseListener() or new MouseAdapter()
//Your overridden methods
});
Hope this helps.