我正在使用Java Eclipse和Swing Designer,我试图在JPanel上显示一些图形。 我是一个非常业余的程序员,也是图形编码的新手。
基本上,有一个带有2个JPanel(Stage和Setttings)的JFrame。 Surface类中有一个方法paintTest。此方法应在舞台JPanel上绘制字符串'This is a test'。 当我执行代码时没有错误。 任何帮助将不胜感激。
请参阅以下代码。
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Window;
public class TestSimulator extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frmTestSimulation;
private JPanel stagePanel = new JPanel();
private JLabel stageLabel = new JLabel("Stage");
private JPanel settingsPanel = new JPanel();
private JLabel settingsLabel = new JLabel("Settings");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestSimulator window = new TestSimulator();
window.frmTestSimulation.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestSimulator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTestSimulation = new JFrame();
frmTestSimulation.setTitle("WAPP Simulation");
frmTestSimulation.setBounds(100, 100, 727, 500);
frmTestSimulation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTestSimulation.getContentPane().setLayout(null);
//JPanel stagePanel = new JPanel();
stagePanel.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
stagePanel.setBounds(262, 11, 439, 439);
frmTestSimulation.getContentPane().add(stagePanel);
stagePanel.setLayout(null);
stagePanel.add(new Surface()); //Show the string 'This is a test'
//JLabel stageLabel = new JLabel("Stage");
stageLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
stageLabel.setBounds(183, 11, 53, 34);
stagePanel.add(stageLabel);
//JPanel settingsPanel = new JPanel();
settingsPanel.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
settingsPanel.setBounds(10, 11, 242, 439);
frmTestSimulation.getContentPane().add(settingsPanel);
settingsPanel.setLayout(null);
//JLabel settingsLabel = new JLabel("Settings");
settingsLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
settingsLabel.setBounds(78, 11, 71, 22);
settingsPanel.add(settingsLabel);
}
class Surface extends JPanel{
public void paintTest(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("This is a test", 50, 50);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
paintTest(g);
}
}
}
答案 0 :(得分:3)
您的stagePanel缺少布局,因此只会打印其中的一个组件。变化
stagePanel.setLayout(null);
到
stagePanel.setLayout(new GridLayout(1, 2));
它应该显示类似
的内容有关Swing和this website中布局的详细信息,请参阅this answer,了解有关在JPanel中显示自定义内容的详情。