Domanda

This is my code:

package com.Bench3.simplyMining;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Keying extends JPanel {

    private static final long serialVersionUID = 1L;

    public Rectangle miningRock;
    public Rectangle Rocks;
    public int mRockW = 150;
    public int mRockH = 100;
    public long rocks = 0;
    public String rockAmount = rocks + " Rocks";

    public Keying(Display f, Images i){
        miningRock = new Rectangle(0, 658, mRockW, mRockH);
        Rocks = new Rectangle(1024, 0, 0, 0);

        f.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e){

            }

            public void keyReleased(KeyEvent e){
                /* if(e.getKeyCode() == KeyEvent.VK_A){
                    left = false;
                } -- Used for setting key combinations and stuff */
            }
        });
    }

    public void paintComponent(Graphics g){
        if(Main.f.i.imagesLoaded){
        super.paintComponent(g);

        g.drawImage(Main.f.i.miningRock, miningRock.x, miningRock.y, miningRock.width, miningRock.height, null);

        g.drawString(rockAmount, Rocks.x, Rocks.y);

        this.setBackground(Color.WHITE); // Sets background color
        // g.setColor(Color.WHITE); -- Used for setting colors

        repaint();
        }
    }
}

I've been trying to insert the string "rockAmount" into the rectangle "Rocks" using g.drawString(), but when I try it doesn't output the string inside of the rectangle. What am I doing wrong?

EDIT: Solved, thanks to Paul for providing the answer.

È stato utile?

Soluzione 2

You need to add to x and y position 1/2 of the width and height of the rectangle.

g.drawString(rockAmount,Rocks.x+rectangleWidth/2,Rocks.y+rectangleHeight/2);

Altri suggerimenti

The y position of text represents the base line minus the font ascent. This means that it appears that text is rendered above the y position.

When rendering text, you need to take into consideration the FontMetrics of the text and font.

For example, the following renders the text at the rectangles x/y position on the left and then calculates the x/y position so it can centre the text within the give rectangle.

enter image description here

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTextRect {

    public static void main(String[] args) {
        new TestTextRect();
    }

    public TestTextRect() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            int mRockW = 150;
            int mRockH = 100;
            int x = ((getWidth() / 2) - mRockW) / 2;
            int y = (getHeight() - mRockH) / 2;
            badRect(g2d, x, y, mRockW, mRockH);

            x = (getWidth() / 2) + (((getWidth() / 2) - mRockW) / 2);
            goodRect(g2d, x, y, mRockW, mRockH);

            g2d.dispose();
        }

        protected void badRect(Graphics2D g2d, int x, int y, int mRockW, int mRockH) {
            g2d.drawRect(x, y, mRockW, mRockH);
            String text = "rockAmount";

            g2d.drawString(text, x, y);
        }

        protected void goodRect(Graphics2D g2d, int x, int y, int mRockW, int mRockH) {
            g2d.drawRect(x, y, mRockW, mRockH);
            FontMetrics fm = g2d.getFontMetrics();
            String text = "rockAmount";

            x = x + ((mRockW - fm.stringWidth(text)) / 2);
            y = (y + ((mRockH - fm.getHeight()) / 2)) + fm.getAscent();
            g2d.drawString(text, x, y);
        }

    }

}

Take a look at Working with text APIs for more details

You should avoid calling repaint or any method that might call repaint from within your paintXxx methods. Because of the way painting is scheduled in Swing, this will set up an infinite loop that will eventually consume you CPU cycles and make your application unresponsive...

You should, also, always call super.paintComponent, regardless of what ever else you want to do...

I would also recommend Key bindings over KeyListener as it provides better control over the focus level

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top