Make mouse events on JComponent after transform work? - java

Hello and sorry for my imperfect English.
I have a class MyNode (draws a rectangle) that extends JComponent. I have mouse listener for mouseEntered and mouseExited to change its color.
The big problem is that i need to work with transforms (the main app, not this SSCE, it is a graph (nodes&edges) drawer.)
I read about this problem already but I want to ask you how can i make it work. If I apply a scale(2,2) on my panel i have two main problems:
The mouse position doesn't correspond anymore to the drew MyNode. I know i can apply inverseTransform and this works just well, but I must search in all node collection of the panel and check the contains method with the inversed point (inefficient imo). (hope you get what i am saying here). How i can make the mouseEntered, mouseExited etc. work by itself in the new scaled system.
If I scale the panel, the MyNode paintComponent() doesn't apply its owner (Panel) transforms. The node is drew with its initial size.
I am very curious if this can be resolved, and I wait any other question to help you understand what I am looking for. It seems even hard to explain the problem, can't imagine the solution :)
This is a demo of my problem (you can run it):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SSCE extends JPanel {
public SSCE() {
setLayout(null);
setBackground(Color.yellow);
setSize(new Dimension(500, 300));
setPreferredSize(new Dimension(500, 200));
add(new MyNode(0, 0));
setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.scale(2, 2);
super.paintComponent(g2d);
paintComponents(g2d);
}
}
class MyNode extends JComponent {
private Color activeColor = Color.red;
public MyNode(int x, int y) {
this.setLocation(x, y);
this.setSize(50, 50);
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
colorOnMouseHover();
}
#Override
public void mouseExited(MouseEvent e) {
colorOnMouseLeave();
}
});
}
private void colorOnMouseHover() {
this.activeColor = Color.blue;
repaint();
}
private void colorOnMouseLeave() {
this.activeColor = Color.red;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(activeColor);
g.fillRect(0, 0, 50, 50);
}
}
class Run {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 200);
frame.add(new SSCE());
frame.setVisible(true);
}
}

Related

Can't get paint function to update in simple pong game

I'm a relatively inexperienced Java programmer when it comes to graphics. I'm trying to make a simple pong game to learn more about how graphics are done in Java.
In the program, the left paddle (the only paddle thus far implemented) should move up 5 pixels when 'W' is pressed on the keyboard. According to the console, it is recognizing that the key is being pressed, and it is updating a variable that represents the y-coordinate for the left paddle accordingly. However, the paddle's location isn't actually being updated on the screen.
Help?
Game class:
import javax.swing.JFrame;
public class Game {
static int WIDTH = 500;
static int HEIGHT = 500;
public static void main(String[] args) {
window();
}
public static void window() {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setAlwaysOnTop(true);
frame.setVisible(true);
frame.setResizable(false);
frame.add(new Panel());
frame.addKeyListener(new Panel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Panel class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class Panel extends JPanel implements KeyListener {
int leftPaddlePos = 100;
public void paint(Graphics g) {
g.clearRect(0, 0, Game.WIDTH, Game.HEIGHT);
g.setColor(Color.black);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
g.setColor(Color.white);
g.fillRect(75, leftPaddlePos, 15, 100);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) {
System.out.println("W pressed");
leftPaddlePos = leftPaddlePos + 5;
System.out.println(leftPaddlePos);
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
public class Panel extends JPanel implements KeyListener {
Don't call your class Panel. There is an AWT class with that name so it is confusing. Your class name should be more descriptive. Maybe something like PongPanel.
public void paint(Graphics g) {
Don't override paint(...);
public void paintComponent(Graphics g) {
Custom painting in Swing is done by overriding paintComponent(...).
g.clearRect(0, 0, Game.WIDTH, Game.HEIGHT);
g.setColor(Color.black);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
Don't use above code to paint the background of the panel. Instead, you just use:
super.paintComponent(g);
So in the constructor of your class you can invoke setBackground(...) to set the desired background color.
However, the paddle's location isn't actually being updated on the screen.
leftPaddlePos = leftPaddlePos + 5;
You update the position, but you haven't told the component that a property of the class has changed, so it doesn't know it needs to paint itself again.
You should not change the property of the class in the listener. Instead you should have a method like adjustLeftPaddlePosition(int value)
The method would be:
public void adjustLeftPaddlePostion(int value)
{
leftPaddlePos = leftPaddlePos + value;
repaint();
}
Then in the KeyListener you would use:
adjustLeftPaddlePosition(5);
Also, you should not be using a KeyListener. Instead you should be using "Key Bindings" Check out Motion Using the Keyboard for more information and working examples.

Why doesn't JPanel (panel) get drawn on the green background (the jpanel)?

Why doesn't JPanel (panel) get drawn on the green background (the jpanel)? I want to be able to do this without extending j panel to...
Furthermore, for java games should i use keybindings or keylistener in java.
import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class Game {
JFrame window;
JPanel panel;
int charPosX = 0;
int charPosY = 0;
public Boolean createGui() {
window = new JFrame("Game");
window.setSize(1000,500);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
panel = new JPanel();
panel.setVisible(true);
panel.setLayout(null);;
panel.setBackground(new Color(65,130,92));
window.add(panel);
return true; //returns true if ran and will be ran by check status in Main.
}
public void paintComponent(Graphics g) {
panel.paintComponents(g);
g.setColor(Color.RED);
g.drawRect(100,10,30,40);
g.fillRect(10, 10, 20, 10);
}
}
Let's take your code for a second and add #Override to your paintComponent method...
public class Game {
//...
#Override
public void paintComponent(Graphics g) {
panel.paintComponents(g);
g.setColor(Color.RED);
g.drawRect(100, 10, 30, 40);
g.fillRect(10, 10, 20, 10);
}
}
And now we have a compiler error! This is because Game extends Object and does not have a paintComponent method. This means that there is no way that the method could be called by any part of the existing painting system, so, it never gets called.
Components make poor "game" entities, they have a lot of "plumbing" which doesn't make them very efficient for this kind of work, you're generally better off heading down a complete custom painting route
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Game {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Game().createGui();
}
});
}
JFrame window;
GamePanel panel;
int charPosX = 0;
int charPosY = 0;
public Boolean createGui() {
window = new JFrame("Game");
window.setSize(1000, 500);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new GamePanel();
panel.setBackground(new Color(65, 130, 92));
window.add(panel);
window.setVisible(true);
return true; //returns true if ran and will be ran by check status in Main.
}
public class GamePanel extends JPanel {
private Rectangle entity = new Rectangle(100, 10, 30, 40);
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.draw(entity);
g2d.setColor(Color.BLUE);
g2d.fill(entity);
g2d.dispose();
}
}
}
Also note, I called window.setVisible(true); only after I had added the panel to the window, this is because Swing is lazy when it comes to adding/removing components. If you want to add/remove components after the UI has been realized on the screen, you'll need to call revalidate and repaint on the container to trigger a layout and paint pass
Also, beware, there is a difference between paintComponent and paintComponents ;)
I would highly recommend having a look at Painting in AWT Swing and Performing Custom Painting to gain a better understanding of how painting works in Swing and how you can take advantage of it

Can't see child JPanel in JPanel in JFrame

I've created a JFrame.
Inside this JFrame, I've created a JPanel.
Inside this JPanel I've created another JPanel (lets call it "A").
I've drawn in "A" a rectangle, and wanted to create buttons using graphics.
There is no rectangle in my gui. I could see that the paintComponent() method inside "A" is not being invoked.
Code:
The JPanels: (the child JPanel is inner class)
public class MemoryPanel extends JPanel {
public MemoryPanel(){
setPreferredSize(new Dimension(350,448));
}
#Override
public void paintComponent(Graphics g) {
//POSITIONING
setLayout(new BorderLayout());
//CREATE MEMORY BUTTONS
MemButton a=new MemButton();
//Drawing Rectangles for Memory
add(a,BorderLayout.CENTER);
}
private class MemoryButton extends JPanel{
public MemoryButton(){
setLayout(null);
setPreferredSize(new Dimension(87,40));
}
#Override
public void paintComponent(Graphics g){
Graphics2D td= (Graphics2D)g;
td.drawRect(0, 0, 20, 20);
}
}
}
You should program the JButtons first in order for your graphics to work as buttons. I belive this post will help you with that:
Creating a custom button in Java
I you want a rectangle to be the background for your buttons you can draw it in your main panel and add the buttons on it. Try using different Layouts to mantain some order.
I've made a simple GUI to test your code and the rectangle appears correctly.
I made no relevant changes in the code that you posted.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimpleJFrameProgram extends JFrame {
private static final long serialVersionUID = 1L;
public SimpleJFrameProgram() {
super("TEST");
initComponents();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private void initComponents() {
MemoryPanel memoryPanel = new MemoryPanel();
this.add(memoryPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new SimpleJFrameProgram();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I've applyed minor changes to your MemoryPanel: replaced MemButton by your MemoryButton and fill the rectangle in red to improve its visibility for the test. Without this last change, the rectangle appears too.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class MemoryPanel extends JPanel {
public MemoryPanel(){
setPreferredSize(new Dimension(350,448));
}
#Override
public void paintComponent(Graphics g) {
// POSITIONING
setLayout(new BorderLayout());
// CREATE MEMORY BUTTONS
MemoryButton a = new MemoryButton();
// Drawing Rectangles for Memory
add(a,BorderLayout.CENTER);
}
private class MemoryButton extends JPanel{
public MemoryButton(){
setLayout(null);
setPreferredSize(new Dimension(87,40));
}
#Override
public void paintComponent(Graphics g) {
Graphics2D td = (Graphics2D) g;
td.setColor(Color.red);
td.fillRect(0, 0, 20, 20);
}
}
}
This is the obtained result:
Maybe your problem is located on initializing the parent JFrame.
Changing the class name of MemoryButton fixed it.
I had another package with the same class name.

How to prevent the JPanel from being updated?

I'm creating a sort of paint application. The user can move a circle in a JPanel by pressing/dragging the mouse.
I have a JCheckBoxMenuItem in one of my JMenus:
JCheckBoxMenuItem checkitem = new JCheckBoxMenuItem("Draw mode",false);
When it is not activated, the circle can only be moved (by dragging/pressing) and the previous circle will be erased.
When it is activated, the circle can only be moved, but the previous circle will not be erased when dragging/pressing the mouse ( This works the same way as a paint program )
Shortened version of my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class GUI extends JFrame implements MouseListener, MouseMotionListener, ActionListener, ItemListener
{
JPanel mainPan, colorPan;
Color color = Color.BLACK;
JCheckBoxMenuItem checkitem;
boolean clear = true;
public GUI(String header)
{
maker();
mainPan.addMouseListener(this);
mainPan.addMouseMotionListener(this);
add(mainPan , BorderLayout.CENTER);
add(colorPan, BorderLayout.PAGE_END);
}
public void maker()
{
colorPan = new JPanel();
colorPan.setLayout(new GridLayout(1, 0));
mainPan = new JPanel(){
#Override
public void paintComponent(Graphics g)
{
//g.setColor(Color.WHITE);
//g.fillRect(0,0,getWidth(),getHeight());
if(clear)
super.paintComponent(g); //Do the same thing as above(Clear JPanel)
g.setColor(color);
g.fillOval(x,y,50,50); //x and y are integer variables that I use in my full program
}
};
checkitem = new JCheckBoxMenuItem("Draw mode",false);
//After adding this to a JMenu,
checkitem.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
clear = false;
}
else
{
clear = true;
}
}
}
The below screenshot shows the output of my full program:
colorPan is the JPanel full of JButtons of different colors. The top of it is mainPan.
Right now, the "Draw mode" doesn't work as expected. I had always thought that super.paintComponent(g); was the one that clears/resets the screen when repaint() is called. But I removed that and was quite surprised to see the program behave the same way.
Basically, my problem is here:
if(clear)
super.paintComponent(g);
I need to prevent everything from being cleared when repaint() is called. How do I achieve what I want?
It is not in this code where changes should be made. And it is not paint method which should be changed. Paint paints whenever is required either by your or by system. When window is resized or moved or partially covered - it uses paint to paint picture again.
What you should really do is to stop updating coordinates for your painted oval. It could be done in mouse listener or in coordinates setter or, better, in control part which manages these coordinates. Your checkbox should control ability to change your model. It should not control painting.
There is commonly used pattern Model-View-Controller - look at it. Maybe it could look like overkill for such small application but even Swing itself is built on this pattern so you already follow it. Issues rise when you try to break it. So - don't.
You can't "prevent the JPanel from being updated;" paintComponent() will be called asynchronously, as required by the system. Instead, condition attributes of your view class in a way that allows your implementation of paintComponent() to render everything whenever it is called.
In the example below, the foreground color is changed with each mouse click and paintComponent() uses the revised setting. In the more elaborate example cited here, ClearAction clears the List<Node> and List<Edge> that define the graph's model. Absent a call to super.paintComponent(g), otherwise required for an opaque component, a call to fillRect() in paintComponent() cleans up any leftover selection artifacts.
public void actionPerformed(ActionEvent e) {
nodes.clear();
edges.clear();
repaint();
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/a/5312702/230513 */
public class MouseDragTest extends JPanel {
private static final String TITLE = "Drag me!";
private static final Random r = new Random();
private static final int W = 640;
private static final int H = 480;
private Point textPt = new Point(W / 2, H / 2);
private Point mousePt;
private Color color = Color.black;
public MouseDragTest() {
this.setFont(new Font("Serif", Font.ITALIC + Font.BOLD, 32));
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mousePt = e.getPoint();
setColor(Color.getHSBColor(r.nextFloat(), 1, 1));
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
int dx = e.getX() - mousePt.x;
int dy = e.getY() - mousePt.y;
textPt.setLocation(textPt.x + dx, textPt.y + dy);
mousePt = e.getPoint();
repaint();
}
});
}
public void setColor(Color color) {
this.color = color;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
int w2 = g.getFontMetrics().stringWidth(TITLE) / 2;
g.drawString(TITLE, textPt.x - w2, textPt.y);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame(TITLE);
f.add(new MouseDragTest());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}

JButton subclass with custom shape shifts during repainting

I have just started working with Swing and am trying to draw a button with a custom shape, a triangle in this example. I called the JButton subclass 'ShiftingButton' in the following code because of its unusual behavior. When the mouse enters its region, it is repainted with an offset from its original position. Furthermore the shifted, offset version is drawn in addition to the original position so that both the original and shifted versions appear together. That is, when I run this code, the button is shown as a triangle along the left edge of the window. Then when I run the mouse over the button, a new triangle is drawn (in addition to the old one), shifted down and to the right by about 10 pixels. Resizing the window changes the offset of the phantom button from the original.
Experimenting with mouse clicks shows that only the original, correctly-positioned button is active. The region of the offset phantom button is not active.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.Polygon;
public class ShiftingButton extends JButton implements ActionListener {
private Polygon shape;
public ShiftingButton () {
initialize();
addActionListener(this);
}
protected void initialize() {
shape = new Polygon();
setSize(120, 120);
shape.addPoint(0, 0);
shape.addPoint(0, 60);
shape.addPoint(90, 0);
setMinimumSize(getSize());
setMaximumSize(getSize());
setPreferredSize(getSize());
}
// Hit detection
public boolean contains(int x, int y) {
return shape.contains(x, y);
}
#Override
public void paintComponent (Graphics g) {
System.err.println("paintComponent()");
g.fillPolygon(shape);
}
protected void paintBorder(Graphics g) {
}
#Override
public void actionPerformed (ActionEvent ev) {
System.out.println("ShiftingButton ActionEvent!");
}
public static void main (String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
ShiftingButton button = new ShiftingButton();
panel.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
You failed to call super.paintComponent(g) inside the overridden paintComponent(...) method. Moreover, while overriding a method of the Base class, always try to keep the access specifier of the methods, the same, as much as possible. In this case it's protected and not public :-) Now function should be like this :
#Override
protected void paintComponent (Graphics g) {
System.err.println("paintComponent()");
super.paintComponent(g);
g.fillPolygon(shape);
}
EDIT 1 :
Moreover, since you are using a custom shape to be drawn, hence you again failed to specify the ContentAreaFilled property for this JButton in question, hence inside your constructor, you should write setContentAreaFilled(false), for it to work nicely. Though if this doesn't works (for reasons specified in the Docs), then you have to use the plain old Opaque property and set it to false for this JButton using setOpaque(false) :-)
Here is your code with modified changes :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.Polygon;
public class ShiftingButton extends JButton implements ActionListener {
private Polygon shape;
public ShiftingButton () {
setContentAreaFilled(false);
initialize();
addActionListener(this);
}
protected void initialize() {
shape = new Polygon();
setSize(120, 120);
shape.addPoint(0, 0);
shape.addPoint(0, 60);
shape.addPoint(90, 0);
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(120, 120));
}
// Hit detection
public boolean contains(int x, int y) {
return shape.contains(x, y);
}
#Override
protected void paintComponent(Graphics g) {
System.err.println("paintComponent()");
super.paintComponent(g);
g.fillPolygon(shape);
}
protected void paintBorder(Graphics g) {
}
#Override
public void actionPerformed (ActionEvent ev) {
System.out.println("ShiftingButton ActionEvent!");
}
public static void main (String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
ShiftingButton button = new ShiftingButton();
panel.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}

Categories