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
}
如何同时使用Class01
和Class02
在此JFrame中进行绘制,Class01
将绘制管道,Class02
code> 将画 Frog (快乐 Frog )。我尝试创建 Container contains = getContentPane(); 并添加两个类。但它只能添加 1 个类。如果我添加两个类,JFrame 将不会绘制任何内容。
最佳答案
您犯了一个常见的错误:创建扩展 Swing 组件的绘图类,而它们应该是逻辑类,而不是组件类:
- 如果您正在制作动画,通常只有一个组件,通常由 JPanel 进行绘图,这意味着
paintComponent
方法在一个组件中被重写。 - 如果您希望一个类来绘制特定的 Sprite ,例如 Frog 或管道,那么这些 Sprite 将在上述相同的单个绘图类中绘制。
- 组件类,即扩展 Swing GUI 组件(例如 JPanel)的类,通常作为组件放置在 GUI 中 - GUI 的构建 block ,放置在 GUI 中的有限位置,并且仅绘制自身及其子组件。
- 因此,要绘制多个 Sprite 占据相同绘图空间的绘图,创建这些 Sprite 的类不应该扩展 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?
}
}
关于java - 如何在 JFrames 中使用 2 类绘制通过 Netbeans 中的 Palette 生成代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65156150/