在1个JFrame中绘制多个对象

时间:2018-02-08 21:54:06

标签: java swing jframe

我试图让我的程序面向对象,并且我试图将它分成几个类。简短的版本是我想在1 JFrame中绘制不同的对象。所以我为每个想要绘制的对象创建了一个类,在我的方法中定义了对象,然后将它们添加到我的框架中。问题是只有最后一个组件被绘制在框架中。我尝试首先将对象添加到JPanel,但这似乎不起作用。

trees1

public class trees1 extends JComponent{

public final ImageIcon  pokemontree;

public trees1(){
    ImageIcon poke = new ImageIcon("pokemontree.png");

    Image image = poke.getImage(); // transform it 
    pokemontree = new ImageIcon(newimg);  // transform it back
}

public void paintComponent (Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    pokemontree.paintIcon(this,g2 , 100,200);
}
}

testing

// main program
public class testing {

public static void main(String[] args){
    JFrame win = new JFrame();
    win.setSize(600,400);
    win.setTitle("Test");
    win.setResizable(false);
    win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    trees1 exo = new trees1();
    Playerwalking p1 = new Playerwalking(1,2);
    win.add(exo);
    win.add(p1);

    win.setVisible(true);
}

1 个答案:

答案 0 :(得分:0)

JFrame内容窗格默认使用BorderLayout

默认内容窗格将包含BorderLayout。

对于BorderLayout,如果您没有指定添加的组件的位置(NORTH / EAST / SOUTH / WEST / CENTER等),则“add()”方法始终设置为“CENTER”。

您需要在组件中指定“getPreferredSize()”,还要了解如何正确使用BorderLayout(或其他布局管理器)。

public class Test1 extends JFrame {

public static void main(String[] args) throws Exception {
    JFrame win = new JFrame();
    win.setSize(600,400);
    win.setTitle("Test");
    win.setResizable(false);
    win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    win.add(new trees1(), BorderLayout.CENTER);
    win.add(new trees1(), BorderLayout.SOUTH);
    win.add(new trees1(), BorderLayout.EAST);

    win.pack();
    win.setVisible(true);
}

}

class trees1扩展了JComponent {

public final ImageIcon pokemontree;

public trees1(){
    ImageIcon poke = new ImageIcon("c:\\temp\\2.png");

    Image image = poke.getImage(); // transform it
    pokemontree = new ImageIcon(image);  // transform it back
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(pokemontree.getIconWidth(), pokemontree.getIconHeight());
}

public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    pokemontree.paintIcon(this,g2 , 0,0);
}

}