我想在JFrame中添加背景怎么办? [重复]

问题描述 投票:-1回答:1

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

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

  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个回答
0
投票

将背景色设置为JPanel

尝试一下:

TestPane myPane = new TestPane();
myPane.setBackground(Color.green);
frame.add(myPane);
© www.soinside.com 2019 - 2024. All rights reserved.