How can I remove this Bar in "fullscreenmode"? - java

My Problem is that there's a little bar at the top of my screen which i want to remove (I want the picture to be fullscreen). I'm not sure though from which source this bar is caused.
picture
Here's my code till now:
lpane = new JLayeredPane();
lpane.setBackground(Color.BLACK);
panelBlue = new JPanel();
panelGreen = new JPanel();
frame.add(lpane);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
lpane.setBounds(0, 0, 1920, 1080);
BufferedImage background = null;
BufferedImage title = null;
try{
background = javax.imageio.ImageIO.read(getClass().getResource("resources/background.jpg"));
}catch(IOException ex){
sendErrorMessage("Picture couldn't be loaded"); //custom Errormessage Method
}
JLabel picLabel = new JLabel(new ImageIcon(background));
ImageIcon buttonbackground = new ImageIcon(flames);
panelBlue.add(picLabel);
panelBlue.setBounds(0, 0, 1920, 1080);
panelBlue.setOpaque(true);
frame.pack();
frame.setVisible(true);
I'm not sure if the cause is the JLabel or if it has something to do with the undecorated frame.
What's the cause and how can i remove the bar?
Thx in advance

Don't use setBounds. This is just plain wrong. The proper way is to use an appropriate LayoutManager. Additionaly, if you use pack(), using setBounds before is useless.
To put you frame in fullscreen, you can use any of the following:
frame.setExtendedState(frame.getExtendedState() & JFrame.MAXIMIZED_BOTH);
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame);
See this example that illustrates this:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UnsupportedLookAndFeelException;
public class TestFullScreen {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestFullScreen().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
public static class ImagePanel extends JPanel {
private ImageIcon imageIcon;
public ImagePanel(ImageIcon imageIcon) {
super();
this.imageIcon = imageIcon;
};
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imageIcon.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight());
}
}
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePanel(new ImageIcon(new URL("http://blog.timesunion.com/opinion/files/2011/10/brickwall.jpg"))));
frame.setUndecorated(true);
frame.pack();
frame.setExtendedState(frame.getExtendedState() & JFrame.MAXIMIZED_BOTH);
// GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame);
frame.setVisible(true);
}
}

Related

Set Transparent Color for the Whole JPanel

I have a JPanel with a JLabel which owns an Icon picture.
how do I set a transparent red color at the top of the whole JPanel (including JLabel Icon)?
I have the transparent backgriound color on for the panel but I want the whole panel including the picture and everything get this transparent color. something like a transparent colorful glass at the top of the JPanel
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TransparentJLabel {
private static final String IMAGE_PATH = "http://duke.kenai.com/Oracle/OracleStratSmall.png";
private static void createAndShowUI() {
JPanel panel = new JPanel();
panel.setBackground(Color.pink);
URL imageUrl;
try {
imageUrl = new URL(IMAGE_PATH);
BufferedImage image = ImageIO.read(imageUrl);
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
panel.add(label);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("TransparentJLabel");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
If you just need a layered panel over the whole contentPane, a simple glassPane will do fine (override it's paintComponent(...) method). For example:
JPanel glassPane = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(0, 100, 0, 100));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
glassPane.setOpaque(false);
frame.setGlassPane(glassPane);
frame.getGlassPane().setVisible(true);
However, if you want a layered panel over only one JPanel, I would use JLayer combined with LayerUI, as MadProgrammer already mentioned. You will need a custom LayerUI in which you override the paint(Graphics g, JComponent c) method. I know that sounds dangerous, but I honestly don't know of another way of doing it...
I've provided an example below, this is the output:
As you can see, panel1 (or more accurately, the JLayer) is slighty transparent (RGBA = "0, 100, 0, 100") and panel2 is normal.
Code:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class Example {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
public Example() {
JFrame frame = new JFrame("Example");
JPanel panel1 = new JPanel();
panel1.add(new JButton("Panel 1"));
MyLayerUI layerUI = new MyLayerUI();
JLayer<JPanel> panel1Layer = new JLayer<JPanel>(panel1, layerUI);
panel1.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (layerUI.hasOverlay()) {
layerUI.setOverlay(false);
} else {
layerUI.setOverlay(true);
}
panel1Layer.repaint();
}
});
JPanel panel2 = new JPanel();
panel2.add(new JButton("Panel 2"));
JPanel contentPane = new JPanel(new GridLayout(2, 1));
contentPane.add(panel1Layer);
contentPane.add(panel2);
frame.setContentPane(contentPane);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyLayerUI extends LayerUI<JPanel> {
private boolean overlay = true;
#Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (hasOverlay()) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(0, 100, 0, 100));
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
g2.dispose();
}
}
public boolean hasOverlay() {
return overlay;
}
public void setOverlay(boolean overlay) {
this.overlay = overlay;
}
}

Image not appearing in jbutton with wordGen

The image isn't being painted when this is run with WordGen, how do i fix this?
When I run this without wordgen I can get the image to appear. I'm not sure what i'm doing wrong since i'm not getting any errors.
Any help is appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tfot extends JComponent{
private static final long serialVersionUID = 1L;
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI(args);
}
});
}
public static void showGUI(String[] args) {
JPanel displayPanel = new JPanel();
JButton okButton = new JButton("Did You Know?");
okButton.setFont(new Font("Times", Font.TRUETYPE_FONT, 100));
final JLabel jLab = new JLabel();
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jLab.setText(wordGen());
}
});
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
content.add(jLab, BorderLayout.NORTH);
JFrame window = new JFrame("Window");
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(Toolkit.getDefaultToolkit().getImage("Pictures/background1.png"), 0, 0, this);
}
public static String wordGen() {
String[] wordListOne = {"generic text","hi",};
int oneLength = wordListOne.length;
int rand1 = (int) (Math.random() * oneLength);
String phrase = wordListOne[rand1] + " ";
return phrase;
}
}
First...
Don't load resources or perform long running tasks within the paint methods, these may be called a number of times in quick succession. Instead, load the images before hand and paint them as needed...
public Tfot() {
setLayout(new BorderLayout());
try {
background = ImageIO.read(new File("pictures/background1.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
g.drawImage(background, 0, 0, this);
}
}
Generally, you are discouraged from overriding paint and instead should use paintComponent, lots of reasons, but generally, this is where the background is painted...
Second...
You need to add Tfot to something that is displayable, otherwise it will never be painted
JFrame window = new JFrame("Window");
window.setContentPane(new Tfot());
window.add(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
Thrid...
JPanel by default is not transparent, you need to set it's opaque property to false
JPanel displayPanel = new JPanel();
displayPanel.setOpaque(false);
//...
JPanel content = new JPanel();
content.setOpaque(false);
Then it will allow what ever is below it to show up (ie, the background image)
Take a look at Painting in AWT and Swing, Performing Custom Painting and Reading/Loading an Image for more details
Fourth...
You need to learn the language basics for embarking on advance topics like GUI and custom painting, without this basic knowledge, this topics will bite you hard.
You need to declare background as a instance field of the class Tfot
private BufferedImage background;
public Tfot() {
Updated - Fully runnable example
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Tfot extends JComponent {
private static final long serialVersionUID = 1L;
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI(args);
}
});
}
public static void showGUI(String[] args) {
JPanel displayPanel = new JPanel();
displayPanel.setOpaque(false);
JButton okButton = new JButton("Did You Know?");
okButton.setFont(new Font("Times", Font.TRUETYPE_FONT, 100));
final JLabel jLab = new JLabel();
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jLab.setText(wordGen());
}
});
JPanel content = new JPanel();
content.setOpaque(false);
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
content.add(jLab, BorderLayout.NORTH);
Tfot tfot = new Tfot();
tfot.setLayout(new BorderLayout());
tfot.add(content);
JFrame window = new JFrame("Window");
window.setContentPane(tfot);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
}
private BufferedImage background;
public Tfot() {
try {
background = ImageIO.read(new File("Pictures/background1.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, this);
}
public static String wordGen() {
String[] wordListOne = {"generic text", "hi",};
int oneLength = wordListOne.length;
int rand1 = (int) (Math.random() * oneLength);
String phrase = wordListOne[rand1] + " ";
return phrase;
}
}

Swing - Allowing JButton to always stay on page when scrolling in application

I have this application that I am working on, I have a JFrame that uses a BorderLayout. In the JFrame is a JPanel, the JPanel is using a MigLayout.I am trying to make a JButton stay on the bottom left hand side of the screen , achieving a similar effect as the "position:fixed" property in CSS.
Any tips on how I can achieve this effect by code?
Tried JLayeredPane code from a few other sources, but still doesn't work somehow.
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if (info.getName().equals("Nimbus")) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
MainFrame frame = new MainFrame();
ForumMainPage panel = new ForumMainPage(frame);
panel.setFocusable(true);
panel.requestFocusInWindow();
frame.add(jLabelOnJButton());
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
this.setSize(dim);
this.setUndecorated(true);
this.setExtendedState(Frame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.add(jLabelOnJButton(),BorderLayout.CENTER);
}
private static JComponent jLabelOnJButton(){
JLayeredPane layers = new JLayeredPane();
JLabel label = new JLabel("label");
JButton button = new JButton("button");
label.setBounds(40, 20, 100, 50);
button.setBounds(100, 20, 150, 75);
layers.add(label, new Integer(200));
layers.add(button, new Integer(100));
return layers;
}
}
Thanks in advance!
You could add the button to the frame's glass pane. This takes a little bit of work to make happen, as you need to keep track of the scroll pane relative to the glass pane, but it should achieve the desired effect
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class OverlayButton {
public static void main(String[] args) {
new OverlayButton();
}
public OverlayButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JScrollPane sp;
private JButton btn;
private JTextArea ta;
private JPanel glassPane;
public TestPane() {
setLayout(new BorderLayout());
btn = new JButton("Print");
ta = new JTextArea(10, 20);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("Script.txt")));
String text = null;
while ((text = br.readLine()) != null) {
ta.append(text + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
}
}
ta.setCaretPosition(0);
sp = new JScrollPane(ta);
glassPane = new JPanel() {
#Override
public void doLayout() {
Point p = sp.getLocation();
Dimension dim = sp.getSize();
p = SwingUtilities.convertPoint(sp, p, this);
btn.setSize(btn.getPreferredSize());
int barWidth = sp.getVerticalScrollBar().getWidth();
int barHeight = sp.getHorizontalScrollBar().getHeight();
int x = p.x + (dim.width - btn.getWidth()) - barWidth;
int y = p.y + (dim.height - btn.getHeight()) - barHeight;
btn.setLocation(x, y);
}
};
glassPane.setOpaque(false);
glassPane.add(btn);
glassPane.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
e.getComponent().doLayout();
}
});
add(sp);
}
#Override
public void addNotify() {
super.addNotify();
SwingUtilities.getRootPane(this).setGlassPane(glassPane);
glassPane.setVisible(true);
glassPane.revalidate();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
}
Take a look at How to use Root Panes for more details
Try using the OverlayLayout:
JPanel contentPane = new JPanel();
contentPane.setLayout( new OverlayLayout(ContentPane) );
frame.setContentPane( panel );
JButton button = new JButton(...);
button.setAlignmentX(0.0f);
button.setAlignmentY(1.0f);
contentPane.add( button );
ForumMainPage panel = new ForumMainPage(frame);
contentPane.add( panel );

Inserting an image under a JTextArea

so I'm trying to insert an image underneath a JTextArea, but I havent had much luck, could anyone please help? Basically what I'm asking is if anybody could help make another class or subclass that does this. Heres my code:
import java.awt.*;
import javax.swing.*;
public class t{
private JFrame f; //Main frame
private JTextArea t; // Text area private JScrollPane sbrText; // Scroll pane for text area
private JButton btnQuit; // Quit Program
public t(){ //Constructor
// Create Frame
f = new JFrame("Test");
f.getContentPane().setLayout(new FlowLayout());
String essay = "Test";
// Create Scrolling Text Area in Swing
t = new JTextArea(essay, 25, 35);
t.setEditable(false);
Font f = new Font("Verdana", Font.BOLD, 12 );
t.setFont( f );
t.setLineWrap(true);
sbrText = new JScrollPane(t);
sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// Create Quit Button
btnQuit = new JButton("Quit");
btnQuit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
} } );
}
public void launchFrame(){ // Create Layout
// Add text area and button to frame
f.getContentPane().add(sbrText);
f.getContentPane().add(btnQuit);
// Close when the close button is clicked
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display Frame
f.pack(); // Adjusts frame to size of components
f.setSize(450,480);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String args[]){
t gui = new t();
gui.launchFrame();
}
}
The basic issue is that JTextArea will paint it's background and it's text within the paintComponent.
The simplest solution is to make the JTextArea transparent and take over the control of painting the background.
This example basically fills the background with the background color, paints the image and then calls super.paintComponent to allow the text to be rendered.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TransparentTextArea {
public static void main(String[] args) {
new TransparentTextArea();
}
public TransparentTextArea() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(new CustomTextArea()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CustomTextArea extends JTextArea {
private BufferedImage image;
public CustomTextArea() {
super(20, 20);
try {
image = ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/Miho_Small_02.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public boolean isOpaque() {
return false;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
if (image != null) {
int x = getWidth() - image.getWidth();
int y = getHeight() - image.getHeight();
g2d.drawImage(image, x, y, this);
}
super.paintComponent(g2d);
g2d.dispose();
}
}
}
Check out the Background Panel. When you add a scrollpane to the panel it will make the scrollpane, viewport and text area all non-opaque so you can see the image.

How to set Jframe Background Image in GroupLayout Java

Am trying to set a background image for my frame but it does not work. I tried this link:
Setting background images in JFrame
The code:
setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/Images/about.png")))));
I tried adding the above code to my Contentpane but it does not work.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu frame = new MainMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainMenu() {
setIconImage(Toolkit.getDefaultToolkit().getImage(MainMenu.class.getResource("/Images/bug-red.png")));
setTitle("Automated Bug Fixing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 712, 458);
contentPane = new JPanel();
//contentPane.setBackground(new Color(220, 220, 220));
contentPane.setForeground(new Color(32, 178, 170));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
*setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/Images/about.png")))));*
The basic concept looks fine.
The only possible reason you might be getting problems is if the image doesn't exist.
It looks look you are trying to reference an image that should exist within the context of the Jar
Instead of
ImageIO.read(new File("/Images/about.png"))
Try
ImageIO.read(getClass().getResource("/Images/about.png"))
Instead.
Also, don't swallow exceptions, make sure all exceptions are been logged at the very least
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BackgroundFrameImage {
public static void main(String[] args) {
new BackgroundFrameImage();
}
public BackgroundFrameImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
JLabel label = new JLabel(new ImageIcon(ImageIO.read(...))));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(label);
frame.setLayout(new BorderLayout());
JLabel text = new JLabel("Hello from the foreground");
text.setForeground(Color.WHITE);
text.setHorizontalAlignment(JLabel.CENTER);
frame.add(text);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException | HeadlessException exp) {
exp.printStackTrace();
}
}
});
}
}
I've an inkling the problem may lie with
setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/Images/about.png")))));
Try removing the leading slash in the file path, as this may be interpreted differently based on the OS:
setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("Images/about.png")))));
Put everything on an IPanel and put the IPanel on the JFrame. Tweak as necessary to suit your needs.
public class IPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image imageOrg = null;
private Image image = null;
{
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(final ComponentEvent e) {
final int w = IPanel.this.getWidth();
final int h = IPanel.this.getHeight();
image = w > 0 && h > 0 ? imageOrg.getScaledInstance(w, h, Image.SCALE_SMOOTH) : imageOrg;
IPanel.this.repaint();
}
});
}
public IPanel(final Image i) {
imageOrg = i;
image = i;
}
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0, 0, null);
}
}
Example:
final JPanel j = new IPanel(image);
j.setLayout(new FlowLayout());
j.add(new JButton("YoYo"));
j.add(new JButton("MaMa"));
j.add(new JLabel(icon));
Produces:

Categories