import java.awt.*; import javax.swing.*; public class MyFrame extends JFrame { public MyFrame() { // Set the title and size of the frame setTitle("My Frame"); setSize(300, 300); setVisible(true); } public void paint(Graphics g) { // Set the font of the text g.setFont(new Font("Times New Roman", Font.BOLD, 20)); // Set the color of the text g.setColor(Color.RED); // Draw the text at (50, 100) g.drawString("Hello World!", 50, 100); } public static void main(String args[]) { new MyFrame(); } }
import java.awt.*; import javax.swing.*; public class MyPanel extends JPanel { public MyPanel() { // Set the preferred size of the panel setPreferredSize(new Dimension(300, 300)); } public void paintComponent(Graphics g) { // Set the font of the text g.setFont(new Font("Arial", Font.BOLD, 30)); // Set the color of the text g.setColor(Color.BLUE); // Draw the text at the center of the panel String text = "Hello World!"; FontMetrics fm = g.getFontMetrics(); int textWidth = fm.stringWidth(text); int x = (getWidth() - textWidth) / 2; int y = getHeight() / 2; g.drawString(text, x, y); } public static void main(String args[]) { JFrame frame = new JFrame("My Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new MyPanel()); frame.pack(); frame.setVisible(true); } }In this example, we create a new JPanel and set the font of the text using the setFont() method. The font is set to Arial, bold, and with a size of 30. We then set the color of the text to blue and draw the text "Hello World!" at the center of the panel using the drawString() method. Package library: java.awt