【问题标题】:How to create a "Game Option/Pause Screen" in Swing?如何在 Swing 中创建“游戏选项/暂停屏幕”?
【发布时间】:2018-01-28 08:15:07
【问题描述】:

背景:在 Swing 中制作游戏。这是简单的回合制游戏。没有很多事情发生。因此,我认为我不需要实现 Game Tick。相反,我的想法是当组件发生更改或需要更新时,只需即时重新验证/重新绘制该组件,而不是重新绘制整个屏幕。

我有一个 GameJPanel,目前它上面有所有组件。此 JPanel 是包含重新验证/重新绘制等组件的 JPanel。 我想我可以制作包含 GameJPanel 和我的 OptionJPanel 的 JLayeredPane。在 GameJPanel 上有一个按钮,当按下该按钮时,OptionJPanel 会显示在其顶部,并且其 JPanel 有 50% 透明(因此它会产生使 GameJPanel 变暗的效果)。

但是,一旦我这样做了,GameJPanel 开始替换 OptionJPanel 组件(因为事件......等等;重新绘制组件)。

所以目前我不知道该怎么做。我在想,如果我有某种游戏滴答声,我就不会遇到这个问题,但是,我不是 100% 确定的。我有点担心如果我实现了一个gametick,游戏中的事件会导致GameJPanel组件显示半秒钟然后被替换。有一些事件会导致组件在没有手动操作的情况下重新绘制自己(例如 JLabel setText(); 的快速示例)

作为我正在努力的一个例子。

我尝试过使用 CardLayout,但在后台看到 GameJPanel 时,我无法弄清楚如何让 OptionJPanel 位于 GameJPanel 之上(我尝试设置背景颜色 setOpaque(false)...,试图限制选项 JPanel 大小,但我认为 CardLayout 会拉伸它(不是 100% 肯定))这样做时我得到的只是灰色背景。

我不想走 CardLayout 路线,因为将来我还计划将组件放置在 GameJPanel 的顶部(比如有人单击一个按钮,让另一个面板在不同的层上有一个组件滑入或滑出等) . 我大量使用 CardLayout 和 GameJPanel 中的其他组件来交换屏幕,但不需要让显示背后的其他组件显示出来。

任何关于如何实现这一点的想法都会很棒,甚至是显示这一点的示例代码。

【问题讨论】:

  • 您需要一个模态JDialog 用于“弹出”选项菜单。如果您需要具体帮助,请发帖minimal reproducible example
  • 为什么一定要在同一个窗口做呢?用户如何知道实施细节?
  • 这是JDialogs的标准用法,有什么不方便的?什么可以变得更容易?如果您使用默认的跨平台 L&F,实现看起来将相同。你想制作什么动画,为什么它对对话框很重要?
  • "I would have to size the JDialog to the JFrame" -- 什么?为什么?不,您根据其组成组件的首选大小和布局管理器操作,让 JDialog 自身 调整为自然大小。您提到的其他所有内容都使事情变得过于复杂,并表明您还没有深入了解这些对话框(或 Swing )的使用。试试看吧。
  • 如前所述,对话框计算自己的大小(您可以给出提示)。您还可以将其设置为框架的中心,移除其装饰(顶部栏)并使其成为模态(阻止与父级交互)。而已。动画是与对话框或其他组件无关的其他东西。

标签: java swing


【解决方案1】:

如上所述,您将使用 JDialog,这是一个易于制作(类似于制作 JFrame)且易于放置的组件。只需将其“相对于”JFrame,例如,

myDialog.setLocationRelativeTo(myJFrame);

... 它会自动以 JFrame 为中心。棘手的部分是使底层 JFrame 变暗,为此,您需要使用添加到 JFrame 根窗格的 JGlassPane,一组具有使用 alpha 复合值的背景颜色。棘手的部分是在不引起副作用的情况下绘制较暗的背景,为此,请阅读 Rob Camick(StackOverflow 用户camickr)关于使用 alpha 复合材料在 Swing 中绘制的优秀教程,您可以在此处找到:Java Tips Weblog: Backgrounds with Transparency

此处显示了此类程序的示例:

import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

public class DialogEg {
    // path to example image used as "game" background
    private static final String IMG_PATH = "https://upload.wikimedia.org/"
            + "wikipedia/commons/7/76/Jump_%27n_Bump.png";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        // get the "game" background image, or exit if fail
        BufferedImage img = null;
        try {
            URL imgUrl = new URL(IMG_PATH);
            img = ImageIO.read(imgUrl);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        // pass "game" image into main JPanel so that it will be drawn
        DeMainPanel mainPanel = new DeMainPanel(img);
        JFrame frame = new JFrame("Dialog Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel); // add main JPanel to JFrame
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}

// main JPanel
@SuppressWarnings("serial")
class DeMainPanel extends JPanel {
    private BufferedImage img; // background image

    // JButton action that shows the JDialog and darkens the glasspane
    private PauseAction pauseAction = new PauseAction("Pause");

    public DeMainPanel(BufferedImage img) {
        super();
        this.img = img;
        add(new JButton(pauseAction));
    }

    // draw the "game" background image within the JPanel if not null
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            g.drawImage(img, 0, 0, this);
        }
    }

    // size this JPanel to match the image's size
    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet() || img == null) {
            return super.getPreferredSize();
        }
        int width = img.getWidth();
        int height = img.getHeight();
        return new Dimension(width, height);
    }
}

// Action / ActionListener for JButton -- shows JDialog and darkens glasspane
@SuppressWarnings("serial")
class PauseAction extends AbstractAction {
    private static final int ALPHA = 175; // how much see-thru. 0 to 255
    private static final Color GP_BG = new Color(0, 0, 0, ALPHA);
    private DeDialogPanel deDialogPanel = new DeDialogPanel();  // jpanel shown in JDialog

    public PauseAction(String name) {
        super(name);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // comp is our JButton
        Component comp = (Component) e.getSource();
        if (comp == null) {
            return;
        }

        // create our glass pane
        JPanel glassPane = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                // magic to make it dark without side-effects
                g.setColor(getBackground());
                g.fillRect(0, 0, getWidth(), getHeight());
                super.paintComponent(g);
            }
        };
        // more magic below
        glassPane.setOpaque(false); 
        glassPane.setBackground(GP_BG);     

        // get the rootpane container, here the JFrame, that holds the JButton
        RootPaneContainer win = (RootPaneContainer) SwingUtilities.getWindowAncestor(comp);
        win.setGlassPane(glassPane);  // set the glass pane
        glassPane.setVisible(true);  // and show the glass pane

        // create a *modal* JDialog
        JDialog dialog = new JDialog((Window)win, "", ModalityType.APPLICATION_MODAL);
        dialog.getContentPane().add(deDialogPanel);  // add its JPanel to it
        dialog.setUndecorated(true); // give it no borders (if desired)
        dialog.pack(); // size it
        dialog.setLocationRelativeTo((Window) win); // ** Center it over the JFrame **
        dialog.setVisible(true);  // display it, pausing the GUI below it

        // at this point the dialog is no longer visible, so get rid of glass pane
        glassPane.setVisible(false);

    }
}

// JPanel shown in the modal JDialog above
@SuppressWarnings("serial")
class DeDialogPanel extends JPanel {
    private static final Color BG = new Color(123, 63, 0);

    public DeDialogPanel() {
        JLabel pausedLabel = new JLabel("PAUSED");
        pausedLabel.setForeground(Color.ORANGE);
        JPanel pausedPanel = new JPanel();
        pausedPanel.setOpaque(false);
        pausedPanel.add(pausedLabel);

        setBackground(BG);
        int eb = 15;
        setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
        setLayout(new GridLayout(0, 1, 10, 10));
        add(pausedPanel);
        add(new JButton(new FooAction("RESUME")));
        add(new JButton(new FooAction("RESTART")));
        add(new JButton(new FooAction("EXIT TO MAP")));
    }

    // simple action -- all it does is to make the dialog no longer visible
    private class FooAction extends AbstractAction {
        public FooAction(String name) {
            super(name);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Component comp = (Component) e.getSource();
            Window win = SwingUtilities.getWindowAncestor(comp);
            win.dispose();  // here -- dispose of the JDialog
        }
    }
}

GUI 最初看起来像这样:

但是当对话框显示并且玻璃窗格变暗时,它看起来像这样:

【讨论】:

  • dialog.setUndecorated(true) 超出预期,它不允许用户移动它。此外,对话框应该是模态的。
  • @user1803551:感谢您的 cmets,事实上您在这两点上都是正确的。为了使对话框模式化,我使用了上面的 JDialog 构造函数之一,它接受 ModalityType 枚举作为其参数之一,并将底层窗口作为其另一个参数——new JDialog((Window)win, "", ModalityType.APPLICATION_MODAL)。模式化意味着底层 GUI 无法与用户交互,直到对话框不再可见。再次感谢您的澄清。
  • 哦,没有看到你已经在构造函数中设置了模态,抱歉。正在寻找setModal(或setModalityType)。
  • @user1803551:没问题,因为我已经发布了很多代码,可能比我应该的多一点。对我来说最棘手的部分是在不引起副作用的情况下使玻璃板部分变暗。我通常这样做的所有方法都会导致图像伪影出现在玻璃窗格上,因此我不得不搜索、学习和使用 camickr 的解决方案。
  • DontKnowMuch 但是很欣赏完整的解释,然后跑下来。我认为没有比这更好的了。感谢您的所有帮助。
【解决方案2】:

因此,在我开发游戏大约一个月后,我再次被这篇文章所吸引。我使用 DontKnowMuchButGettingBetter 的方式实现了我的游戏的一部分,并且还通过将组件添加到 GlassPane 来实现这一点(制作一个 JPanel,将其设置为 GlassPane,在该面板上执行任何操作)...

后来的实现(GlassPane)并不是解决这个问题的最佳方式,因为这样您就不能将玻璃窗格用于其他有用的事情。

我回到了使用 JLayeredPane 的最初想法。在不同级别上拥有不同的组件并解决它。我之前的问题是,当组件被重新绘制时,后层中的组件过度绘制了前层中的组件。

我刚刚遇到了一个名为 isOptimizedDrawingEnabled() 的方法...通过使此方法始终为 JLayeredPane 返回 false,我能够实现我想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多