从子类调用 awt Frame 方法

发布于 2024-11-01 11:28:37 字数 3827 浏览 4 评论 0原文

这个问题是关于框架、Java 和处理

这个问题听起来很复杂,但实际上并非如此。我会尽力将其保持在最低限度。我正在迷宫游戏中创建一个小球,以让我了解物理和渲染。到目前为止,这是一次很好的经历,但我遇到了一些困难。
我决定的总体布局是将 PApplet 包含在 AWT 框架内并关闭该框架。这样做的原因是因为有人告诉我一次只能有一个 Papplet 实例。

PApplet 是渲染库 Processing 中的 Applet 类。

我这里有 3 个类,包括主要的

public class Menu extends PApplet
{
//images and buttons 
PImage background, playbtn1, playbtn2, hsbtn1, hsbtn2, abbtn1, abbtn2, exbtn1,     exbtn2;
FBox pBtn, hBtn, eBtn;

FWorld menu;

//simple constructor
public Menu()
{

}

public void setup()
{
    size(600, 400);
    smooth();
    Fisica.init(this);
    menu = new FWorld();

    //loading and placing images
    background = loadImage("MenuAlt.jpg");
    System.out.println(background);
    playbtn1 = loadImage("play1.gif");
    playbtn2 = loadImage("play2.gif");
    hsbtn1 = loadImage("high1.gif");
    hsbtn2 = loadImage("high2.gif");
    exbtn1 = loadImage("exit1.gif");
    exbtn2 = loadImage("exit2.gif");

    //loading and placing buttons
    pBtn = new FBox(120, 150);
    pBtn.setPosition(135, 215);
    pBtn.setDrawable(false);
    hBtn = new FBox(120, 150);
    hBtn.setPosition(295, 215);
    hBtn.setDrawable(false);
    eBtn = new FBox(120, 150);
    eBtn.setPosition(455, 215);
    eBtn.setDrawable(false);

    //add item to world
    menu.add(pBtn);
    menu.add(hBtn);
    menu.add(eBtn);
}

public void draw()
{
    image(background, 0, 0);
    image(playbtn1, 80, 140);
    image(hsbtn1, 237, 135);
    image(exbtn1, 400, 140);

    mouseOver();
    menu.draw();
}

//close this frame an open a new level, high score or exit
//depending on what the use clicks
public void mousePressed()
{
    FBody pressed = menu.getBody(mouseX, mouseY);
    if (pressed == pBtn)
    {
        System.out.println("play game");
        this.getParent().getParent().getParent().getParent().setVisible(false);

        ExampleFrame x = new ExampleFrame(new Level("level1.txt"));
        x.setLocation(this.getParent().getParent().getParent().getParent().getLocation());
    }
    if (pressed == hBtn)
    {
        System.out.println("high scores");
        this.getParent().getParent().getParent().getParent().setVisible(false);

        /* these are just for finding the parent
 System.out.println(this.getName());
 System.out.println(this.getParent().getName());
 System.out.println(this.getParent().getParent().getName());
 System.out.println(this.getParent().getParent().getParent().getName());
 System.out.println(this.getParent().getParent().getParent().getParent().getName());
         */
        ExampleFrame x = new ExampleFrame(new HighScores()); //for testing, you can change this to new menu()
        x.setLocation(this.getParent().getParent().getParent().getParent().getLocation());
    }
    if (pressed == eBtn)
    {
        System.out.println("exit");
        System.exit(0);
    }
}

exampleFrame 类,

public class ExampleFrame extends JFrame
{
    PApplet app;

    public ExampleFrame(PApplet emApp)
    {
        super("Ball Maze Game");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(200, 200);

        app = emApp;
        setSize(615,438);
        setVisible(true);

        setLayout(new BorderLayout());

        add(app, BorderLayout.CENTER);
        app.init();
    }
}

主要的

public class Main
{
    public static void main(String[] args) 
    {
        ExampleFrame x = new ExampleFrame(new Menu());
    }
}

当 mousePressed == ebtn 时需要发生什么,框架中的所有内容都将被删除,并且将加载高分屏幕。高分几乎与菜单相同。无需发布代码,因为这里已经足够了。

第二类是充当框架并保留 PApplet

底线的类,有谁知道如何从 PApplet 调用 Frame 方法或以其他方式删除所有 PApplet 内容并加载另一个 PApplet 吗?

This question is about Frames, Java and Processing.

This questions sounds pretty convoluted but its really not. I'll try keep this to a simple minimum. I'm creating a small ball in a maze game to get my head around physics and rendering. It's been a good experience so far but I've hit a bit of a brick wall.
The general layout I decided on was to contain PApplets within a AWT Frame and have the Frame close. The reason for this is because I was told that you should only have on instance of a Papplet at a time.

PApplet is the Applet class in Processing, a rendering library.

I have 3 classes here including the main

public class Menu extends PApplet
{
//images and buttons 
PImage background, playbtn1, playbtn2, hsbtn1, hsbtn2, abbtn1, abbtn2, exbtn1,     exbtn2;
FBox pBtn, hBtn, eBtn;

FWorld menu;

//simple constructor
public Menu()
{

}

public void setup()
{
    size(600, 400);
    smooth();
    Fisica.init(this);
    menu = new FWorld();

    //loading and placing images
    background = loadImage("MenuAlt.jpg");
    System.out.println(background);
    playbtn1 = loadImage("play1.gif");
    playbtn2 = loadImage("play2.gif");
    hsbtn1 = loadImage("high1.gif");
    hsbtn2 = loadImage("high2.gif");
    exbtn1 = loadImage("exit1.gif");
    exbtn2 = loadImage("exit2.gif");

    //loading and placing buttons
    pBtn = new FBox(120, 150);
    pBtn.setPosition(135, 215);
    pBtn.setDrawable(false);
    hBtn = new FBox(120, 150);
    hBtn.setPosition(295, 215);
    hBtn.setDrawable(false);
    eBtn = new FBox(120, 150);
    eBtn.setPosition(455, 215);
    eBtn.setDrawable(false);

    //add item to world
    menu.add(pBtn);
    menu.add(hBtn);
    menu.add(eBtn);
}

public void draw()
{
    image(background, 0, 0);
    image(playbtn1, 80, 140);
    image(hsbtn1, 237, 135);
    image(exbtn1, 400, 140);

    mouseOver();
    menu.draw();
}

//close this frame an open a new level, high score or exit
//depending on what the use clicks
public void mousePressed()
{
    FBody pressed = menu.getBody(mouseX, mouseY);
    if (pressed == pBtn)
    {
        System.out.println("play game");
        this.getParent().getParent().getParent().getParent().setVisible(false);

        ExampleFrame x = new ExampleFrame(new Level("level1.txt"));
        x.setLocation(this.getParent().getParent().getParent().getParent().getLocation());
    }
    if (pressed == hBtn)
    {
        System.out.println("high scores");
        this.getParent().getParent().getParent().getParent().setVisible(false);

        /* these are just for finding the parent
 System.out.println(this.getName());
 System.out.println(this.getParent().getName());
 System.out.println(this.getParent().getParent().getName());
 System.out.println(this.getParent().getParent().getParent().getName());
 System.out.println(this.getParent().getParent().getParent().getParent().getName());
         */
        ExampleFrame x = new ExampleFrame(new HighScores()); //for testing, you can change this to new menu()
        x.setLocation(this.getParent().getParent().getParent().getParent().getLocation());
    }
    if (pressed == eBtn)
    {
        System.out.println("exit");
        System.exit(0);
    }
}

the exampleFrame class

public class ExampleFrame extends JFrame
{
    PApplet app;

    public ExampleFrame(PApplet emApp)
    {
        super("Ball Maze Game");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(200, 200);

        app = emApp;
        setSize(615,438);
        setVisible(true);

        setLayout(new BorderLayout());

        add(app, BorderLayout.CENTER);
        app.init();
    }
}

the main

public class Main
{
    public static void main(String[] args) 
    {
        ExampleFrame x = new ExampleFrame(new Menu());
    }
}

What needs to happen when mousePressed == ebtn is all the stuff in the Frame will be removed and a Highscores Screen will be loaded. highscores is almost the same as menu. There is no need to post code as there is enough here.

The second class is the one which acts as a frame and holds the PApplet

Bottom line, has anyone have any idea how to call the Frame methods from the PApplet or another way to remove all PApplets contents and load another PApplet in?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千纸鹤带着心事 2024-11-08 11:28:37

当 mousePressed == ebtn 时需要发生什么,框架中的所有内容都将被删除并加载高分屏幕

演示。下面的嵌套 CardLayout 添加了一个 ActionListener 而不是 MouseListener。它对鼠标键盘输入做出反应。

有多种其他方法可以在同一屏幕空间中包含多个 GUI 元素。 JTabbedPaneJSplitPaneJDesktopPane/JInternalFrame,在 JTabbedPaneJDesktopPane/JInternalFrame 中弹出高分 < code>JDialog 或 JOptionPane..

屏幕截图

游戏视图 高分视图

CardLayoutDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CardLayoutDemo {

    public static void main(String[] args) {

        Runnable r = new Runnable () {
            public void run() {
                final JRadioButton game = new JRadioButton("Game", true);
                JRadioButton highScores = new JRadioButton("High Scores");

                ButtonGroup bg = new ButtonGroup();
                bg.add( game );
                bg.add( highScores );

                JPanel buttons = new JPanel(new 
                    FlowLayout(FlowLayout.CENTER, 5, 5));
                buttons.add( game );
                buttons.add( highScores );

                JPanel gui = new JPanel(new BorderLayout(5,5));
                gui.add(buttons, BorderLayout.SOUTH);

                final CardLayout cl = new CardLayout();
                final JPanel cards = new JPanel(cl);
                gui.add(cards);
                cards.add(new JLabel("Level 1"), "game");
                cards.add(new JLabel("High Scores"), "scores");

                ActionListener al = new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        if (game.isSelected()) {
                            cl.show(cards, "game");
                        } else {
                            cl.show(cards, "scores");
                        }
                    }
                };
                game.addActionListener(al);
                highScores.addActionListener(al);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

What needs to happen when mousePressed == ebtn is all the stuff in the Frame will be removed and a Highscores Screen will be loaded

The demo. below of a nested CardLayout adds an ActionListener instead of a MouseListener. It reacts to both mouse and keyboard input.

There are a multitude of other ways to include more than one GUI element in the same screen space. Off the top of my head, JTabbedPane, JSplitPane, JDesktopPane/JInternalFrame, popping the high scores in a JDialog or JOptionPane..

Screenshots

Game view High Scores view

CardLayoutDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CardLayoutDemo {

    public static void main(String[] args) {

        Runnable r = new Runnable () {
            public void run() {
                final JRadioButton game = new JRadioButton("Game", true);
                JRadioButton highScores = new JRadioButton("High Scores");

                ButtonGroup bg = new ButtonGroup();
                bg.add( game );
                bg.add( highScores );

                JPanel buttons = new JPanel(new 
                    FlowLayout(FlowLayout.CENTER, 5, 5));
                buttons.add( game );
                buttons.add( highScores );

                JPanel gui = new JPanel(new BorderLayout(5,5));
                gui.add(buttons, BorderLayout.SOUTH);

                final CardLayout cl = new CardLayout();
                final JPanel cards = new JPanel(cl);
                gui.add(cards);
                cards.add(new JLabel("Level 1"), "game");
                cards.add(new JLabel("High Scores"), "scores");

                ActionListener al = new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        if (game.isSelected()) {
                            cl.show(cards, "game");
                        } else {
                            cl.show(cards, "scores");
                        }
                    }
                };
                game.addActionListener(al);
                highScores.addActionListener(al);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
冰雪梦之恋 2024-11-08 11:28:37

为了回答如何从 PApplet 调用 Frame 方法?,我已将您的代码片段修改为最低限度。在此修改版本中,当用户单击鼠标按钮时,将触发 System.out。

现在,您可以通过两种方式访问​​ Frame 对象。但在此之前,让我先声明这两点:

  • 当您创建一个像 new ExampleFrame(new Menu()); 这样的 PApplet 并将其添加到您的 JFrame 中时,如下所示 add(app, BorderLayout.CENTER); 然后创建一个复杂的窗口/面板层次结构。

像这样:

javax.swing.JPanel
    javax.swing.JLayeredPane
        javax.swing.JRootPane
            test.ExampleFrame
  • PApplet 提供了一个用于设置和访问框架对象的公共字段。令人惊奇的是它被称为frame:)。可以在调用app.init();之前设置

>>代码

**查看代码中的注释**

修改后的ExampleFrame.java

import java.awt.BorderLayout;    
import javax.swing.JFrame;    
import processing.core.PApplet;

public class ExampleFrame extends JFrame
{
    private static final long serialVersionUID = 4792534036194728580L;
    PApplet app;

    public ExampleFrame(PApplet emApp)
    {
        super("Ball Maze Game");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(200, 200);

        app = emApp;
        setSize(615,438);
        setVisible(true);

        setLayout(new BorderLayout());

        add(app, BorderLayout.CENTER);

        // Setting my frame object
        app.frame = this;       
        app.init();
    }

    // Sample Method
    public void sampleMethod(String msg)
    {
        System.out.println("I think '"+ msg +"' called me !!");
    }
}

修改后的 Menu.java

import java.awt.Container;

import processing.core.PApplet;
import processing.core.PImage;

public class Menu extends PApplet
{
    private static final long serialVersionUID = -6557167654705489372L;

    PImage background;
    static String tab = "";

    //simple constructor
    public Menu()
    {

    }

    public void setup()
    {
        size(600, 400);
        smooth();

        background = loadImage("C:/temp/background.jpg");
    }

    public void draw()
    {
        image(background, 0, 0);
    }

    public void mousePressed()
    {
        Container p = getParent();
        tab = "";

        // FIRST WAY OF ACCESSING PARENT FRAME
        while(p != null)
        {
            //printParentTree(p);
            if(p instanceof ExampleFrame)
            {
                ExampleFrame myframe = (ExampleFrame)p;
                myframe.sampleMethod("First Way");
                break;
            }
            p = p.getParent();
        }

        // SECOND WAY OF ACCESSING PARENT FRAME     
        if(frame != null && (frame instanceof ExampleFrame))
        {
            ExampleFrame myframe = (ExampleFrame)p;
            myframe.sampleMethod("Second Way");
        }
    }

    void printParentTree(Container p) 
    {
        System.out.println(tab+p.getClass().getName());
        tab +='\t';
    }
}

查看 public void mousePressed() 方法。

为了完整起见,我还包括了 Main.java。

public class Main {
    public static void main(String[] args){
        new ExampleFrame(new Menu());
    }
}

现在回答删除所有 PApplet 内容并加载另一个 PApplet

我还没有测试过。但是您可以将 JPanel 添加到您的 JApplet 并在其上进行所有绘图,即创建子控件等。当想要重绘时,请调用 JPanel.removeAll()。根据javadoc:

从中删除所有组件
容器。该方法还通知
布局管理器删除
来自该容器的组件
通过removeLayoutComponent进行布局
方法。

在此之后,在 JPanel 上调用 repaint。尝试一下,它可能会起作用:)。

In order to answer How to call the Frame methods from the PApplet?, I have modified your code snippet to bare minimum. In this modified version when the user click mouse button a System.out is fired.

Now there are two ways in which you can access your Frame object. But before that let me state these two points:

  • When you create a PApplet like new ExampleFrame(new Menu()); and add it in your JFrame like this add(app, BorderLayout.CENTER); then a complex hierarchy of windows/panels are created.

Like this:

javax.swing.JPanel
    javax.swing.JLayeredPane
        javax.swing.JRootPane
            test.ExampleFrame
  • PApplet provides a public field for setting and accessing your frame object. And amazingly it is called frame :). You can set it before calling app.init();

>>Code

** Checkout the comments in the code**

Modified ExampleFrame.java

import java.awt.BorderLayout;    
import javax.swing.JFrame;    
import processing.core.PApplet;

public class ExampleFrame extends JFrame
{
    private static final long serialVersionUID = 4792534036194728580L;
    PApplet app;

    public ExampleFrame(PApplet emApp)
    {
        super("Ball Maze Game");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(200, 200);

        app = emApp;
        setSize(615,438);
        setVisible(true);

        setLayout(new BorderLayout());

        add(app, BorderLayout.CENTER);

        // Setting my frame object
        app.frame = this;       
        app.init();
    }

    // Sample Method
    public void sampleMethod(String msg)
    {
        System.out.println("I think '"+ msg +"' called me !!");
    }
}

Modified Menu.java

import java.awt.Container;

import processing.core.PApplet;
import processing.core.PImage;

public class Menu extends PApplet
{
    private static final long serialVersionUID = -6557167654705489372L;

    PImage background;
    static String tab = "";

    //simple constructor
    public Menu()
    {

    }

    public void setup()
    {
        size(600, 400);
        smooth();

        background = loadImage("C:/temp/background.jpg");
    }

    public void draw()
    {
        image(background, 0, 0);
    }

    public void mousePressed()
    {
        Container p = getParent();
        tab = "";

        // FIRST WAY OF ACCESSING PARENT FRAME
        while(p != null)
        {
            //printParentTree(p);
            if(p instanceof ExampleFrame)
            {
                ExampleFrame myframe = (ExampleFrame)p;
                myframe.sampleMethod("First Way");
                break;
            }
            p = p.getParent();
        }

        // SECOND WAY OF ACCESSING PARENT FRAME     
        if(frame != null && (frame instanceof ExampleFrame))
        {
            ExampleFrame myframe = (ExampleFrame)p;
            myframe.sampleMethod("Second Way");
        }
    }

    void printParentTree(Container p) 
    {
        System.out.println(tab+p.getClass().getName());
        tab +='\t';
    }
}

Checkout the public void mousePressed() method.

For completeness, I am also including Main.java.

public class Main {
    public static void main(String[] args){
        new ExampleFrame(new Menu());
    }
}

Now to answer Remove all PApplets contents and load another PApplet in

Well I have not tested it. But you can add a JPanel to your JApplet and do all your drawing on that i.e creating child controls etc. When feel like redrawing then call JPanel.removeAll(). Which as per javadoc:

Removes all the components from this
container. This method also notifies
the layout manager to remove the
components from this container's
layout via the removeLayoutComponent
method.

After this call repaint on the JPanel. Try it out, it might work :).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文