JFrame中的渐变背景

时间:2014-01-16 17:02:02

标签: java swing background jframe gradient

我用Google搜索并阅读了很多但未找到符合我需求的答案,所以我会在这里问:

我希望在JFrame中有渐变背景。目前背景是单色。我的代码看起来像这样:

//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作为实例变量。有人可以帮助我吗?

编辑:图片:

enter image description here

1 个答案:

答案 0 :(得分:4)

在100 LOC完全编译并运行,这里是 MCVE!

现在,显然上面的示例图片没有指定按钮,也没有为底部的消息添加标签。但是很明显,您希望用户选择这些选项,我使用了按钮。底部的标签只是为了证明他们按钮(附有动作监听器,以显示消息)。

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

如果游戏不需要键盘访问,您可以将它们换成标签并添加鼠标监听器。我会留给你的。

代码中有很多包含“adjust”一词的评论。仔细查看它们,检查JavaDocs,根据需要进行调整..

enter image description here enter image description here

enter image description here enter image description here

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。因此,它们不利于精确放置组件。这就是为什么你不断看到你看到的问题类型的原因。抛出窗外的布局,一切都崩溃了。

要组织强大的GUI组件,而是使用布局管理器,或combinations of them 1 ,以及布局填充&am​​p; white space 2 的边框。