JFrame中的渐变背景 [英] Gradient background in a JFrame

查看:74
本文介绍了JFrame中的渐变背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Google上搜索了很多东西,但是没有找到适合我需要的答案,所以我在这里问:

I have googled this and read a lot but did not find an answer that suits my needs, so I'll ask here:

我想在我的JFrame中使用渐变背景.当前背景是单色.我的代码如下所示:

I would like to have a gradient background in my JFrame. Currently the background is a single colour. My code looks something like this:

//imports

public class Game {

   //some other irrelevant instance variables

   JFrame frame = new JFrame("Game");

   public Game() {

       frame.getContentPane().setBackground(new Color(200,220,200));
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setLayout(null);
       frame.setPreferredSize(new Dimension(frameX,frameY)); //frameX and frameY are instance variables

       getMenu(); //method that adds a few JLabels to the JFrame and so on

   }
}

我已经读过的方法适用于扩展JPanel或JFrame的类(然后使用GradientPaint或类似的东西),但是如您所见,我将JFrame用作实例变量.有人可以帮我吗?

The methods that I have read about apply to classes that extend JPanel or JFrame (and then use GradientPaint or something like that), but as you can see I use JFrame as an instance variable. Can someone help me out?

图片:

推荐答案

在干净编译并运行的100 LOC下,这是 MCVE!

At 100 LOC that compiles cleanly and runs, here is an MCVE!

现在,显然您的示例图像中没有指定按钮,也没有在底部添加消息标签.但是由于很明显您打算让用户选择这些选项,因此我使用按钮.底部的标签只是为了证明它们按钮(已附加动作侦听器,以显示消息).

Now, obviously your example image above does not specify buttons, and does not add a label for the message at the bottom. But since it was obvious you intended the user to select those options, I used buttons. The label at the bottom is just to show proof they are buttons (with an action listener attached, to show the message).

使用实际按钮的优点是它们也可以通过键盘访问(按 Enter 查看第一条消息,按 Tab 导航到下一个消息...

The advantage of using actual buttons is that they are also keyboard accessible (press Enter to see the first message, press Tab to navigate to the next one...

如果游戏不需要通过键盘操作,则可以将其换成标签并添加鼠标侦听器.我把它留给你.

If the game does not need to be keyboard accessible, you can swap those out for labels and add a mouse listener. I'll leave that to you.

该代码有很多注释,其中包含单词"adjust".仔细查看它们,检查JavaDocs,然后根据需要进行调整.

The code has a lot of comments containing the word 'adjust'. Look at them closely, check the JavaDocs, adjust them as needed..

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class GradientPaintBackground {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                // the GUI as seen by the user (without frame)
                JPanel gui = new JPanel(new BorderLayout(15, 15)) {

                    @Override
                    public void paintComponent(Graphics g) {
                        super.paintComponent(g);

                        Point point1 = new Point(10, 10);
                        Point point2 = new Point(
                                getWidth() - 10, 
                                getHeight() - 10);
                        final GradientPaint gp = new GradientPaint(
                                point1, Color.YELLOW,
                                point2, new Color(255, 225, 100),
                                true);

                        // we need a Graphics2D to use GradientPaint.
                        // If this is Swing, it should be one..
                        final Graphics2D g2 = (Graphics2D) g;
                        g2.setPaint(gp);
                        g.fillRect(0, 0, getWidth(), getHeight());
                    }
                };
                // adjust size to need.
                gui.setBorder(new EmptyBorder(20, 20, 20, 20));

                // Start:  Add components
                // adjust size to size of logo
                BufferedImage logo = new BufferedImage(
                        100, 40, BufferedImage.TYPE_INT_RGB);
                JLabel logoLabel = new JLabel(new ImageIcon(logo));
                gui.add(logoLabel, BorderLayout.NORTH);

                // adjust spacing to need
                JPanel menuPanel = new JPanel(new GridLayout(0, 1, 20, 20));
                menuPanel.setBorder(new EmptyBorder(5, 55, 5, 5));
                // allow the BG to show through..
                menuPanel.setOpaque(false);
                gui.add(menuPanel);
                String[] actionTexts = new String[]{
                    "Play Game", "Tutorial", "Other"
                };
                final JLabel messages = new JLabel("Ready to play?  "
                        + "Select an option");
                gui.add( messages, BorderLayout.PAGE_END );
                ActionListener al = new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (e.getSource() instanceof JButton) {
                            JButton b = (JButton)e.getSource();
                            messages.setText(b.getText() + " selected!");
                        }
                    }
                };
                for (int ii = 0; ii < actionTexts.length; ii++) {
                    JButton b = new JButton(actionTexts[ii]);
                    b.setContentAreaFilled(false);
                    b.setHorizontalAlignment(SwingConstants.LEADING);
                    b.setBorder(null);
                    b.addActionListener(al);
                    menuPanel.add(b);
                }
                // End:  Add components

                JFrame f = new JFrame("Gradient Background in JFrame");
                f.add(gui);
                // Ensures JVM closes after frame(s) closed and
                // all non-daemon threads are finished
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See https://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                // ensures the frame is the minimum size it needs to be
                // in order display the components within it
                f.pack();
                f.setMinimumSize(f.getSize());
                // should be done last, to avoid flickering, moving,
                // resizing artifacts.
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

一般提示

Java GUI可能必须在许多平台上,不同的屏幕分辨率和&上运行.使用不同的PLAF.因此,它们不利于准确放置组件.这就是为什么您不断看到所看到的问题类型的原因.将布局扔出窗口,所有地狱都松散了.

General Tip

Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. This is why you are continually seeing the types of problems you see. Toss layouts out the window, and all hell breaks loose.

要为强大的GUI组织组件,请使用布局管理器或它们的组合 1 ,以及布局填充&am​​p; 空白 2 的边框.

To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.

这篇关于JFrame中的渐变背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆