我需要为乐谱添加一些文本。这是我用来制作 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();
}
}
关于java - 如何在 Java 中向 JFrame 添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53798497/