How to Remove JFrame Border as to Let an Image Tou

2020-07-16 02:49发布

问题:

I had a friend make a background for the program I made so that it wouldn't look so plain, and I thought the best way to place the images would be to make a JLabel, fill it with an image, and set it to the size of the screen. This worked fine, except there is a small border around the JFrame and I can't get the JLabel to touch the edges of the frame. Thoughts? I have attached a picture.

public class ProgramDriver extends JFrame {

private JPanel contentPane;
private static CardLayout cardLayout;
private JTextField addGradeN;
private JTextField addGradeD;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ProgramDriver frame = new ProgramDriver();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

//Global Variables 
...
    manager = new StateManager(gb);

    //JFrame Settings
    setTitle("Grade Book");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 656, 530);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    cardLayout = new CardLayout(0,0);
    contentPane.setLayout(cardLayout);
    setResizable(false);

    //Home Panel 
    final JPanel Home = new JPanel();
    contentPane.add(Home, "Home");
    Home.setLayout(null);

    JButton btnSeeGrades = new JButton("See Grades");
    ...

    //Grades Panel
    JPanel Grades = new JPanel();
    contentPane.add(Grades, "Grades");
    Grades.setLayout(null);'

回答1:

To expand on Eng.Fouad's answer, you'll want to use the drawImage(...) method that takes 6 parameters, image, x and y location, image width and height, and image observer, and draw it like so from within a JPanel:

g.drawImage(img, 0, 0, getWidth(), getHeight(), this);

For example, my sscce:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class ExpandingImage extends JPanel {
   public static final String GUITAR = "http://duke.kenai.com/Oracle/OracleStrat.png";
   BufferedImage img;

   public ExpandingImage(String imgUrlPath) throws IOException {
      URL imgUrl = new URL(imgUrlPath);
      img = ImageIO.read(imgUrl);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (img != null) {
         g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
      }
   }


   private static void createAndShowGui() {
      ExpandingImage mainPanel;
      try {
         mainPanel = new ExpandingImage(GUITAR);
         JFrame frame = new JFrame("ExpandingImage");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().add(mainPanel);
         frame.pack();
         frame.setLocationByPlatform(true);
         frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
         frame.setVisible(true);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Edit
I see that you're using an EmptyBorder around the contentPane. Why if you don't want this border to be present?



回答2:

The problem isn't with the JFrame, the problem is with your code. We can spend the rest of our natural life at guessing what's wrong or you can post some example code.

Now it's up to you, we can keep trying to throw wrong guess after wrong guess at you, frustrating us all, or you can help us help you...

Here are two examples I did. The first uses a JLabel as the primary content for a JPanel, where the child components are placed on it. Nice and simple.

The second uses a custom JPanel which paints the image onto the background of the component. I then use this to replace the frames content pane. This is a little more involved, but it has the added benefit of been easily updated (replacing the content pane won't effect the rest of the program)

Example 1: JLabel used as background

public class TestBackground {

    public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";

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

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

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

            }
        });

    }

    protected class LabelPane extends JPanel {

        public LabelPane() {

            BufferedImage bg = null;
            try {
                bg = ImageIO.read(new File(BACKGROUND_PATH));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            JLabel label = new JLabel(new ImageIcon(bg));
            setLayout(new BorderLayout());

            add(label);

            label.setLayout(new GridBagLayout());

            JLabel lblMessage = new JLabel("Look at me!");
            lblMessage.setForeground(Color.WHITE);
            lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));

            label.add(lblMessage);

        }
    }
}

Example 2: Image used as background, replacing content pane...

public class TestBackground {
    public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";

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

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

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

    protected class BackgroundPane extends JPanel {

        private BufferedImage bg = null;

        public BackgroundPane() {
            try {
                bg = ImageIO.read(new File(BACKGROUND_PATH));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            setLayout(new GridBagLayout());

            JLabel lblMessage = new JLabel("Look at me!");
            lblMessage.setForeground(Color.WHITE);
            lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));

            add(lblMessage);
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (bg != null) {
                g.drawImage(bg, 0, 0, this);
            }
        }
    }
}


回答3:

As an alternative, you can override the method paintComponent(Graphics g) of JPanel (the contentPane) and use drawImage() on the Graphics object g as in this example.



回答4:

have you tried JFrame function setUndecorated() ?



回答5:

Make the frame undecorated. frame.setUndecorated(true)

If you want to make it move, you can use the ComponentMover of the Java2S.

Make sure that it is undecorated before it is visible.

Next, use setContentPane(new JLabel(new ImageIcon("myimage.jpg")));

After, that you can add contents as usual.