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:
Related
I am coding a GUI containing a JScrollPane that displays an image that gets updated (with potential modification of its dimensions). The image is in an ImageIcon in a JLabel. The image size is retrieved using ImageIcon.getIconWith() and getIconHeight(). And the JLabel preferred size is updated with those dimensions.
When the application is started for the first time, the JScrollPane and its scrollbars have the right dimensions to view the whole image (potentially using scrolling). But when the image gets updated the JScrollPane and the scrollbars assume the image has the dimensions of the previous image. How do I get the JScrollPane to update correctly ?
Here is a curated version of my GUI. Visualizer.java uses the GUI VisualizerGUI.java. When the "Run" button is pushed, a new image is randomly generated using ImageDrawer.drawImage() (simulates the behavior of the real application) and the content of the JScrollPane is updated using the function VisualizerGUI.setTransitionsImage(String imgPath).
Visualizer.java:
import java.util.*;
import java.io.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Visualizer implements ActionListener {
private VisualizerGUI gui = null;
public Visualizer() {
gui = VisualizerGUI.createAndStart(this);
}
public static void main(String[] args) {
Visualizer viz = new Visualizer();
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Run command")) {
run();
}
}
public void run() {
updateGUIwithSolution();
}
public void updateGUIwithSolution() {
gui.initGUIupdate();
try {
ImageDrawer.drawImage();
gui.setTransitionsImage("image.png");
} catch (Exception e) {
System.out.println("Error while generating image");
e.printStackTrace();
}
gui.finalizeGUIupdate();
}
}
VisualizerGUI.java:
import java.util.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
public final class VisualizerGUI {
private JFrame frame;
private JButton runButton;
private JButton nextButton;
private JScrollPane transitionsDisplay;
private JTabbedPane executionsDisplay;
private JTabbedPane tracesDisplay;
private JTextArea textInfoArea;
public VisualizerGUI() {}
private void initGUI(ActionListener actionsHandler) {
//Create and set up the window.
frame = new JFrame("Visualizer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel controlPanel = new JPanel(new FlowLayout());
runButton = new JButton("Run");
runButton.addActionListener(actionsHandler);
runButton.setActionCommand("Run command");
controlPanel.add(runButton);
nextButton = new JButton("Next");
nextButton.addActionListener(actionsHandler);
nextButton.setActionCommand("Find next solution");
controlPanel.add(nextButton);
transitionsDisplay = new JScrollPane();
executionsDisplay = new JTabbedPane();
tracesDisplay = new JTabbedPane();
JSplitPane ETspliter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, executionsDisplay, tracesDisplay);
JSplitPane graphsSpliter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, transitionsDisplay, ETspliter);
textInfoArea = new JTextArea();
textInfoArea.setLineWrap(true);
textInfoArea.setWrapStyleWord(true);
textInfoArea.setEditable(false);
JScrollPane textInfoAreaSP = new JScrollPane(textInfoArea);
JSplitPane topSpliter = new JSplitPane(JSplitPane.VERTICAL_SPLIT, graphsSpliter, textInfoAreaSP);
transitionsDisplay.setPreferredSize(new Dimension(200,200));
executionsDisplay.setPreferredSize(new Dimension(200,200));
tracesDisplay.setPreferredSize(new Dimension(200,200));
textInfoAreaSP.setPreferredSize(new Dimension(200,100));
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(controlPanel, BorderLayout.NORTH);
frame.getContentPane().add(topSpliter, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static VisualizerGUI createAndStart(ActionListener actionsHandler) {
VisualizerGUI gui = new VisualizerGUI();
final Runnable guiRunner =
new Runnable() {
public void run() {
gui.initGUI(actionsHandler);
// gui.pack();
}
};
try {
javax.swing.SwingUtilities.invokeAndWait(guiRunner);
} catch (InterruptedException e) {
System.out.println(">>> WARNING <<< InterruptedException while creating the GUI");
} catch (InvocationTargetException e) {
System.out.println(">>> WARNING <<< InvocationTargetException while creating the GUI");
}
return gui;
}
public void clear() {
initGUIupdate();
finalizeGUIupdate();
}
public void initGUIupdate() {
// frame.setVisible(false);
transitionsDisplay.setViewportView(null);
executionsDisplay.removeAll();
tracesDisplay.removeAll();
textInfoArea.setText(null);
}
public void pack() {
frame.pack();
}
public void finalizeGUIupdate() {
// frame.validate();
// frame.repaint();
// frame.setVisible(true);
}
public void setTransitionsImage(String imgPath) {
ImageIcon icon = new ImageIcon(imgPath);
icon.getImage().flush();
int width = icon.getIconWidth();
int height = icon.getIconHeight();
JLabel label = new JLabel();
label.setVerticalAlignment(SwingConstants.CENTER);
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setIcon(icon);
label.setPreferredSize(new Dimension(width,height));
//label.setPreferredSize(null);
transitionsDisplay.setViewportView(label);
label.revalidate();
label.repaint();
transitionsDisplay.getViewport().revalidate();
transitionsDisplay.getViewport().repaint();
transitionsDisplay.revalidate();
// transitionsDisplay.validate();
transitionsDisplay.repaint();
frame.revalidate();
// frame.validate();
frame.repaint();
}
public void setTransitionsImageInED(String imgPath) {
final Runnable guiRunner =
new Runnable() {
public void run() { setTransitionsImage(imgPath); }
};
// javax.swing.SwingUtilities.invokeLater(guiRunner);
try {
javax.swing.SwingUtilities.invokeAndWait(guiRunner);
} catch (InterruptedException e) {
System.out.println(">>> WARNING <<< InterruptedException while creating the GUI");
} catch (InvocationTargetException e) {
System.out.println(">>> WARNING <<< InvocationTargetException while creating the GUI");
}
}
}
ImageDrawer.java:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageDrawer {
public static void drawImage() throws Exception {
try {
int width = 20 + (int)(Math.random() * 1000);
int height = 20 + (int)(Math.random() * 1000);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();
ig2.setPaint(Color.blue);
ig2.fillRect(0, 0, width, height);
ig2.setPaint(Color.red);
ig2.fillRect(5, 5, width - 10, height - 10);
ig2.setPaint(Color.blue);
ig2.drawLine(0, 0, width, height);
ig2.drawLine(0, height, width, 0);
ImageIO.write(bi, "PNG", new File("image.png"));
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
Can someone explain why I have this problem? Thanks!
transitionsDisplay.setPreferredSize(new Dimension(200,200));
executionsDisplay.setPreferredSize(new Dimension(200,200));
tracesDisplay.setPreferredSize(new Dimension(200,200));
textInfoAreaSP.setPreferredSize(new Dimension(200,100));
Don't use setPreferredSize(...). Each Swing component is responsible for determining its own size.
The image size is retrieved using ImageIcon.getIconWith() and getIconHeight(). And the JLabel preferred size is updated with those dimensions.
Not necessary. Again the JLabel will determine its own size based on the size of the Icon. This is done dynamically as the image/icon changes.
The scrollbars of the scrollpane will appear when the preferred size of the label is greater than the size of the scrollpane. Just let the layout managers do their job.
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);
}
}
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;
}
}
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 );
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);'
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);
}
}
}
}
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?
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.
have you tried JFrame function setUndecorated() ?
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.