Question

The Jlabel is not showing up when I put it in the paint(Graphics2d g) method and I can't figure out why.

My text class:

import java.awt.Color;
import java.awt.Graphics2D;

import javax.swing.JLabel;


public class Text {
    int ballX,ballY,squareX,squareY;
    Text text;
    private Game game;
    private Ball ball;
    private Racquet racquet;

    public  void main(){
        ballX = ball.getBallX();
        ballY = ball.getBallY();
        squareX = racquet.getSquareX();
        squareY = racquet.getSquareY();
    }

    public void paint(Graphics2D g) {

        g.setColor(Color.red);
        JLabel balltext = new JLabel("the ball is at " + ballX + ballY);
        balltext.setVisible(true);

        g.setColor(Color.green);
        JLabel squaretext = new JLabel("the ball is at " + squareX + squareY);
        squaretext.setVisible(true);
    }
}
Était-ce utile?

La solution

There are a few things not quite right with your code.

Firstly, Text does not extend from anything that is paintable, so paint will never be called. Convention tends to favor overriding paintComponent of Swing components anyway.

Also, you should always call super.paintXxx, this would have highlighted the problem in the first place.

Secondly, components are normally added to some kind container which takes care of painting them for you.

If you want to use Swing components in your program, I'd suggest taking a look at Creating a GUI With JFC/Swing.

If you want to paint text, I'd suggest you take a look at 2D Graphics, in particular Working with Text APIs

An bit more information about what it is you're trying to achieve might also help

Also, I'm not sure if this deliberate or not, but public void main(){ ins't going to act as the main entry point of the program, it should be public static void main(String args[]), but you might just be using main as means to call into the class from else where ;)

Autres conseils

From the look of things you are missing quite a few paradigms / idioms for a Java Swing gui.

For example:

  • Text should extend JComponent if you want to override paint / paintComponent to specify how the component should be drawn.
  • You should create a separate Main class to serve as an entrypoint to your program (you don't have to, but it helps you keep things logically separated for now, which is easier conceptualize mentally for you)
  • You need to create a JFrame inside your main method, then create the Text class and add it to JFrame and call pack() and setVisible(True) on the JFrame.

I would recommend looking at some examples first to get oriented:

http://zetcode.com/tutorials/javaswingtutorial/firstprograms/

http://www.javabeginner.com/java-swing/java-swing-tutorial

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top