如何在Java中向JFrame添加文本



我需要为分数添加一些文本。这是我用来制作JFrame的代码。请给我添加文本的代码。

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.*;
import javax.swing.JPanel;

public class Frame{
JFrame frame;
Frame()
{
frame=new JFrame("Tetris");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 600);
frame.setLayout(null);
frame.setVisible(true);
frame.setResizable(false);
ImageIcon img = new ImageIcon("Blocks.png");
frame.setIconImage(img.getImage());
frame.getContentPane().setBackground(Color.blue);
JOptionPane.showMessageDialog(null, "        Press Ok To Start","Start", JOptionPane.INFORMATION_MESSAGE);

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

如果有任何帧代码我必须键入,请告诉我。

我假设您想向JFrame的内容区域添加一些文本。我在下面添加了两种方法。看看这是否适合你。

方法1-在自定义面板上绘制文本并将其添加到框架中:

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.*;
import javax.swing.JPanel;
public class Frame{
JFrame frame;
Frame()
{
frame=new JFrame("Tetris");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 600);
frame.setLayout(null);
frame.setResizable(false);
ImageIcon img = new ImageIcon("Blocks.png");
frame.setIconImage(img.getImage());
//frame.getContentPane().setBackground(Color.blue);
frame.setContentPane(new MainPanel());
// This line is moved down
frame.setVisible(true);
JOptionPane.showMessageDialog(null, "        Press Ok To Start","Start", JOptionPane.INFORMATION_MESSAGE);   
}
public static void main(String[] args)
{
new Frame();
}
}
class MainPanel extends JPanel
{
MainPanel()
{
setOpaque(true);
setBackground(Color.blue);
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setFont(g.getFont().deriveFont(20.0F));
g.setColor(Color.white);
g.drawString("Sample text", 50, 50);
}
}

方法2-在框架中添加一个JLabel:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
public class Frame2{
JFrame frame;
Frame2()
{
frame=new JFrame("Tetris");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 600);
// *** Commented this line
//frame.setLayout(null);
frame.setResizable(false);
ImageIcon img = new ImageIcon("Blocks.png");
frame.setIconImage(img.getImage());
frame.getContentPane().setBackground(Color.blue);
// *** Added this JLabel
JLabel label = new JLabel("Sample text");
label.setFont(label.getFont().deriveFont(20.0F));
label.setForeground(Color.white);
frame.getContentPane().add(label, BorderLayout.CENTER);
// This line is moved down
frame.setVisible(true);
JOptionPane.showMessageDialog(null, "        Press Ok To Start","Start", JOptionPane.INFORMATION_MESSAGE);    
}
public static void main(String[] args)
{
new Frame2();
}
} 

最新更新