【问题标题】:I want to add background in JFrame how could I? [duplicate]我想在 JFrame 中添加背景,我该怎么做? [复制]
【发布时间】:2020-09-16 21:53:21
【问题描述】:

这是我的代码,如何在其中添加背景我尝试了所有可能的解决方案,但图片不会显示在背景中。

我该怎么办,谁能帮帮我?

  public class Triangle {
        JLabel l1;
        public static void main(String[] args) {
            new Triangle();
        }

        public Triangle() {
            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.setSize(400,400);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);

                }
            });
        }

        public class TestPane extends JPanel {


            private Polygon poly;


           {


                poly = new Polygon(
                    new int[]{110, 150, 50},
                    new int[]{200, 0, 0},
                        3);
            }



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

            }



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

                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(Color.blue);
                g2.fill(poly);
                 g2.setColor(Color.red);
                 g2.fillRect(0,0,25,75); 
                 g2.setColor(Color.green);    
                 g2.fillOval(200,100,100,50);
                 g2.setColor(Color.green);    
                 g2.fillOval(300,300,250,250);





            }
        }
    }

这是我的代码,如何在其中添加背景我尝试了所有可能的解决方案,但图片不会显示在背景中。

我该怎么办,谁能帮帮我?

【问题讨论】:

标签: java swing jframe jpanel


【解决方案1】:

设置 JPanel 的背景颜色

试试这个:

TestPane myPane = new TestPane();
myPane.setBackground(Color.green);
frame.add(myPane);

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 2011-08-12
    相关资源
    最近更新 更多