Erste Schritte Java not setting Font??

idkjavaLOL

Neues Mitglied
So I tried to make a random number generator and made the basics for the whole generator.
When I set the font with frame.getGraphics().setFont(new Font("Dialog", Font.BOLD, 30));
java doesnt take the new set font for frame.getGraphics().drawString("I have to do gen still", 187, 250);

Here is the full code:

package main;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

private String name = "Random number generator";
private Container c;
private JFrame frame;
public static JButton startButton;
boolean gameStarted = true;

public void initialise() {

frame = new JFrame("");
startButton = new JButton("Start random number generator");
startButton.setPreferredSize(new Dimension(100, 100));
startButton.setBounds(70, 180, 260, 50);
c = frame.getContentPane();
this.setLayout(null);
this.setBackground(Color.WHITE);
this.add(startButton);
c.add(this);
this.setPreferredSize(new Dimension(400, 400));
frame.setTitle(name);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);

}

public static void main(String[] args) {

Main method;
method = new Main();
method.initialise();
method.isButtonPressed();

}

public void isButtonPressed() {

while(gameStarted) {

if(startButton.getMousePosition(true) != null) {

System.out.println("U did it xd");
gameStarted = false;
startButton.setVisible(false);
frame.getGraphics().setFont(new Font("Dialog", Font.BOLD, 30));
frame.getGraphics().drawString("I have to do gen still", 187, 250);

}

}

}

}
 
The javadoc says that the method getGraphics creates a new graphic context. So the first call of getGraphics returns another instance than the second call. So you are setting the font on the first graphic context but are drawing with the second. The solution is to create the graphic context only once.

But there is another problem with this code: The UI will repaint components in some cases from time to time. When this happens your text will disappear. If you want a permanent text in the frame you have to write your own frame class (extends JFrame) and overwrite the method "paint(Graphics g)" where you can draw your String. Or better: Write your own panel class, overwrite "paintComponent(Graphics g)" and add this panel to your window.
 
Seid ihr sicher, dass das kein Crossposting ist? English speaker verirren sich selten hierhin. 🙄

Firstly you have to do putting your java code inside java code tags. Otherwise nobody will read your stuff. 😵
 

Neue Themen


Zurück
Oben