我如何在JFrames中使用2类绘画通过Netbeans中的Palette生成代码


public class DrawST extends javax.swing.JFrame {
/**
* Creates new form DrawST
*/


public DrawST() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
Generated code
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DrawST().setVisible(true);
}
});
}
class Class01 extends JPanel{
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
class Class02 extends JPanel{
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
}
}
// Variables declaration - do not modify                     
// End of variables declaration                   
}

如何在这个JFrame中同时使用Class01Class02进行绘制,Class01将绘制管道,Class02将绘制青蛙(快乐青蛙(。我尝试创建Container contain = getContentPane();并添加两个类。但只增加了1个类。如果我添加两个类,JFrame将不会绘制任何内容。

您犯了一个常见的错误:当Swing组件应该是逻辑类,而不是组件类时,创建扩展Swing组件的绘图类:

  • 如果您正在制作动画,通常只有一个组件,通常由JPanel绘制,这意味着paintComponent方法在一个组件中被覆盖
  • 如果您希望一个类绘制特定的精灵,如青蛙或管道,那么这些精灵将在上述相同的单个绘制类中绘制
  • 组件类,即扩展Swing GUI组件(如JPanels(的类,通常作为组件放置在GUI中,这些组件是GUI的构建块,放置在GUI的有限位置,并且只绘制自己及其子级
  • 因此,要绘制多个精灵占据同一绘图空间的绘图,创建这些精灵的类不应扩展JPanel或类似的Swing组件,而应仅为逻辑类(不是组件的类(,然后由单个绘图JPanel绘制

例如

public class DrawST extends javax.swing.JFrame {

public DrawST() {
// add the DrawingPanel to the JFrame here
}

}
// this class extends JPanel and does *all* the drawing
public class DrawingPanel extends JPanel {
private Frog frog = new Frog(0, 0);
private List<Pipe> pipes = new ArrayList<>();
private Timer timer; // you'll probably need a Swing Timer to drive the animation

// a single paintComponent method is present
protected void paintComponent(Graphics g) {
super.paintComponent(g);  // Don't forget this
frog.draw(g);  // have this component draw a frog
for (Pipe pipe : pipes) {
pipe.draw(g);  // draw all the pipes
}
}
}
// does not extend JPanel
public class Frog {
private int x;
private int y;

public Frog(int x, int y) {
this.x = x;
this.y = y;
}

public void draw(Graphics g) {
// use x, y, and g to draw a frog at x,y location 
}
}
// does not extend JPanel (not sure what a pipe is, TBH)
public class Pipe {
private int x;
private int y;
// other? length, color, width?

public void draw(Graphics g) {
// use x, y, and g to draw a pipe. 
// maybe also needs a length, color, width?
}
}

相关内容

  • 没有找到相关文章

最新更新