Getting the font metrics before the paint method id called - java

Hi I am creating a news ticker/ text scroller.
I am using the following method:
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Scroll1 extends JPanel{
private int x;
private int x2;
private int y;
private String text;
final int startX=-100;
public Scroll1(int startX)
{
x2=-650;
x = 20;
y=150;
text= "Some Words and others, and now this must be a longer text that takes up the whole panel/ frame for this test to work ";
}
#Override
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0, 0, 400, 300);
g.setColor(Color.black);
g.drawString(text, x, y);
g.drawString(text, x2, y);
FontMetrics fm= g.getFontMetrics();
System.out.println(fm.stringWidth(text));;
}
public void start() throws InterruptedException{
while(true){
while(x<= 650){
x++;
x2++;
y = getHeight()/2;
repaint();
Thread.sleep(10);
if(x2>650)
x2=-650;
}
if(x>=0)
{
x=-650;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Scrolling Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Scroll1 scrolling = new Scroll1(-100);
frame.getContentPane().add(scrolling);
frame.setSize(400, 300);
frame.setVisible(true);
try {
scrolling.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Basically it has two strings that are being drawn. One starts at the 0 position and the other starts at -650. I got the -650 number by using the font metrics inside of the paint method. The problem is that I had to hard code that number, and if I did a different string that has different metrics, it would not work. I tried making a instance variable called width that stores the font metrics, but it seems that the width is not inputted until the paint method is called. Is there anyway I can get the metrics before it starts drawing it?

Is there anyway I can get the metrics before it starts drawing it?
Just initialize the variable in the first call to paint (or better yet, paintComponent - see below) - you can do this using a boolean flag, or initialize it's value to an extreme and do a check on the value.
int x = Integer.MIN_VALUE;
...
protected void paintComponent(Graphics g){
super.paintComponent(g);
if ( x == Integer.MIN_VALUE ){
x = -g.getFontMetrics().stringWidth(text);
}
...
}
Some other tips:
Use a Swing Timer to perform animation, or be sure to dispatch Swing specific calls to the EDT using SwingUtilities.
Don't override paint, rather override paintComponent (and be sure to call the parent method super.paintComponent(g))

Related

Need help positioning in java

I created this java program and I wanted an output of which if int x and int y are above 100, it would draw a rectangle. But it doesn't. How can I make it work?Is there another line of code I need to add?
Here's my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class GameSetup extends JPanel implements MouseMotionListener{
public static JFrame njf = new JFrame("Test");
public static int x, y;
public static void main(String[] args){
GameSetup gs = new GameSetup();
njf.add(gs);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.GREEN);
g.fillRect(150, 75, 200, 100);
g.setColor(Color.ORANGE);
g.drawString("Play", 239, 123);
njf.addMouseListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}
});
if(x > 100 && y > 100){
g.drawRect(10, 10, 100, 100);
}
}
public GameSetup(){
njf.setSize(500,500);
njf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
njf.setResizable(false);
njf.setLocationRelativeTo(null);
njf.setVisible(true);
}
#Override
public void mouseDragged(MouseEvent arg0) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
Okay, there are several things wrong with the code that you included above.
The first that stood out to me was the way that you are adding the mouse action listener to frame. There are multiple things that are wrong with this.
First of all, you are doing this in the paintComponent method, which, if it works, is still considered to be bad practice because the paintComponent method may be called multiple times. Do that, as pointed out by the comments, in the constructor of the panel.
The second is that you are adding the mouse listener to the frame, not the panel, which doesn't work because the panel is "above" the frame, so the mouse event will only be recognized within the panel. Your best bet here is to add a MouseMotionListener directly to the panel itself.
The third is that you are implementing the MouseMotionListenerinterface in the GameSetup class, but never actually doing anything with this implementation. So what I did was that I got rid of the inner class, and just had the panel be its own MouseMotionListnener
The second thing that is wrong with the code is that the paintComponent method is only called at certain points in time (see this). That means that even though the mouse might have moved within the zone, your paintComponent method isn't being called to update the screen accordingly. For this, you need to call the repaint method for your panel.
The third is that you didn't set a size for your panel, and the default one is 0x0, so you need to set a size of your panel (which should be the same as the frame itself) (if you want to keep the default layout).
All of that being said, here is your code that I fixed up. I added a variable called enteredZone to keep track of if the mouse had previously entered the zone, so that the rectangle would stay up even if the mouse left the zone after entering it (its your choice if you want to keep it). Note that there are other things with this code that might be considered bad practice, but this is enough to get you started:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class GameSetup extends JPanel implements MouseMotionListener {
public static JFrame njf = new JFrame("Test");
public static int x = 0, y = 0;
public static boolean enteredZone = false;
public static void main(String[] args) {
GameSetup gs = new GameSetup();
gs.addMouseMotionListener(gs);
njf.add(gs);
njf.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.GREEN);
g.fillRect(150, 75, 200, 100);
g.setColor(Color.ORANGE);
g.drawString("Play", 239, 123);
if (x > 100 && y > 100 || enteredZone){
g.drawRect(10, 10, 100, 100);
enteredZone = true;
}
}
public GameSetup() {
super();
setSize(500, 500);
njf.setSize(500,500);
njf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
njf.setResizable(false);
njf.setLocationRelativeTo(null);
}
#Override
public void mouseDragged(MouseEvent arg0) {
}
#Override
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
if (x > 100 && y > 100) repaint();
}
}

Java Mousepress() to draw images

I create this to draw a fish when the mouse is pressed at the mouse's x and y coordinate. but i seems then that the drawfish method is not being called. I can't find the reason why is it is not working. I would be me very grateful for any help.
/*FishTank*/
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
/*FishTank class-contains a frame and the WinstonCanvas.*/
public class FishTank{
public static void main ( String[] args ){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame window = new JFrame();
window.setTitle("Fish Tank");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 700, 430);
window.getContentPane().add(new FishTankCanvas());
window.setVisible(true);
}
});
}
}
/*FishTankCanvas is a component that allows drawing shapes.*/
class FishTankCanvas extends JComponent {
static Graphics2D g;
int x = 11;
Timer myTimer;
public FishTankCanvas(){
myTimer = new Timer (2, new ActionListener(){
public void actionPerformed (ActionEvent evt){
repaint();
}
});
myTimer.start();
}
public void paint(Graphics graphics) {
g = (Graphics2D)graphics;
//makes the background white
Color backgroundColor = new Color(89, 216, 255);//light blue
g.setColor(backgroundColor);
g.fillRect(0,0,this.getWidth(),this.getHeight());
// drawfish (Graphics graphics, int bodyX, int bodyY, int bodyLength,int bodyHeight, int tailwidth, int eyesize,int tailcolor, int bodycolor)
// Mouselistener and mouseadapter
this.addMouseListener (new MouseAdapter() {
public void mousePressed(MouseEvent e) {
//call drawfish method
drawfish(FishTankCanvas.g,e.getX(), e.getY(),118,74,1,((int) (Math.random()*(4 - 0))));
repaint();
}
});
// x coordinate plus 1 of fish (animate)
x= x + 1;
}
// drawfish method
public void drawfish(Graphics graphics, int bodyX, int bodyY, int bodyLength,int bodyHeight,int tailcolor, int bodycolor ){
Graphics2D g = (Graphics2D)graphics;
bodyX +=x;
//colours
Color[] colours= new Color[5];
colours[0] = new Color(0, 0, 0);//black
colours[1] = new Color(162, 0, 255);//purple
colours[2] = Color.red;//red
colours[3] = new Color(255,255,0);// yellow
colours[4] = new Color(60,179,113);//green
//draw fish
// body
g.setColor(colours[bodycolor]);
g.fillOval(bodyX, bodyY, bodyLength, bodyHeight);
// tail
g.setColor(colours[tailcolor]);
int tailWidth = bodyLength/4;
int tailHeight = bodyHeight/2;
int[] tailPointx = new int[3];
int[] tailPointy = new int[3];
tailPointx[0]=bodyX;
tailPointy[0]=bodyY+bodyHeight/2;
tailPointx[1]=bodyX-tailWidth;
tailPointy[1]=bodyY+bodyHeight/2-tailHeight;
tailPointx[2]=bodyX-tailWidth;
tailPointy[2]=bodyY+tailHeight+tailHeight;
g.fillPolygon(tailPointx, tailPointy, 3);
// eye
g.setColor(colours[0]);
g.fillOval(bodyX+3*bodyLength/4, bodyY+bodyHeight/2-bodyHeight/5, bodyHeight/5, bodyHeight/5);
}
}
i seems then that the drawfish method is not being called.
Well that is easy enough to verify. All you need to do is add debug code to the method to determine if this is true or not. Then you can tell us if that is the problem instead of guessing.
Other problems:
Don't add the MouseListener to the component in a painting method. The listener should be added in the constructor of your class.
Don't override paint(). Custom painting is done by overriding the paintComponent() method. And don't forget to invoke super.paintComponent(...).
Extend JPanel instead of JComponent. Then you can just use the setBackground() method to paint the background.
However, the real problem is that when you click the mouse the fish might get drawn, but then the Timer does a repaint which will clear the panel 2ms later, so you never really see the fish. Get rid of the Timer. There is no need for the Timer to draw a fish.
Assuming you want to paint multiple fish you need to keep track of every place you click and then paint all the fish. The two way of doing this are:
Keep an ArrayList of the points where you want to paint the fish and then iterate through this list in your painting method
Paint the fish on a BufferedImage when the mouse click happens, and then just paint the image.
See Custom Painting Approaches for working examples of both of these approaches.

Timer of swing not performing as expected

I was suggested not to use sleep for pausing purpose and instead use swing timer but still its not working.The animation i want to achieve is a ball travelling from the top left corner diagonally towards the bottom.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Show_starter {
int x, y;
JFrame window = new JFrame("Graphic_show");
Graphic_panel jp = new Graphic_panel();
public static void main(String[] args) {
Show_starter start = new Show_starter();
start.go();
}
private void go() {
window.getContentPane().add(BorderLayout.CENTER, jp);
window.setSize(600,800);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class Graphic_panel extends JPanel {
public void paintComponent(Graphics g) {
for ( int i = 0; i < 100; ++i) {
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
x++;
y++;
try {
Timer tmr = new Timer(1000, new TimerListener()); //This fires an event after every 1 sec after it has started by start().
//But The ball travels too much fast and stops at a point and again travels very fast.
tmr.serRepeats(false); // even this is not working.
tmr.start();
//should i use repaint here or in Listener for this timer?
} catch (Exception e){}
}
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
jp.repaint();
}
}
}
}
The behaviour it is showing is very odd ball first goes at very high speed and stops momentarily at a point and again moves at same speed.
I have also tried to change the time for timer event to fire but the same thing happens.
Even inside loop where I have started timer the follow function call is not working
setRepeats(false);
don't create new timers always one timer is enough .decrees timing interval bit more .1 second is too slow for a animation.you don't need a loop and don't increment x and y inside paintcomponet() method because this method get called for some reason for example when you resize,minimize,maximize.
the unexpected behavior is due to your loop and creating new timers(). for example in x y start at zero but in first second x y increased to 100,100 in next paint you see them in a 100,100 position .that's look like quick move and then stop ...
example code (edited)
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Show_starter {
private Timer tmr;
int x, y;
JFrame window = new JFrame("Graphic_show");
Graphic_panel jp = new Graphic_panel();
public static void main(String[] args) {
Show_starter start = new Show_starter();
start.go();
}
private void go() {
window.getContentPane().add(BorderLayout.CENTER, jp);
window.setSize(600, 800);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tmr = new Timer(10, new ActionListener() { // time gap in millisecond
#Override
public void actionPerformed(ActionEvent ae) {
jp.increse();
jp.repaint();
}
});
tmr.start();
}
class Graphic_panel extends JPanel {
public void increse() {
x++;
y++;
if (x > 100) { // stop animation at x>100
tmr.stop();
}
}
public void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
}
}
output (smoother than that)
Firstly you should not use a loop inside paint component.
public void paintComponent(Graphics g){
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
Just draw it and make x and y public in the class so that you can easily access from outside
Now run a runnable (consult invokelater and swingUtilities) or create a new Thread
inside public void run() do whatever animations you want to do . You can use a loop but add Thread.sleep(//in miliseconds) and repaint() in each iteration .
note : you need to change the x and y and repaint() so that it is drawn in a new position. And the sleep() is needed to slow down the execution otherwise it can't be visible to viewer.

Fill percentage of JTextArea background

I'm attempting to partially fill a JTextArea based on an object's member field that is between 0 and 1. If I hard code the percentage in the paintComponent function, it works great. But when I try to use the member field as the percentage value, it's always 0.0 in the debugger and no rectangle is painted behind the text.
Why are the member fields seemingly uninitialized within paintComponent()? After calling setPercent(), percentFilled is correct. (I do invalidate the container of the BarGraphText objects after their setPercent() are called.)
EDIT: setPercent() is called after an ActionListener is triggered by a button. Would the separate gui thread have something to do with this failing? It works when the class below is in a JFrame by itself. Update: Having a button change the percent and redraw the component makes no difference when I have this in a separate project.
Solved: I was clearing the values at the wrong spot in my program. I'll leave this question published.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JTextArea;
public class BarGraphText extends JTextArea {
double percentFilled;
Color fillColor;
BarGraphText( String s )
{
super(s);
setOpaque(false);
percentFilled = 0.0;
}
#Override
public void paintComponent( Graphics g )
{
int width, height;
Rectangle bounds = g.getClipBounds();
if( bounds != null )
{
height = bounds.height;
width = bounds.width;
}
else
{
System.err.println("Error [BarGraphText]: Clipping bounds unknown.");
height = width = 0;
}
g.setColor(fillColor);
g.fillRect(0, 0, (int) (width*percentFilled), height);
super.paintComponent(g);
}
public void setPercent( int myResp, int totResp )
{
percentFilled = (float)myResp / totResp;
}
public void setColor( Color c )
{
fillColor = c;
}
}
I was clearing the values at the wrong spot in my program. This is not in the code published above.

Swing double Buffering and Animation

I am trying to prevent redrawing an animation by the EDT. The first thing i have done is excluding the actual drawing tasks into a different thread, writing into a VolatileImage, which gets redrawn by EDT within paintComponent method of my corresponding JPanel.
If i exclude the repaint into another thread, this works properly. Nevertheless, i do have positioned a couple of other panels above my animation.
In result, having called the repaint method of my painter (animation) panel, has caused the others to also get redrawn without flickering.
Therefore to redraw the other panels, calling repaint on painter, results in flickering. Repaint of a single panel results in an opaque redraw with rarely flickering.
Does somebody know, how to synchronize an own repaint of a jpanel, for instance into my already available bufferimage. Id say the repaint triggered to EDT results in flickering, since its not synchronized.
My repaint call to animation
#Override
public void KeyframeChanged(Keyframe frame) {
if (painter.isVisible()) {
map.getMainMap().doPaintComponent(painter.getBuffer().getGraphics());
painter.renderAnimation();
painter.updateScreen();
}
}
painter methods:
public void updateScreen() {
Graphics g = this.getGraphics();
if (g != null) // component already visible?
{
// is there a backBuffer to draw?
if (backBuffer != null) {
g.drawImage(backBuffer, 0, 0, null);
} else {
// if not, create one and render on it
createBackBuffer();
renderAnimation();
}
}
}
public void renderAnimation() {
// Do drawing stuff here
}
#Override
protected void paintComponent(Graphics g) {
// super.paintComponent(g);
}// end of paint
Thanks
Thanks for answers and links. I still need to read a few of them. Nevertheless in order to illustrate the current behavior, this small SSCCE shall help.
package repaintexample;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.VolatileImage;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
class Painter extends JPanel {
private VolatileImage backBuffer;
private Graphics2D g2d;
public Painter() {
setDoubleBuffered(false);
setOpaque(false);
}
#Override
public boolean isOptimizedDrawingEnabled() {
return false;
}
private void createBackBuffer() {
backBuffer = this.getGraphicsConfiguration().createCompatibleVolatileImage(1920, 1200);
}
public void adjustBackBufferSize() {
if (backBuffer != null) {
if (getWidth() > backBuffer.getWidth() || getHeight() > backBuffer.getHeight()) {
createBackBuffer();
}
}
}
public void updateScreen(Graphics g) {
if (g != null) // component already visible?
{
// is there a backBuffer to draw?
if (backBuffer != null) {
g.drawImage(backBuffer, 0, 0, null);
} else {
// if not, create one and render on it
createBackBuffer();
}
}
}
public void renderAnimation(int i, int j) {
if (backBuffer == null) {
createBackBuffer();
}
do {
if (backBuffer.validate(getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE) {
createBackBuffer();
}
g2d = (Graphics2D) backBuffer.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.white);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setColor(Color.red);
g2d.fillOval(i, j, 50, 50);
} while (backBuffer.contentsLost());
}
#Override
protected void paintComponent(Graphics g) {
// super.paintComponent(g);
updateScreen(g);
}// end of paint
public VolatileImage getBuffer() {
return backBuffer;
}
}
class ContainerFrame extends JFrame {
private Painter mapPainter;
private JPanel informationPanel; // covers a lot of metainformation - Actually own JTable instance updating the same objects for repainting in each circle
private JPanel controller; // Maptools
private JPanel tabbedPabe; // Change redraw content
public ContainerFrame() {
this.setSize(1600, 1024);
this.setVisible(true);
initComponents();
initPositions();
Thread animation = new Thread(new Runnable() {
#Override
public void run() {
// My application is a mapping application, in which i first draw the tiles, before goin on with the "real" animated stuff
// clearing backbuffer content with g.fillRect(0, 0, getWidth(), getHeight());
while (true) {
for (int i = 0; i < mapPainter.getWidth(); i += 100) {
for (int j = 0; j < mapPainter.getHeight(); j += 5) {
mapPainter.renderAnimation(i, j);
int repaintCase = 2;
switch (repaintCase) {
case 0:
// Default case redrawing via EDT, triggering the others in proper order
mapPainter.repaint();
break;
case 1:
// case repainting by current Thread - necessity of repainting above positioned panels
// results in flickering, since not synchronized
mapPainter.updateScreen(mapPainter.getGraphics());
informationPanel.repaint();
controller.repaint();
tabbedPabe.repaint();
break;
case 2:
// painting components on buffer
// Results in rarely flickering and opague repaint
// is there any common way, to manually repaint onto anything - like image
informationPanel.paintAll(mapPainter.getBuffer().getGraphics());
controller.paintAll(mapPainter.getBuffer().getGraphics());
tabbedPabe.paintAll(mapPainter.getBuffer().getGraphics());
mapPainter.updateScreen(mapPainter.getGraphics());
break;
}
}
}
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
animation.start();
}
private void initComponents() {
mapPainter = new Painter();
mapPainter.setSize(this.getSize());
informationPanel = new JPanel();
informationPanel.setSize(new Dimension(360, 800));
controller = new JPanel();
controller.setSize(new Dimension(500, 250));
tabbedPabe = new JPanel();
tabbedPabe.setSize(new Dimension(300, 300));
this.getLayeredPane().add(mapPainter, JLayeredPane.DEFAULT_LAYER);
this.getLayeredPane().add(controller, JLayeredPane.MODAL_LAYER);
this.getLayeredPane().add(tabbedPabe, JLayeredPane.MODAL_LAYER);
this.getLayeredPane().add(informationPanel, JLayeredPane.MODAL_LAYER);
}
private void initPositions() {
controller.setLocation(mapPainter.getWidth() - controller.getWidth(), mapPainter.getHeight() - controller.getHeight());
tabbedPabe.setLocation(this.getWidth() - tabbedPabe.getWidth(), mapPainter.getHeight() - controller.getHeight() - tabbedPabe.getHeight() - 400);
informationPanel.setLocation(10, mapPainter.getHeight() - informationPanel.getHeight() - 200);
}
}
public class RepaintExample {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ContainerFrame f = new ContainerFrame();
}
}
I do use case 0 at the moment and do see having either great or pretty bad fps - either 30 or around 6. I am not certain, how that may be possible and i may be able to find sth. in the already posted links. I thought making sure to relieve the EDT at best, could become a proper solution.
Additionally the content of the 3 panels, i illustrated do not need a repaint in the same frequency as the animation does. Unfortunately i haven't found a proper way to prevent the repaint. The only way i have used for quite a while was a paintimmediately in an invokelater call for those areas, which are known as "animated". A common repaint(Rectangle rec) has not been working, since single calls have been summarized to a big one, covering more pixels, than i have passed in.
public void drawCachedSprite(Graphics2D g, CachedSprites sprites, int zoom, double cog, double x, double y, double w, double h) {
try{
pos_x = x;
pos_y = y;
RenderingUtil.getRenderQuality();
transform.setToIdentity();
// Compute the corner, the drawing needs to start with
transform.translate(x - (w / 2.0), y - (h / 2.0));
g.drawImage(sprites.getSprite(DefaultResources.getType(), spriteColor, zoom, cog), transform, null);
} catch (IllegalArgumentException e) {
e.printStackTrace();
System.out.println("width or height not set properly");
}
}

Categories