Setting a background image on a JFrame using Swing

前端 未结 2 1300
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 23:52

I have been learning Java for a few weeks now and I am really stuck when it comes to applying a background image to a JFrame. Every tutorial I\'ve come across doesn\'t creat

相关标签:
2条回答
  • 2020-12-22 00:01

    As to your question as it's titled

    You will want to setup a custom Component (such as a JPanel) and override the paintComponent method

    Take a look at

    • Performing Custom Painting in Swing
    • Java 2D Graphics

    Now, you're going to have some issues, the note pane will block most of the background, obscuring the image. This shouldn't discourage from trying though ;)

    You'll want to familiarise yourself with how Swing components can be made transparent as well.

    Some feedback ;)

    I don't think you need to keep a reference to the Classloader, for what you're using it for, it's just adding weight and complexity to your code. It's not a massive issue, but my first question was, "What's he using the class loader for??"

    I'd probably adopt some kind of naming convention as well. Generally been a little more verbose will make it easier to understand the code.

    close ?? Is that an action? Maybe something like "closeButton", at least I know it's some type of button

    0 讨论(0)
  • 2020-12-22 00:08

    Better to use:

    ImageIcon closeImg = new ImageIcon(getClass().getResource("\\images\\buttons\\closeBtn.png"));
    

    Make sure your image is located in the same location relative to where your class file is output.

    Also your close button calls setVisible(false) but does not dispose of any resources or exit the application.

    0 讨论(0)
提交回复
热议问题