What should I have in paintComponent to drag and rotate an image? - java

I have worked with the school assignment for quite some time now. But I can not really understand what I should do. The assignment is due tomorrow and I feel quite stressed.
The task is, I'll get some pictures, have them in a window, then be able to move around them and also be able to rotate.
The big problem is that I do not know how I'll manage paintComponent().
What I read is that it should be called automatic "when needed" and when you call repaint(). I find it hard to get it to work.
The main class
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class JFrameC extends JFrame{
JPanel panel;
ArrayList <ThePhoto> oneArray = new <ThePhoto> ArrayList();
public JFrameC(){
super("This window");
setLayout(new BorderLayout());
panel = new JPanel();
panel.setBackground(Color.GREEN);
panel.setLayout(null);
add(panel);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void addPicture(String name){
oneArray.add(new ThePhoto(name, this));
panel.add(oneArray.get(oneArray.size()-1).getJPanel());
}
public void draw(JPanel p){
//One of the tasks is that the image is pressed to end up on top.
//I thought that if I sort of an ArrayList so I can keep track of which one
//is on top. Then be able to paint them in order.
for(ThePhoto x : oneArray){
if(x.getJPanel() == p && oneArray.indexOf(x) != 0){
int i = oneArray.indexOf(x);
for(;i > 0; i--){
ThePhoto temp = oneArray.get(i);
oneArray.set(i, oneArray.get(i-1));
oneArray.set(i-1, temp);
}
break;
}
}
panel.validate();//I can not get this to work
panel.repaint();
getContentPane().validate();//Or this.
getContentPane().repaint();
}
public void paintComponent(Graphics g){
//Is this right?
//What should I write here?
}
public static void main(String[] args) {
JFrameC j = new JFrameC();
j.addPicture("one.gif");
j.addPicture("two.gif");
j.addPicture("three.gif");
j.addPicture("four.gif");
}
}
Class
import javax.swing.*;
import java.awt.*;
public class ThePhoto{
ImageIcon onePicture;
JLabel l;
JPanel p;
JFrameC k;
int posX = 10;
int posY = 10;
public ThePhoto(String name, JFrameC k){
this.k = k;
onePicture = new ImageIcon(name);
l = new JLabel(onePicture);
p = new JPanel();
p.setLayout(new CardLayout());
p.setBorder(null);
p.setBackground(null);
p.add(l);
p.setBounds(posX, posY, 100, 100);
p.addMouseListener(new HandleMouse(k, this));
p.addMouseMotionListener(new HandleMouse(k, this));
}
public void setX(int x){posX = x;}
public void setY(int y){posY = y;}
public JPanel getJPanel(){return p;}
public void paintComponent(Graphics g){
//Is this right?
//What should I write here?
}
}
MouseEvent Class
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.*;
import javax.swing.*;
public class HandleMouse extends MouseAdapter implements MouseMotionListener{
JFrame k;
ThePhoto b;
public HandleMouse(JFrameC k, ThePhoto b){
this.k = k;
this.b = b;
}
public void mouseClicked (MouseEvent e) {
k.draw((JPanel)e.getComponent());
}
public void mouseDragged (MouseEvent e) {
e.translatePoint(e.getComponent().getLocation().x, e.getComponent().getLocation().y);
e.getComponent().setLocation(e.getX(), e.getY());
b.setX(e.getX());
b.setY(e.getY());
}
public void mouseReleased(MouseEvent e) {
k.draw((JPanel)e.getComponent());
}
}
To summarize the issues clearer:
1.Is it best to call repaint() to Frame or Panel? As, I understand it is in both cases everything 'in' the container that will be repainted. And if so, should JFrame be preferable?
2.Is there any routine/usual/rule on what should be in the paintComponent()?
3.What advice and criticism whatsoever is very welcome. But please write so that a beginner understands and no unnecessary insults.
I understand that nobody wants to do my homework. But I only ask for some advice so that I can get better. I also want to write that I am a novice and therefore looks like my code to be written by a novice.

Solve the problem for a single image before trying for multiple images. Starting from this example, use ImageIO.read() to initialize an image and use drawImage() to render it in paintComponent().
private final BufferedImage image = getImage();
private BufferedImage getImage() {
try {
return ImageIO.read(new URL(
"http://i.imgur.com/kxXhIH1.jpg"));
} catch (IOException e) {
e.printStackTrace(System.err);
}
return null;
}
…
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image,
textPt.x - image.getWidth() / 2,
textPt.y - image.getHeight() / 2, this);
}
You can rotate the graphics context as shown here.

Related

Ball doesn't move; Thread?

This is an UI that makes a ball go down in a diagonal way, but the ball stays static; it seems something is not working adecuatedly with the threads. Could you please, tell me how to make the ball move?
Please download a ball and change the directory so the program can find where your ball is allocated. It's not necessary to download the soccer pitch but if you want, it's OK. Finally, I have to thank you for spending time in search of this malfunctioning.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import java.io.File;
class Animation extends JFrame implements ActionListener { //Frame and listener
Rectangle2D dimensions = new Rectangle2D.Double(0,0,850,595); //Not implemented limits
JButton animate, stop;
Runnable runnable;
Thread move;
public Animation() {
setLayout(new BorderLayout()); //BorderLayout disposition
setTitle("Pelota en acción");
animate = new JButton("Animate it!"); //Button to create balls
animate.setBounds(0,0,120,30);
animate.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Image ball = null;
new Layout().createEllipse(ball);
runnable = new Layout();
move = new Thread(runnable);
move.start();
}
});
stop = new JButton("Freeze"); //Button to interrupt thread (not implemented)
stop.setBounds(0,0,120,30);
stop.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
move.interrupt();
Layout.running = false;
}
});
JPanel subPanel = new JPanel(); //Layout with its buttons situated to the south
subPanel.add(animate);
subPanel.add(stop);
add(subPanel,BorderLayout.SOUTH);
add(new Layout());
}
public static void main(String[] args) {
Animation ventana = new Animation();
ventana.setSize(850,625);
ventana.setLocationRelativeTo(null);
ventana.setVisible(true);
ventana.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {} //Tag
} //Class close
class Layout extends JPanel implements Runnable { //Layout and thread
int X,Y; //Coordenadas
static boolean running = true; //"To interrupt the thread" momentaneously.
static ArrayList<Image> balls = new ArrayList<>(); //Balls collection
#Override
public void run () { //Just moves ball towards Narnia xd
while(running) {
X++; Y++;
System.out.println(X+" "+Y);
repaint();
updateUI();
try {
Thread.sleep(4);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
repaint();
updateUI();
try {
URL url = new URL("https://www.freejpg.com.ar/image-900/9c/9ca2/F100004898-textura_pasto_verde_linea_de_cal.jpg");
Image picture = ImageIO.read(url);
g.drawImage(picture,0,0,null);
} catch(IOException e){
System.out.println("URL image was not found");
}
finally {
try {
//----------------------------------------------------------------------------
Image picture = ImageIO.read(new File("C:\\Users\\Home\\Desktop\\Cancha.jpg")); //Pitch
//----------------------------------------------------------------------------
g.drawImage(picture, 0, 0, null);
} catch (IOException ex) {
System.out.println("Pitch image was not found");
}
}
for (Image ball : balls) { //I add balls to the Layout
g2.drawImage(ball,X,Y,100,100,null);
}
}
public void createEllipse (Image ball) { //Method that adds balls to the collection
try {
//-------------------------------------------------------------------- Ball
ball = ImageIO.read(new File("C:\\Users\\Home\\Desktop\\Pelota.png")); //Change this
//-------------------------------------------------------------------- Ball
} catch(IOException ex) {
System.out.println("Any balls were found");
}
balls.add(ball);
}
}
So to break your code down:
When the button is pressed, you execute the following code:
Image ball = null;
new Layout().createEllipse(ball);
runnable = new Layout();
move = new Thread(runnable);
move.start();
This will create a new layout. The run() method of this will increase the X and Y variables. They are declared here:
int X,Y; //Coordenadas
Those are instance variables, this means they belong to your newly created Layout.
Then you call repaint() on the new Layout, which will do nothing, because this new Layout has not been added to some window.
So, how do you fix this?
First, you have to keep the original Layout around:
class Animation extends JFrame { // no need to implement ActionListener
Rectangle2D dimensions = new Rectangle2D.Double(0,0,850,595); //Not implemented limits
JButton animate, stop;
Thread move;
Layout layout;
Then remember the Layout when you create it:
// before: add(new Layout());
layout = new Layout();
add(layout);
Then use the layout in your ActionListener:
layout.createEllipse(ball);
move = new Thread(layout);
move.start();
This might have some problems with concurrency (Swing is not thread-safe), so for good measure, you should call repaint() in the AWTEventThread:
// in run(), was repaint():
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
repaint();
}
});
Now, there are some cleanup tasks left:
Delete this code:
#Override
public void actionPerformed(ActionEvent e) {} //Tag
It's no longer needed, because you don't implement ActionListener.
Drop the static modifiers from some fields, and add volatile:
volatile int X,Y; //Coordenadas
volatile boolean running = true; //"To interrupt the thread" momentaneously.
ArrayList<Image> balls = new ArrayList<>(); //Balls collection
volatile is needed for variables that are accessed from more than one thread.
Also remove repaint() and resetUI() from the paint method. You don't need them.
For the pictures in paint: you should cache them. Store them in a field, so you don't have to load the picture every time.
When all this is done, your code is much cleaner, but there are still some warts that should be addressed. But at least you have something working.
Johannes has already spoken about many of the things which are wrong with your original example, so I won't go over many of them again.
This example makes use of a Swing Timer instead of a Thread as the main "animation" loop. It also focuses on demonstrating encapsulation and responsibility.
For example, the AnimtionPane is responsible for managing the balls, managing the animation loop and paint. It isn't, however, responsible for determining "how" the balls are updated or paint, it only provides the timing and functionality to make those things happen.
A couple of the glaring issues I can see are:
Trying to load resources from within the paintComponent method. This is a bad ideas, as it could slow you paint pass down, causing your UI to lag
Calling repaint and updateUI from within the paintComponent method. You should avoid causing any new updates to the UI from occurring during a paint process. This could cause your program to run wide and consume all the CPU cycles, not only making your app non-responsive, but also the whole system.
Some very quick points
Swing is not thread safe. You should never update the UI (or anything the UI relies on) from outside the context of the Event Dispatching Thread. This example uses a Swing Timer as it allows the delay to occur of the EDT (and not block the UI), but it's updates are triggered within the EDT, allowing us to safely update the UI from within
You create multiple instances of Layout, meaning that the one on the screen isn't the one which is been updated
Your "freeze" logic is broken. It will never "freeze" anything
Runnable example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private AnimationPane animationPane;
public TestPane() {
setLayout(new BorderLayout());
animationPane = new AnimationPane();
JButton actionButton = new JButton("Start");
actionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (animationPane.isAnimating()) {
animationPane.stop();
actionButton.setText("Start");
} else {
animationPane.start();
actionButton.setText("Stop");
}
}
});
add(animationPane);
add(actionButton, BorderLayout.SOUTH);
}
}
// This is just makes it seem more random ;)
private static Random RANDOM = new Random();
public class Ball {
private int x;
private int y;
private int xDelta;
private int yDelta;
private Color color;
private Shape shape;
public Ball(Color color) {
shape = new Ellipse2D.Double(0, 0, 10, 10);
this.color = color;
// Get some random motion
do {
xDelta = RANDOM.nextInt(6) + 2;
yDelta = RANDOM.nextInt(6) + 2;
} while (xDelta == yDelta);
}
public void update(Rectangle bounds) {
x += xDelta;
y += yDelta;
if (x + 10 > bounds.x + bounds.width) {
x = bounds.x + bounds.width - 10;
xDelta *= -1;
} else if (x < bounds.x) {
x = bounds.x;
xDelta *= -1;
}
if (y + 10 > bounds.y + bounds.height) {
y = bounds.y + bounds.height - 10;
yDelta *= -1;
} else if (y < bounds.y) {
y = bounds.y;
yDelta *= -1;
}
}
public void paint(Graphics2D g2d) {
// This makes it easier to restore the graphics context
// back to it's original state
Graphics2D copy = (Graphics2D) g2d.create();
copy.setColor(color);
copy.translate(x, y);
copy.fill(shape);
// Don't need the copy any more, get rid of it
copy.dispose();
}
}
public class AnimationPane extends JPanel {
// This does not need to be static
private List<Ball> balls = new ArrayList<>(); //Balls collection
private Timer timer;
private List<Color> colors;
public AnimationPane() {
colors = new ArrayList<>(8);
colors.add(Color.RED);
colors.add(Color.GREEN);
colors.add(Color.BLUE);
colors.add(Color.CYAN);
colors.add(Color.MAGENTA);
colors.add(Color.ORANGE);
colors.add(Color.PINK);
colors.add(Color.YELLOW);
timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (RANDOM.nextBoolean()) {
makeBall();
}
Rectangle bounds = new Rectangle(new Point(0, 0), getSize());
for (Ball ball : balls) {
ball.update(bounds);
}
repaint();
}
});
makeBall();
}
protected void makeBall() {
Collections.shuffle(colors);
balls.add(new Ball(colors.get(0)));
}
public boolean isAnimating() {
return timer.isRunning();
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
// Bad ideas. Repaint will cause a new paint event to be posted, causing your
// UI to run away - consuming all your CPU cycles in a singulator forms
// and destorys the known universe
//repaint();
// This doesn't do what you think it does and there shouldn't be
// reason for you to call it
//updateUI();
// This is a bad idea as it could cause the paint cycles to slow down
// destorying the responsiveness of your app
// Besids, you should be passing this as the ImageObserver
// try {
// URL url = new URL("https://www.freejpg.com.ar/image-900/9c/9ca2/F100004898-textura_pasto_verde_linea_de_cal.jpg");
// Image picture = ImageIO.read(url);
// g.drawImage(picture, 0, 0, null);
// } catch (IOException e) {
// System.out.println("URL image was not found");
// } finally {
// try {
// //----------------------------------------------------------------------------
// Image picture = ImageIO.read(new File("C:\\Users\\Home\\Desktop\\Cancha.jpg")); //Pitch
// //----------------------------------------------------------------------------
// g.drawImage(picture, 0, 0, null);
// } catch (IOException ex) {
// System.out.println("Pitch image was not found");
// }
// }
// This is "bad" per say, but each ball should have it's own
// concept of location
// for (Image ball : balls) { //I add balls to the Layout
// g2.drawImage(ball, X, Y, 100, 100, null);
// }
for (Ball ball : balls) {
ball.paint(g2);
}
// I made a copy of the graphics context, as this is shared
// with all the other components been painted, changing the
// render hints could cause issues
g2.dispose();
}
}
}

Swing mousePressed for more things

Basicly this is a part of my code:
package Piano;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class DrawingPanel extends JPanel
{
int r = 0;
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(2.0f));
for (int i = 60; i < 1800; i += 150)
{
drawKeys(g, i, 450, 150, 550);
}
}
public void drawKeys(Graphics g, int x, int y, int width, int height)
{
g.setColor(Color.WHITE);
g.fillRect(x, y, width, height);
g.setColor(Color.BLACK);
g.drawRect(x, y, width, height);
r++;
this.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
if (e.getX() > x && e.getX() < x + width && e.getY() > y && e.getY() < y + height)
{
System.out.println(r);
}
}
});
}
}
and I was wondering if it is possible to add all the mousePressed locations in a single loop. Well, in my case it doesn't work, because for all keys it prints the same, which is the last known 'r' (System.out.println(r)). How would you approch this?
Never add a MouseListener (or any listener) to a component in a painting method. Every time Swing repaints the component you will add another listener.
I was wondering if it is possible to add all the mousePressed locations in a single loop.
You would never add a MouseListener for each pixel location. That is not how a MouseListener works.
Instead you:
create an ArrayList of Rectangles to represent each piano key
you add a single MouseListener to your component
When a MouseEvent is generated you use the Point from the MouseEvent and iterate through the ArrayList of rectangles using the Rectangle.contains(...) method to see if the Rectangle contains the mouse point. If so, then you do your custom logic.
Going off what you said in your comment you could do something a little like this. Create a JButton for each key, or preferably a JButton Array for all the keys. Add an action listener to them all. Then when a JButton is clicked play the corresponding sound.
A simple example
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class GUITemplate {
private JFrame myMainWindow = new JFrame("This is my title");
private JPanel firstPanel = new JPanel();
private JButton a = new JButton("a"), b = new JButton("b"), c = new JButton("c"), d = new JButton("d"), e = new JButton("e");
private CustomMouseListener cML = new CustomMouseListener();
private void runGUI() {
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new FlowLayout());
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.pack();
myMainWindow.setVisible(true);
}
private void createFirstPanel() {
firstPanel.setLayout(new FlowLayout());
firstPanel.add(a);
firstPanel.add(b);
firstPanel.add(c);
firstPanel.add(d);
firstPanel.add(e);
int panelComponents = firstPanel.getComponentCount();
for(int i = 0;i<panelComponents;i++) {
if(firstPanel.getComponent(i) instanceof JButton) {
JButton temp = (JButton) firstPanel.getComponent(i);
temp.addMouseListener(cML);
firstPanel.getComponent(i).setFocusable(false);
}
}
}
private class CustomMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent mE) {
if(mE.getSource() == a) {
System.out.println("a");
}
if(mE.getSource() == b) {
System.out.println("b");
}
if(mE.getSource() == c) {
System.out.println("c");
}
if(mE.getSource() == d) {
System.out.println("d");
}
if(mE.getSource() == e) {
System.out.println("e");
}
}
}
public static void main(String[] args)
{
new GUITemplate().runGUI();
}
}
In this example, a letter is printed to the terminal instead of a sound being played and it looks nothing like a piano but the JButtons could be made to look like piano keys and it would be easy enough to get it to play correct sounds.
Edit
I changed code to use a MouseListener just incase you desperately wanted to use one. It works the same except you a MouseListener to each JButton instead of an ActionListener.

Mirroring JLabel or JTextArea

I need to get a mirror of JLabel or JTextArea.
http://www.subirimagenes.net/i/150305101716451074.jpg
If I use a JTextArea, I'll need the letters are complety mirrored.
If I use a JLabel, I'll need format and the mirrored letters.
The example was created on Photoshop.
My idea is using graphics(), but I don't have idea how to do it.
Here's the bad news: It's not as straight-forward as we might wish, there's a limitation. In Swing, graphics transformations are applied only on the paint operation, not the general layout and event process. Therefore, in Swing the mirrored component is basically "unusable", it cannot be used for anything else than displaying the mirror image of the primary component. Coordinates of mouse clicks etc. will be wrong.
Therefore, this is all tricky stuff, a bit hackish.
There are multiple ways how you can do that.
One possibility is to use two views on one model and tell the Graphics of one of the views to flip horizontally.
Here's an example how to do so which demonstrates a flipped JEditorPane:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class MirrorText {
public static void main(final String... args) {
SwingUtilities.invokeLater(MirrorText::setupUI);
}
public static void setupUI() {
final JEditorPane editor = new JEditorPane("text/html", "<h1>Mirrored</h1><p>This is mirrored text.</p>");
final JEditorPane mirroredEditor = new JEditorPane("text/html", "") {
protected Graphics getComponentGraphics(final Graphics g) {
return horizontalFlip(super.getComponentGraphics(g), getWidth());
}
};
mirroredEditor.setDocument(editor.getDocument());
final JFrame frame = new JFrame("mirrored label");
final JPanel mirrorPanel = new JPanel(new GridLayout(1, 2));
mirrorPanel.add(new JScrollPane(editor));
mirrorPanel.add(new JScrollPane(mirroredEditor));
frame.add(mirrorPanel);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
public static Graphics horizontalFlip(final Graphics g, final int width) {
final Graphics2D g2d = (Graphics2D) g;
final AffineTransform tx = g2d.getTransform();
tx.scale(-1.0, 1.0);
tx.translate(-width, 0);
g2d.setTransform(tx);
return g2d;
}
}
The advantage of this solution is that the mirror entirely the original component's MVC and observers because it is the same type of component (View/Controller) on the very same model.
The disadvantage of this solution is that you have create the mirror component in a way that is very specific to the component that is mirrored.
Another possibility is to create a decorator JComponent Mirror which can mirror an arbitrary other JComponent. This is a bit tricky, as in Java, decorators cannot override methods of the decorated object, and the Mirror needs to be updated (repainted) as well whenever the original component is updated (repainted).
Here's an incomplete example using a Mirror which hooks into the corresponding events. Incomplete because it only hooks into DocumentEvent but should also hook onto other events as well, like CaretEvent. It would be nice if Swing would have something like a PaintEvent. As far as I am aware of, it hasn't. (Well, in fact it has, but there's no corresponding PaintListener and addPaintListener().)
Also incomplete because the Mirror doesn't observe the original component's attributes like size. It only works because the GridLayout on the MirrorPanel keeps the mirror size in sync with the original component.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
public class MirrorText {
public static void main(final String... args) {
SwingUtilities.invokeLater(MirrorText::setupUI);
}
public static void setupUI() {
final JEditorPane editor = new JEditorPane("text/html", "<h1>Mirrored</h1><p>This is mirrored text.</p>");
final MirrorPanel mirrorPanel = new MirrorPanel(new JScrollPane(editor));
editor.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(final DocumentEvent e) { mirrorPanel.updateMirror(); }
public void insertUpdate(final DocumentEvent e) { mirrorPanel.updateMirror(); }
public void removeUpdate(final DocumentEvent e) { mirrorPanel.updateMirror(); }
});
final JFrame frame = new JFrame("mirrored label");
frame.add(mirrorPanel);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}
class MirrorPanel extends JPanel {
public MirrorPanel(final JComponent c) {
super(new GridLayout(1, 2));
add(c);
add(new Mirror(c));
}
public void updateMirror() {
repaint();
}
}
class Mirror extends JComponent {
private final JComponent mirroredComponent;
public Mirror(final JComponent mirroredComponent) {
this.mirroredComponent = mirroredComponent;
}
public static Graphics horizontalFlip(final Graphics g, final int width) {
final Graphics2D g2d = (Graphics2D) g;
final AffineTransform tx = g2d.getTransform();
tx.scale(-1.0, 1.0);
tx.translate(-width, 0);
g2d.setTransform(tx);
return g2d;
}
public void paint(final Graphics g) {
mirroredComponent.paint(horizontalFlip(g, mirroredComponent.getWidth()));
}
}
There probably are more possibilities as well. For example, one could override the mirrored component's paint() method to update the mirror component as well. That would get rid of getting notified, but it would lead to unnecessary paint() calls in case painting isn't done due to content change but due to buffer destruction (i.e. other window moved away).
Here's one way to create a mirror image.
Basically, you print the contents of the JTextArea on a BufferedImage. Then you reverse the pixels of the BufferedImage on the X axis.
package com.ggl.testing;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class MirrorImage implements Runnable {
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new MirrorImage());
}
#Override
public void run() {
frame = new JFrame("Mirror Image Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
JPanel textPanel = new JPanel();
JTextArea textArea = new JTextArea(15, 30);
textPanel.add(textArea);
mainPanel.add(textPanel);
MirrorPanel mirrorPanel = new MirrorPanel();
mirrorPanel.setPreferredSize(textPanel.getPreferredSize());
mainPanel.add(mirrorPanel);
TextListener listener = new TextListener(textArea, mirrorPanel);
textArea.getDocument().addDocumentListener(listener);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
listener.createImage(textArea);
frame.setVisible(true);
}
private class MirrorPanel extends JPanel {
private static final long serialVersionUID = 2496058019297247364L;
private Image image;
public void setImage(Image image) {
this.image = image;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, (getWidth() - image.getWidth(this)) / 2,
(getHeight() - image.getHeight(this)) / 2, this);
}
}
private class TextListener implements DocumentListener {
private JTextArea textArea;
private MirrorPanel mirrorPanel;
public TextListener(JTextArea textArea, MirrorPanel mirrorPanel) {
this.textArea = textArea;
this.mirrorPanel = mirrorPanel;
}
#Override
public void insertUpdate(DocumentEvent event) {
createImage(textArea);
}
#Override
public void removeUpdate(DocumentEvent event) {
createImage(textArea);
}
#Override
public void changedUpdate(DocumentEvent event) {
createImage(textArea);
}
public void createImage(JTextArea textArea) {
BufferedImage img = new BufferedImage(textArea.getWidth(),
textArea.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
textArea.printAll(g2d);
g2d.dispose();
createMirrorImage(img);
mirrorPanel.setImage(img);
}
private void createMirrorImage(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int[][] pixels = new int[width][height];
for (int i = width - 1; i >= 0; i--) {
int j = width - i - 1;
for (int k = 0; k < height; k++) {
pixels[j][k] = img.getRGB(i, k);
}
}
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
img.setRGB(i, j, pixels[i][j]);
}
}
}
}
}

This square I'm animating is leaving a trail behind it, can anyone work out why?

Thanks for checking out this Question. I think I've just about scratched through my skull in frustration.
So what I've got is a 'JFrame' containing a 'JPanel'. The 'JPanel' contains a little colored Square which is supposed to move X pixels whenever I click the window.
Well, essentially everything behaves as it should, with one exception. When the blue square moves to the right, it leaves a trail of other squares behind it. It is not supposed to leave the trail, however, when I re-size the window, the trail vanishes.
Catalyst.java
package Prototype;
import java.awt.*;
public class Catalyst {
public static void main(String[] args){
World theWorldInstance = new World("Prototype", 100,100, 600,100); /*title,xpos,ypos,width,height*/
}
}
World.java
package Prototype;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class World extends JFrame {
Level mainPanel;
public World(String title, int x, int y, int width, int height) {
setTitle(title);
setBounds(x,y,width,height);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBackground(new Color(0x00000000));
initLevel();
}
public void initLevel(){
mainPanel = new Level();
Container visibleArea = getContentPane();
visibleArea.add(mainPanel);
setVisible(true);
add(mainPanel);
}
}
Level.java
package Prototype;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Level extends JPanel implements MouseListener, ActionListener {
Square x;
public Level() {
System.out.println("This is working correctly[JPANEL Cons]");
addMouseListener(this);
x = new Square();
}
public void paintComponent(Graphics g){
x.draw(g);
}
public void actionPerformed(ActionEvent e){
}
public void mousePressed(MouseEvent e){
requestFocus();
x.move();
repaint();
System.out.println("Focus Acquired");
}
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
}
Square.java
package Prototype;
import java.awt.*;
public class Square {
private Point position;
private int size;
private final int displacement;
public Square(){
position = new Point(10,10);
size = 20;
displacement = 5;
}
public void draw(Graphics g){
g.setColor(Color.blue);
g.fillRect(position.x-(size/2), position.y-(size/2), size,size );
g.setColor(Color.black);
g.drawRect(position.x-(size/2), position.y-(size/2), size,size );
}
public void move() {
position.x += displacement;
}
}
Those are all my files. I hope I've phrased everything properly and provided all the content required. Whenever I've done something similar in the past this has never happened. I assume I'm missing something small, or I've done something stupid. If you can help me, thanks in advance!
There's another way of doing this. You can simply call the parent object's paintComponent method to clear the panel.
Add this to your constructor in Level :
this.setBackground(Color.BLACK);
And this as the first call in paintComponent:
super.paintComponent(g);
You can use g.clearRect(x, y, width, height), and provide the said coordinates, where you want the painting to be cleared from. Or you can give the dimensions of whole of the JPanel/JComponent where you are drawing, though doing this keep one thing in mind, that the said drawing is not a heavy work, else too much of cleaning will put extra burden on the painting calls.

Java Graphics not displaying on successive function calls, why?

I'm making a visualization for a BST implementation (I posted another question about it the other day). I've created a GUI which displays the viewing area and buttons. I've added code to the BST implementation to recursively traverse the tree, the function takes in coordinates along with the Graphics object which are initially passed in by the main GUI class. My idea was that I'd just have this function re-draw the tree after every update (add, delete, etc...), drawing a rectangle over everything first to "refresh" the viewing area. This also means I could alter the BST implementation (i.e by adding a balance operation) and it wouldn't affect the visualization.
The issue I'm having is that the draw function only works the first time it is called, after that it doesn't display anything. I guess I don't fully understand how the Graphics object works since it doesn't behave the way I'd expect it to when getting passed/called from different functions. I know the getGraphics function has something to do with it.
Relevant code:
private void draw(){
Graphics g = vPanel.getGraphics();
tree.drawTree(g,ORIGIN,ORIGIN);
}
vPanel is what I'm drawing on
private void drawTree(Graphics g, BinaryNode<AnyType> n, int x, int y){
if( n != null ){
drawTree(g, n.left, x-10,y+10 );
if(n.selected){
g.setColor(Color.blue);
}
else{
g.setColor(Color.gray);
}
g.fillOval(x,y,20,20);
g.setColor(Color.black);
g.drawString(n.element.toString(),x,y);
drawTree(g,n.right, x+10,y+10);
}
}
It is passed the root node when it is called by the public function. Do I have to have:
Graphics g = vPanel.getGraphics();
...within the drawTree function? This doesn't make sense!!
Thanks for your help.
This is not the right way of doing it. If you want a component that displays the tree, you should make your own JComponent and override the paintComponent-method.
Whenever the model (the tree / current node etc) changes, you invoke redraw() which will trigger paintComponent.
I actually don't think you are allowed to fetch the Graphics object from anywhere else than the argument of the paintComponent method.
Try out the following program
import java.awt.Graphics;
public class FrameTest {
public static void main(String[] args) {
final JFrame f = new JFrame("Frame Test");
f.setContentPane(new MyTreeComponent());
f.setSize(400, 400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
f.repaint();
}
}
}.start();
}
}
class MyTreeComponent extends JComponent {
public void paintComponent(Graphics g) {
// Draw your tree. (Using random here to visualize the updates.)
g.drawLine(30, 30, 50, 30 + new Random().nextInt(20));
g.drawLine(30, 30, 50, 30 - new Random().nextInt(20));
}
}
The best starting point is probably http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html
#aioobe's approach is sound and the example is compelling. In addition to the cited tutorial, Performing Custom Painting, I would add that drawing should take place on the Event Dispatch Thread (EDT). In the variation below, note how the GUI is built using EventQueue.invokeLater. Similarly, the actionPerformed() method of javax.swing.Timer invokes repaint() on the EDT to display recently added nodes. A more elaborate example may be found here.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class StarPanel extends JPanel implements ActionListener {
private static final Random rnd = new Random();
private final Timer t = new Timer(100, this);
private final List<Node> nodes = new ArrayList<Node>();
private static class Node {
private Point p;
private Color c;
public Node(Point p, Color c) {
this.p = p;
this.c = c;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Star Topology");
f.add(new StarPanel());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
});
}
public StarPanel() {
this.setPreferredSize(new Dimension(400, 400));
t.start();
}
#Override // Respond to the Timer
public void actionPerformed(ActionEvent e) {
int w = this.getWidth();
int h = this.getHeight();
nodes.add(new Node(
new Point(rnd.nextInt(w), rnd.nextInt(h)),
new Color(rnd.nextInt())));
this.repaint();
}
#Override
public void paintComponent(Graphics g) {
int w2 = this.getWidth() / 2;
int h2 = this.getHeight() / 2;
for (Node n : nodes) {
g.setColor(n.c);
int x = n.p.x;
int y = n.p.y;
g.drawLine(w2, h2, x, y);
g.drawLine(w2, h2, x, y);
g.drawRect(x - 2, y - 2, 4, 4);
}
}
}

Categories

Resources