首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JPanel中添加JPanel -嵌套的JPanel将不会显示

在JPanel中添加JPanel -嵌套的JPanel将不会显示
EN

Stack Overflow用户
提问于 2013-02-16 14:08:55
回答 2查看 5.2K关注 0票数 3

新代码

代码语言:javascript
复制
package test;

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


public class TestWindow extends JFrame{
//------------------------------------------------------------------------------
    public static void main(String[] args) {
        new TestWindow();
    }
//------------------------------------------------------------------------------
    public TestWindow(){
        setSize(300,300);
        this.setUndecorated(true);
        add(new Background());
        setVisible(true);
    }
//------------------------------------------------------------------------------

    private class Background extends JPanel{
        public Background(){
            add(b);
            repaint();
        }
//------------------------------------------------------------------------------    
        Bubble b = new Bubble();
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Color c = Color.cyan;
            g.setColor(c);
            g.fillRect(0, 0,getWidth(), getHeight());
        }
//------------------------------------------------------------------------------
        private class Bubble extends JPanel{
            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.setColor(Color.green);
                g.drawOval(0, 0, Background.this.getWidth(), Background.this.getHeight());
            }
        }
//------------------------------------------------------------------------------
    }
}  

输出

问题

其目的是绘制一个带有绿色圆圈的青色窗口。稍后,我将向绿色圆圈添加组件,这样看起来就像是有一个带有青色背景的窗口和一个带有组件的绿色圆圈。

然而,输出只是青色背景。没有圆圈。

我尝试将XOR模式设置为青色,但也不起作用。我嵌套的类是错的吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-16 14:16:23

主要的问题在这里……

代码语言:javascript
复制
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Color c = Color.cyan;
        g.setColor(c);
        g.fillRect(0, 0,getWidth(), getHeight());
        add(b);
        repaint();
    }

不仅要在paint方法中将组件添加到容器中,还需要调用repaint,所有这些都将合谋对您不利。

当您的组件由于各种原因需要更新时,reapint管理器会调用Paint。您不应该调用任何可能使其无效的方法,否则需要重新绘制组件,这样做会使您的CPU耗尽。

而不是。

  1. Bubble组件添加到Background的构造函数中这两个组件的getPreferredSize方法,并提供有用的提示,以便布局管理器了解这些组件实际想要使用

的空间有多大

您面临的主要问题(除了糟糕的绘画之外)是组件报告自身不需要高度或宽度,这意味着当布局管理器对它们进行布局时,它们实际上是不可见的。

更新

我建议你看一看

  • Creating a GUI with Swing,特别关注有关layout managers
  • Custom painting
  • Painting in AWT and Swing

的部分

复活节彩蛋

对于接受建议和做出努力,让我给你一点帮助…

我建议你做的是通读代码,回到Java文档和教程,试着弄清楚是怎么回事;)

代码语言:javascript
复制
public class CircleControl {

    public static void main(String[] args) {
        new CircleControl();
    }

    public CircleControl() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            add(new Bubble());
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 300);
        }

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

            Graphics2D g2d = (Graphics2D) g.create();

            Color startColor = brighten(Color.CYAN, 0.75f);
            Color endColor = brighten(Color.CYAN, 0.5f);

            LinearGradientPaint lgp = new LinearGradientPaint(
                            new Point(0, 0),
                            new Point(0, getHeight()),
                            new float[]{0f, 1f},
                            new Color[]{startColor, endColor});

            g2d.setPaint(lgp);
            g2d.fill(new Rectangle(getWidth(), getHeight()));
            g2d.dispose();

        }
    }

    public class Bubble extends JPanel {

        public Bubble() {
            Font font = UIManager.getFont("Label.font");
            setFont(font.deriveFont(Font.BOLD, 48));
            setForeground(Color.WHITE);
            setBackground(darken(Color.CYAN, 0.3f));
            setOpaque(false);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(150, 150);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
            g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            
            int x = (getWidth() - 150) / 2;
            int y = (getHeight() - 150) / 2;

            Color startColor = brighten(getBackground(), 0.05f);
            Color endColor = getBackground();

            LinearGradientPaint lgp = new LinearGradientPaint(
                            new Point(x, y),
                            new Point(x, y + 150),
                            new float[]{0f, 1f},
                            new Color[]{startColor, endColor});
            g2d.setPaint(lgp);
            g2d.fill(new Ellipse2D.Double(x, y, 150, 150));
            
            FontMetrics fm = g2d.getFontMetrics();
            x = x + ((150 - fm.stringWidth("22")) / 2);
            y = y + ((150 / 2) + fm.getAscent());
            g2d.setColor(getForeground());
            g2d.drawString("22", x, y);

        }
    }

    public static Color brighten(Color color, double fraction) {
        int red = (int) Math.round(Math.min(255, color.getRed() + 255 * fraction));
        int green = (int) Math.round(Math.min(255, color.getGreen() + 255 * fraction));
        int blue = (int) Math.round(Math.min(255, color.getBlue() + 255 * fraction));
        int alpha = color.getAlpha();
        return new Color(red, green, blue, alpha);
    }

    public static Color darken(Color color, double fraction) {
        int red = (int) Math.round(Math.max(0, color.getRed() - 255 * fraction));
        int green = (int) Math.round(Math.max(0, color.getGreen() - 255 * fraction));
        int blue = (int) Math.round(Math.max(0, color.getBlue() - 255 * fraction));
        int alpha = color.getAlpha();
        return new Color(red, green, blue, alpha);
    }
}
票数 8
EN

Stack Overflow用户

发布于 2013-02-16 14:40:43

我已经运行了你的代码,并使changes.Here是it.However,你的程序不能处理窗口关闭。你必须把它写出来。

代码语言:javascript
复制
package test;
import javax.swing.*;
import java.awt.*;

public class TestWindow extends JFrame
{
    //------------------------------------------------------------------------------
    public static void main(String[] args) {
        new TestWindow();
    }
    //------------------------------------------------------------------------------
    public TestWindow(){
        setSize(300,310);
        this.setUndecorated(true);
        add(new Background());
        setVisible(true);
    }
//------------------------------------------------------------------------------

    private class Background extends JPanel{
        public Background(){
            Bubble b = new Bubble();
            add(b);
        }
        //------------------------------------------------------------------------------    

        @Override public Dimension getPreferredSize()
        {
            return new Dimension(300,300);
        }

        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Color c = Color.cyan;
            g.setColor(c);
            g.fillRect(0, 0,getWidth(), getHeight());
        }
        //------------------------------------------------------------------------------
        private class Bubble extends JPanel{

            Bubble()
            {
                setOpaque(false);
            }

            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.setColor(Color.green);
                g.fillOval(0, 0, getWidth(), getHeight());
            }

            @Override public Dimension getPreferredSize()
            {
                return new Dimension(300,300);
            }
        }
//------------------------------------------------------------------------------
    }
}  
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14907535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档