我想绘制由.form创建的子面板。有一个“mainPanel”,它包含三个名为panel1(顶部),panel2(左下角)和panel3(右下角)的子面板。
现在我想在subPanel“panel1”上画一些东西,但它不起作用。当我运行程序时,它只显示那里的三个子面板,但没有我的“paintComponent()”方法的图纸。
我在这里粘贴了我的代码,有人可以帮我检查一下是什么问题吗?非常感谢。
public class PanelDrawTest extends JFrame {
private JPanel mainPanel;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
public PanelDrawTest(){
getContentPane().add(mainPanel);
setPanel1(new MyPanel1());
}
public JPanel getMainPanel() {
return mainPanel;
}
public JPanel getPanel1() {
return panel1;
}
public void setPanel1(JPanel panel1) {
this.panel1 = panel1;
}
private class MyPanel1 extends JPanel {
public MyPanel1(){
}
@Override
public void paintComponent(Graphics g){
g.drawString("This is Panel 1",20,20);
g.drawRect(0,200,100,200);
}
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
PanelDrawTest frame = new PanelDrawTest();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 50, 1200, 700);
frame.setPreferredSize(new Dimension(1200,800));
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:1)
注意:发布的代码会抛出NullPointerException,因为mainPanel从未初始化。
构造函数没有将自定义面板添加到布局中,这就是无法看到它的原因。 试试这个,你会看到你的画:
public PanelDrawTest() {
mainPanel = new JPanel();
getContentPane().add(mainPanel,BorderLayout.NORTH);
panel1 = new MyPanel1();
getContentPane().add(panel1,BorderLayout.CENTER);
}
答案 1 :(得分:1)
您的版本不能为我运行,但这样做有效:
public class PanelDrawTest extends JFrame {
private JPanel mainPanel = new JPanel(); // I added a constructor to avoid NullPointerexception
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
public PanelDrawTest(){
getContentPane().add(mainPanel);
setPanel1(new MyPanel1());
add(panel1); // and I added the panel
}
public JPanel getMainPanel() {
return mainPanel;
}
public JPanel getPanel1() {
return panel1;
}
public void setPanel1(JPanel panel1) {
this.panel1 = panel1;
}
private class MyPanel1 extends JPanel {
public MyPanel1(){
}
@Override
public void paintComponent(Graphics g){
g.drawString("This is Panel 1",20,20);
g.drawRect(0,200,100,200);
}
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
PanelDrawTest frame = new PanelDrawTest();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 50, 1200, 700);
frame.setPreferredSize(new Dimension(1200,800));
frame.pack();
frame.setVisible(true);
}
}