기본 메소드를 사용하거나 다른 방법을 호출하지 않고 ContentPane을 어떻게 설정합니까?

StackOverflow https://stackoverflow.com/questions/19844666

  •  29-07-2022
  •  | 
  •  

문제

다음은 ContentPane의 배경색을 설정한다는 것을 이해합니다. 대신 사진을 배경으로 어떻게 설정합니까?

나는 이것들을 시도했다 :

그러나 그들 중 누구도 효과가 없었습니다.

JLabel lblbackground = new JLabel();
lblbackground.setBounds(20, 20, 160, 160);
lblbackground.setBorder(new LineBorder(new Color(0, 0, 0), 2));
lblbackground.setIcon (new ImageIcon (this.getClass().getResource("/boundary/background.jpg")));
lblbackground.setHorizontalAlignment (SwingConstants.CENTER);                   
BufferedImage img = new BufferedImage(lblbackground.getIcon().getIconWidth(), lblbackground.getIcon().getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = img.createGraphics();
lblbackground.getIcon().paintIcon(null, g, 0, 0);
g.dispose();
Image newing = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
lblbackground.setIcon(new ImageIcon(newing));           

//getContentPane().setLayout(new GridBagLayout());
contentPane = new JPanel();
//contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(null);
contentPane.setLayout(null);        
contentPane.add(lblbackground);
setContentPane (contentPane);
도움이 되었습니까?

해결책

(...)
// 1) Create your image;
final ImageIcon image = new ImageIcon("../folder/myImage.gif");

//2) Create a JPanel with a background image;
  JPanel  myPanel = new JPanel(){
            @Override
            public void paintComponent(Graphics g)
            {
                g.drawImage(image.getImage(), 0, 0, null);
            }
    };

//3) Add panel 
getContentPane().add(myPanel);

(...)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top