我需要为得分添加一些文字。这是我用来制作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();
}
}
如果我必须输入任何框架代码,请告诉我。
答案 0 :(得分:2)
我假设您想向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();
}
}