Sorry guys I know there is a lot of info on this topic, but I'm still stuck. I have two panels mainPanel and sidePanel. What I'm trying to do is paint an Image to the sidePanel. My sidePanel will have other components such as buttons and labels. I can add the Image to the sidePanel using a JLabel, however, sizing and positioning the image is a problem. Therefor, I'm experimenting with Graphics g to paint the Image onto the sidePanel instead. If anyone could help much would be appreciated. Thanks all that help.` import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Gui extends JFrame {
private JPanel j;
private ImageIcon i;
public Gui(){
this.setSize(800,600);
this.setUp();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setUp(){
j = new JPanel();
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BorderLayout());
contentPanel.setSize(new Dimension(800,600));
JPanel mainPanel = new JPanel();
JPanel sidePanel = new JPanel();
sidePanel.setPreferredSize(new Dimension(200,600));
mainPanel.setPreferredSize(new Dimension(600,600));
ImagePanel v = new ImagePanel();
//v.setBackground(Color.BLUE);
v.setPreferredSize(new Dimension(100,100));
sidePanel.add(v);
mainPanel.setBackground(Color.BLACK);
sidePanel.setBackground(Color.RED);
contentPanel.add(sidePanel, BorderLayout.WEST);
contentPanel.add(mainPanel, BorderLayout.CENTER);
this.add(contentPanel);
}
private class ImagePanel extends JPanel{
public void createImage(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("/GUI Practice/src/images.jpeg");
Image ii = i.getImage();
g.drawImage(ii, 10, 10, 90, 90, Color.WHITE, this);
repaint();
validate();
updateUI();
}
}
public static void main(String [] args){
Gui g = new Gui();
}
}
`
Taken from bcash's answer here.
public class ImagePanel extends JPanel {
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("image name and path"));
} catch (IOException ex) {
// handle exception...
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
Related
I've done several inspection and done research on how to make a single panel transparent so that the image underneath it will show but has been unsuccessful with panels on a JTabbedPane. I have setOpaque(false) and setBackground(new Color(0,0,0,20)) on both the panels of the JTabbedPane and also did the same on the JTabbedPane itself. However, I still can't get the image on the back of the tabbed pane to show. What else am I missing here?
tabbePane.java
package tabbedpanetransparencypractice;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
public class tabbedPane extends JTabbedPane{
JPanel tab1panel = new JPanel();
JPanel tab2panel = new JPanel();
public tabbedPane(){
this.setPreferredSize(new Dimension(400,400));
this.setBackground(new Color(0,0,0,20));
this.setOpaque(false);
tab1panel.setBackground(new Color(0,0,0,20));
tab2panel.setBackground(new Color(0,0,0,20));
tab1panel.setOpaque(false);
tab2panel.setOpaque(false);
this.addTab("Tab 1", tab1panel);
this.addTab("Tab 2", tab2panel);
}
}
topPanel.java
package tabbedpanetransparencypractice;
import javax.swing.*;
import java.awt.*;
public class topPanel extends JPanel{
Image myBG = new ImageIcon(getClass().getClassLoader().getResource("Assets/loginBg.jpg")).getImage();
#Override
public void paintComponent(Graphics g){
g.drawImage(myBG,0,0,getWidth(),getHeight(),this);
}
public topPanel(){
addTabbedPane();
}
public void addTabbedPane(){
tabbedPane tabbedpane = new tabbedPane();
this.add(tabbedpane);
}
}
frame.java
package tabbedpanetransparencypractice;
import java.awt.Dimension;
import javax.swing.*;
public class frame extends JFrame{
topPanel myPanel = new topPanel();
public frame(){
this.setPreferredSize(new Dimension(600,600));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.pack();
this.setLocationRelativeTo(null);
addComponents();
}
final void addComponents(){
this.setContentPane(myPanel);
}
}
main.java
package tabbedpanetransparencypractice;
public class main {
public static void main(String[] args) {
frame myFrame = new frame();
}
}
This is the output I get (I want the tab1 and tab2 to be transparent to reveal the bg image underneath)
I'd appreciate any help. Thanks.
First, Swing DOES NOT know how to deal with component's whose background colors are alpha based but which are opaque. Swing only knows how to deal with fully opaque and fully transparent components.
Using alpha based colors will generate weird and random paint artefacts. The simple answer is, you should never apply a alpha based color to a component's background (the only exception is JFrame - thanks Sun :P)
The primary solution is, fake it.
That is, make the component transparent (setOpaque(false)) and paint the background at a reduced alpha level. You can then use a alpha based color (because the component is no longer reliant on the color, as it's transparent), but I tend to just use a AlphaComposite as it's generally easier to control and manipulate.
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
BackgroundPane bp = new BackgroundPane();
bp.setLayout(new BorderLayout());
bp.setBorder(new EmptyBorder(20, 20, 20, 20));
SeeThroughTabbedPane tp = new SeeThroughTabbedPane();
tp.setAlpha(0.5f);
tp.addTab("Tab 1", new TestPane("I be see through"));
tp.addTab("Tab 2", new TestPane("But you can't see me"));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(bp);
frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane(String text) {
setOpaque(false);
setLayout(new GridBagLayout());
JLabel label = new JLabel(text);
label.setForeground(Color.WHITE);
add(label);
}
}
public class BackgroundPane extends JPanel {
private BufferedImage bg;
public BackgroundPane() {
try {
bg = ImageIO.read(new File("/Volumes/Disk02/Dropbox/MegaTokyo/megatokyo_omnibus_1_3_cover_by_fredrin-d4oupef 50%.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return bg == null ? new Dimension(200, 200) : new Dimension(bg.getWidth(), bg.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - bg.getWidth()) / 2;
int y = (getHeight() - bg.getHeight()) / 2;
g2d.drawImage(bg, x, y, this);
g2d.dispose();
}
}
}
public class SeeThroughTabbedPane extends JTabbedPane {
private float alpha;
public SeeThroughTabbedPane() {
setOpaque(false);
setAlpha(1f);
}
public void setAlpha(float value) {
if (alpha != value) {
float old = alpha;
this.alpha = value;
firePropertyChange("alpha", old, alpha);
repaint();
}
}
public float getAlpha() {
return alpha;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(getAlpha()));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
}
}
Remember, anything you added to the JTabbedPane which is still opaque will remain so, not in my TestPane's constructor, I set the panel's opaque state to false
You might also like to take a look at Painting in AWT and Swing and Performing Custom Painting
You might be able to use UIManager.put("TabbedPane.contentAreaColor", new Color(255, 255, 0, 100));
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TransparentTabbedPaneTest {
public JComponent makeUI() {
Color bgc = new Color(110, 110, 0, 100);
Color fgc = new Color(255, 255, 0, 100);
UIManager.put("TabbedPane.shadow", fgc);
UIManager.put("TabbedPane.darkShadow", fgc);
UIManager.put("TabbedPane.light", fgc);
UIManager.put("TabbedPane.highlight", fgc);
UIManager.put("TabbedPane.tabAreaBackground", fgc);
UIManager.put("TabbedPane.unselectedBackground", fgc);
UIManager.put("TabbedPane.background", bgc);
UIManager.put("TabbedPane.foreground", Color.WHITE);
UIManager.put("TabbedPane.focus", fgc);
UIManager.put("TabbedPane.contentAreaColor", fgc);
UIManager.put("TabbedPane.selected", fgc);
UIManager.put("TabbedPane.selectHighlight", fgc);
UIManager.put("TabbedPane.borderHightlightColor", fgc);
JTabbedPane tabs = new JTabbedPane();
JPanel tab1panel = new JPanel();
tab1panel.setBackground(new Color(0, 220, 220, 50));
JPanel tab2panel = new JPanel();
tab2panel.setBackground(new Color(220, 0, 0, 50));
JPanel tab3panel = new JPanel();
tab3panel.setBackground(new Color(0, 0, 220, 50));
JCheckBox cb = new JCheckBox("setOpaque(false)");
cb.setOpaque(false);
tab3panel.add(cb);
tab3panel.add(new JCheckBox("setOpaque(true)"));
tabs.addTab("Tab 1", tab1panel);
tabs.addTab("Tab 2", tab2panel);
tabs.addTab("Tab 3", new AlphaContainer(tab3panel));
JPanel p = new JPanel(new BorderLayout()) {
private Image myBG = new ImageIcon(getClass().getResource("test.png")).getImage();
#Override public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(myBG, 0, 0, getWidth(), getHeight(), this);
}
};
p.add(tabs);
p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
return p;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TransparentTabbedPaneTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
//https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/
class AlphaContainer extends JComponent {
private JComponent component;
public AlphaContainer(JComponent component) {
this.component = component;
setLayout( new BorderLayout() );
setOpaque( false );
component.setOpaque( false );
add( component );
}
/**
* Paint the background using the background Color of the
* contained component
*/
#Override
public void paintComponent(Graphics g) {
g.setColor( component.getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
}
}
I want to make a background image for a game I'm designing but I cant figure out the right way to get the effect I want, I want a background that can be seen behind text etc. basically having the background cover the whole JFrame / JPanel not just one section of the layout (e.g. BorderLayout.Center) I think it does this anyway but if it does do that how do I make the background for those transparent to see the background which is behind...
Confusing i know but I hope someone here understands what I am trying to do and can help... this is my current code. I have been playing around with the background so dont read to much in how i have written it.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class GamePanel extends JPanel {
private JTextPane playertext;
private JTextField wealthstring, currentwealth;
public GamePanel() {
super();
setLayout(new BorderLayout());
setBackground(Game.getBackgroundColor());
Border raised = BorderFactory.createRaisedBevelBorder();
Border lowered = BorderFactory.createLoweredBevelBorder();
setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(4, 4, 4, 4), (BorderFactory.createCompoundBorder(raised, lowered))));
add(northpanel(), BorderLayout.NORTH);
add(eastpanel(), BorderLayout.EAST);
}
private JLabel northpanel() {
Font northfont = new Font("Engravers MT", Font.BOLD, 12);
ImageIcon banner = new ImageIcon("images/banner.png", "North Background");
playertext = new JTextPane();
playertext.setFont(northfont);
playertext.setEditable(false);
playertext.setText("Player: \n" + Game.getName());
playertext.setBackground(Game.getBackgroundColor());
playertext.setBorder(new EmptyBorder(10,10,10,10));
wealthstring = new JTextField("Money: ");
wealthstring.setFont(northfont);
wealthstring.setEditable(false);
wealthstring.setHorizontalAlignment(wealthstring.RIGHT);
wealthstring.setBorder(null);
wealthstring.setBackground(Game.getBackgroundColor());
currentwealth = new JTextField();
currentwealth.setFont(northfont);
currentwealth.setEditable(false);
currentwealth.setHorizontalAlignment(wealthstring.RIGHT);
currentwealth.setBackground(Game.getBackgroundColor());
currentwealth.setBorder(null);
String wealthrounded = String.format("%.2f", Game.getMoney());
currentwealth.setText(wealthrounded);
JPanel wealthtext = new JPanel();
wealthtext.setLayout(new GridLayout(2, 1));
wealthtext.setBackground(Game.getBackgroundColor());
wealthtext.setBorder(new EmptyBorder(10,10,10,10));
wealthtext.add(wealthstring);
wealthtext.add(currentwealth);
JLabel northpanel = new JLabel();
northpanel.setLayout(new BorderLayout());
northpanel.setIcon(banner);
northpanel.add(new JSeparator(), BorderLayout.PAGE_END);
northpanel.add(playertext, BorderLayout.WEST);
northpanel.add(wealthtext, BorderLayout.EAST);
return northpanel;
}
private JPanel eastpanel() {
JButton tab1 = new JButton("Tab 1");
JButton tab2 = new JButton("Tab 2");
JButton tab3 = new JButton("Tab 3");
JPanel easttabs = new JPanel();
easttabs.setLayout(new GridLayout(1, 3));
easttabs.add(tab1);
easttabs.add(tab2);
easttabs.add(tab3);
JPanel eastpanels = new JPanel();
eastpanels.setLayout(new BorderLayout());
eastpanels.setBackground(Game.getBackgroundColor());
eastpanels.add(easttabs, BorderLayout.NORTH);
return eastpanels;
}
}
So if you already have a JPanel that has your image as Background and you want to add another panel over it with your components you can use Opacity to achieve this. Only the components added to this panel will be visible. Here's the code :
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class TransparentPane extends JPanel {
public TransparentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0f));
g2d.setColor(getBackground());
g2d.fill(getBounds());
g2d.dispose();
}
}
Create a class that extends from JPanel and in its paint method draw an image over it.
Now create a class the extends from JFrame and in its constructor set its contentpane to the object of that JPanel class like below. Now you can add components to jframe.
class SimpleTest extends JFrame {
JButton btn = new JButton("A Game");
public SimpleTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new CPane());
getContentPane().setBackground(Color.red);
getContentPane().add(btn, BorderLayout.NORTH);
setSize(new Dimension(300, 300));
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleTest();
}
});
}
}
class CPane extends JPanel {
Image back;
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
back = ImageIO.read(getClass().getResource("back.jpg"));
} catch (Exception ex) {
}
g.drawImage(back, 0, 0, this);
}
}
If you want to make a jpanel transparent then do
panel.setOpaque(false);
I'm creating a slideshow using swing and trying to place it in the center of my JFrame. The slideshow works fine, but it's taking up the entire center section. How would I limit it to a small place under the banner?
Here's a picture of what it looks like.
Here's a picture of what I want it to look like
This is what I have so far, you run this class.
package com.RBV2.engine;
import javax.swing.*;
import com.RBV2.Settings;
import com.RBV2.panels.News;
import com.RBV2.panels.SlideShow;
import com.RBV2.panels.SlideShow.MovingPanel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;
/*
* Author Jon & David
*
*/
#SuppressWarnings("serial")
public class Client extends JFrame implements ActionListener {
private JPanel bottomPanel, news;
private JButton launch;
private JLabel loading, banner;
private MovingPanel slideshow;
protected boolean updated = false;
private void createLayout() {
createPanel();
addPanel();
setVisible(true);
}
private void createPanel() {
bottomPanel = new JPanel(new BorderLayout());
news = new News();
slideshow = new SlideShow.MovingPanel();
launch = new JButton(new URL("http://www.runerebellion.com/clientImages/launch.png"));
loading = new JLabel(new URL("http://www.runerebellion.com/clientImages/loader.gif"));
banner = new JLabel(new URL("http://www.runerebellion.com/clientImages/201457.gif"));
launch.addActionListener(this);
}
private void addPanel() {
setTitle("RuneRebellionV2 Launcher");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Bottom Panel
add(bottomPanel, BorderLayout.SOUTH);
bottomPanel.add(new JLabel(" Launcher, release " + Settings.version), BorderLayout.WEST);
bottomPanel.setBackground(Color.BLACK);
bottomPanel.add(launch, BorderLayout.EAST);
launch.setPreferredSize(new Dimension(120, 40));
//News Feed
add(news, BorderLayout.CENTER);
news.add(banner, BorderLayout.CENTER);
banner.setPreferredSize(new Dimension(500, 70));
//slideshow
slideshow.setPreferredSize(new Dimension(610, 331));
add(slideshow, BorderLayout.CENTER);
//Sets size
setSize(Settings.width, Settings.height);
}
public Client() throws IOException {
createLayout();
}
public static void main(String args[]) throws IOException {
final Client l = new Client();
l.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
l.setVisible(true);
}
});
}
These specific lines of code call the slideshow(I commented out exactly where)
private void addPanel() {
setTitle("RuneRebellionV2 Launcher");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Bottom Panel
add(bottomPanel, BorderLayout.SOUTH);
bottomPanel.add(new JLabel(" Launcher, release " + Settings.version), BorderLayout.WEST);
bottomPanel.setBackground(Color.BLACK);
bottomPanel.add(launch, BorderLayout.EAST);
launch.setPreferredSize(new Dimension(120, 40));
//News Feed
add(news, BorderLayout.CENTER);
news.add(banner, BorderLayout.CENTER);
banner.setPreferredSize(new Dimension(500, 70));
//slideshow here
slideshow.setPreferredSize(new Dimension(610, 331));
add(slideshow, BorderLayout.CENTER);
//Sets size
setSize(Settings.width, Settings.height);
}
Here is my slideshow class, you may need this also.
package com.RBV2.panels;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class SlideShow extends JFrame {
public static class MovingPanel extends JPanel {
public int i = 0;
public MovingPanel() {
Timer timer = new Timer(3000, new TimerListener());
timer.start();
}
protected void paintComponent(Graphics x) {
super.paintComponent(x);
int y = i % 25;
Image showImg = new ImageIcon("bin/slide/" + y + ".png").getImage();
x.drawImage(showImg, 0, 0, getWidth(), getHeight(), 0, 0, 610, 331, null);
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
i++;
repaint();
if (i >= 5)
i = 1;
}
}
}
}
So my question is how would I limit the slideshow to be in a box in the very center under the banner.
Have a look at this picture (from Border layout Tutorial)
As you are only adding panels to the Center and South(PAGE_END) regions of the layout manager there is no other components to stop the center panel from stretching out as far as it can.
Note this relevant sentence of the tutorial
If the window is enlarged, the center area gets as much of the available space as possible. The other areas expand only as much as necessary to fill all available space. Often a container uses only one or two of the areas of the BorderLayout object — just the center, or the center and the bottom.
You either need to add blank panels on the other sides or make use of an empty border within your Center panel. See here about how to use borders.
I painted the background, then painted the images over the background
protected void paintComponent(Graphics x) {
super.paintComponent(x);
int y = i % 25;
Image showImg = new ImageIcon("bin/slide/" + y + ".png").getImage();
super.paintComponent(x);
x.drawImage((Settings.background).getImage(), 0, 0, getWidth(), getHeight(), this);
x.drawImage(showImg, 360, 260, getWidth(), getHeight(), 0, 0, 110, 31, null);
}
I am making a small app, but i want to set an image as background at the whole window. I tried to make this like below but nothing happen. The image is in the folder where the class is so as a path I put only the name...Can you help me please? what can I do?
Container c = getContentPane();
setContentPane(c);
setContentPane(new JLabel(new ImageIcon("Chrysanthemum.jpg")));
One possibility is to add a BorderLayout to the JFrame, which should fill the JFrame with the JLabel, then set the background, adding the JLabel to the frame and then add components to it, like this:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Foo extends JFrame {
public Foo() {
setLayout(new BorderLayout());
JLabel background = new JLabel(new ImageIcon("Untitled.png"));
add(background);
background.setLayout(new FlowLayout());
background.add(new JButton("foo"));
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args) {
Foo foo = new Foo();
}
}
The above works for me, with the JButton at the top center of the 500 by 500 JFrame with the specified background.
What I would do is create a JPanel with a background image, and add it to the JFrame. I already have a BackgroundPanel class right in one of my projects, and this is the setup I have for it.
public class MyFrame extends JFrame {
private BackgroundPanel bgPanel;
public MyFrame() {
bgPanel = new BackgroundPanel("Chrysanthemum.jpg");
setTitle("MyFrame");
setResizable(false);
setContentPane(bgPanel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
// -- BackgroundPanel class
public class BackgroundPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image bg;
public BackgroundPanel(String path) {
this(Images.load(path).getImage());
}
public BackgroundPanel(Image img) {
this.bg = img;
setPreferredSize(new Dimension(bg.getWidth(null), bg.getHeight(null)));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) g.drawImage(bg, 0, 0, getWidth(), getHeight(), null);
}
}
I just created a simple imagepanel and add a button on the panel
Can any body tell me wats the problem in code?
Image is displaying but button is not
package inventorymanagement;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageTest {
public static void main(String[] args) {
ImagePanel panel = new ImagePanel(new ImageIcon("E:/Desktop[/icon/6470729-exclamation-mark-icon-button-3d-red-glossy-circle.jpg").getImage());
JButton jButton1=new JButton("jButton1");
panel.add(jButton1);
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
You have to set the layout for the panel
Just add panel.setLayout(new java.awt.FlowLayout()); before adding the button panel.add(jButton1);.
when you setLayout(null); you need to setBounds to all your component. You should read these tutorial: http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html