Setting a background image in JTabbedPane - java

I want to set a background image in a simple JTabbedPane. I used a Jlabel to set my background image. But i haven't been able to do so as i get a null pointer exception upon running.
Can anyone help with some more ideas?
Here is my code:
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.*;
class ImageTest
{
JTabbedPane tp;
JLabel lab1
JPanel welcome;
JFrame frame;
ImageIcon image2;
public void createUI()
{
frame=new JFrame("JTabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcome= new JPanel(null);
welcome.setPreferredSize(new Dimension(1366,786));
image2 = new ImageIcon("icloud.jpg");
tp=new JTabbedPane();
Container pane = frame.getContentPane();
pane.add(tp);
tp.addTab("Welcome", welcome);
lab1.setIcon(image2);
lab1.setBounds(0,0,1500,700);
frame.setSize(500,500);
frame.setVisible(true);
frame.setTitle("I-Cloud");
}
public static void main(String[] args)
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
ImageTest tbp = new ImageTest ();
tbp.createUI();
}
}
EDIT:
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.*;
class ImageTest
{
JTabbedPane tp;
JLabel lab1;
JPanel welcome,w;
JFrame frame;
ImageIcon image2;
JButton b1;
public void createUI()
{
frame=new JFrame("JTabbedPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton();
welcome= new JPanel(new GridLayout(1,1,15,15));
w=new JPanel (new GridLayout(1, 1, 15, 15));
welcome.setPreferredSize(new Dimension(1366,786));
ImageIcon icon = new ImageIcon(ImageTest.class.getResource("icloud.jpg"));
tp=new JTabbedPane();
Container pane = frame.getContentPane();
pane.add(tp);
lab1=new JLabel();
lab1.setIcon(icon);
w.setOpaque(false);
w.add(b1);
b1.setVisible(true);
welcome.add(lab1);
welcome.add(w);
tp.addTab("Welcome", welcome);
frame.setSize(500,500);
frame.pack();
frame.setVisible(true);
frame.setTitle("I-Cloud");
}
public static void main(String[] args)
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
ImageTest w = new ImageTest();
w.createUI();
}
}

You may just want to paint the image onto the panel you use for the JTabbedPane (as seen below). But as MadProgammer pointed out. It's most likely you are getting a null from the file location of your image file.
Note: when passing a String to the ImageIcon you are telling it to look for image in the file system. though this may work in a development environment from your IDE, it will not work at time of deployment Instead of reading the image file from the file system, you want to load it from the class path, as should be don with embedded resources, using a URL, which can be obtained by using MyClass.class.getResource(path)
So the way you should loading your image is like this
ImageIcon icon = new ImageIcon(ImageTest.class.getResource("icloud.jpg"));
And your image file would be in the same package as ImageIcon.java. You don't have to put the image in the same package, as you can specify a different path. You can find more info from the embedded resource tag wiki link above.
But back to the option of painting the background, see the example below. Instead of using a URL web link for the image though, you would read in your image file path as specified above.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TabBackground {
private BufferedImage bg;
public TabBackground() {
try {
bg = ImageIO.read(new URL("http://2.bp.blogspot.com/-wWANHD-Dr00/TtSmeY57ZXI/AAAAAAAABB8/t-fpXmQZ0-Y/s1600/Vector_by_Karpiu23.png"));
} catch (IOException ex) {
Logger.getLogger(TabBackground.class.getName()).log(Level.SEVERE, null, ex);
}
JPanel tabPanel = new JPanel(new GridBagLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
};
JPanel buttons = new JPanel(new GridLayout(4, 1, 15, 15));
buttons.setOpaque(false);
for (int i = 0; i < 4; i++) {
buttons.add(new JButton("Button"));
}
tabPanel.add(buttons);
JTabbedPane tabPane = new JTabbedPane();
tabPane.add("Panel with Bachground", tabPanel);
JFrame frame = new JFrame("Tabbed Pane with Background");
frame.setContentPane(tabPane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
Logger.getLogger(TabBackground.class.getName()).log(Level.SEVERE, null, ex);
}
new TabBackground();
}
});
}
}

You can add an image like this on Jframe:
tp.addTab("Welcome",new JLabel(new ImageIcon("bksqla_xlargecover.jpg")));

Related

Why can't I resize or relocate my JButton on my JPanel?

package swingtraining;
import static java.awt.Color.BLACK;
import static java.awt.Color.RED;
import java.awt.EventQueue;
import static java.awt.Font.BOLD;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class JFrameWithAButton extends JFrame {
public JFrameWithAButton(){
setSize(400,400);
setTitle("Swing is hard");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]){
JPanel Jp1 = new JPanel();
Jp1.setOpaque(true);
Jp1.setBackground(RED);
JButton Jbt = new JButton();
Jbt.setLayout(null);
Jbt.setSize(200,200);
Jbt.setBounds(new Rectangle(new Point(200, 200)));
Jbt.setText("Hello!");
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrameWithAButton ex = new JFrameWithAButton();
ex.setVisible(true);
ex.add(Jp1);
Jp1.add(Jbt);
}
});
}
}
Sorry if the code's a bit mom's spaghetti-esque, but I just can't crack this cookie >.> Even with layout set to null it doesn't move. Any suggestions of how I get this JButton to not only move to the middle of the window but also grow 200 by 200 pixels?
Any suggestions of how I get this JButton to not only move to the middle of the window but also grow 200 by 200 pixels?
I can think of a few, none of which use null layouts
GridBagConstraints
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
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();
}
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 {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx = 200;
gbc.ipady = 200;
add(new JButton("Hello"), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
JButton#setMargin
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
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();
}
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 {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton btn = new JButton("Hello");
btn.setMargin(new Insets(100, 100, 100, 100));
add(btn);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
EmptyBorder
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
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();
}
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 {
public TestPane() {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(50, 50, 50, 50));
JButton btn = new JButton("Hello");
add(btn);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
You could use combination of them, maybe using an EmptyBorder and GridBagConstraints to further constrain the layout.
The great benefit of these examples, is, for the most part, if the font size changes or the rendering requirements for the fonts change, the layout is capable of compensating
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
And because it's always a fun read, Why is it frowned upon to use a null layout in SWING?
if you wanna define any component size manually you have to set the mother component's layout: null
so you have to set Jframe layout null to define Jpanel size and location
then you have to set JPanel layout null to define Jbutton size and location in it
final JPanel Jp1 = new JPanel();
Jp1.setOpaque(true);
Jp1.setBackground(RED);
Jp1.setLayout(null);
final JButton Jbt = new JButton();
// Jbt.setLayout(null); not needed!
Jbt.setBounds(10, 10, 100, 40);
// Jbt.setBounds(new Rectangle(new Point(200, 200))); not in this style
Jbt.setText("Hello!");
Jp1.add(Jbt);
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrameWithAButton ex = new JFrameWithAButton();
ex.setVisible(true);
ex.add(Jp1);
}
});
don't forget to define size and location both when you are adding a component in a null layout Jpanel or Jframe and ...

Transparent JTexfield with background image

I wanted to know how to set an image to a JTextField if this is transparent, or how to make my JTextField look like this:
Here's how I make my field transparent, but I can't set its background image:
//Step 1: Remove the border line to make it look like a flat surface.
field.setBorder(BorderFactory.createLineBorder(Color.white, 0));
//Step 2: Set the background color to null to remove the background.
field.setBackground(null);
All Swing components have a concept of transparency, which is controlled via the use of opaque property. Setting the background to null tents to rest the background color of the field to it's UI default.
Having said that, some components can ignore this (partially or completely). In these case we can cheat...
In the following example, set the field transparent via the opaque property, this is important, as the RepaintManager will not paint areas behind components unless they are transparent, and use a fully transparent background color.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
field.setBackground(new Color(0, 0, 0, 0));
field.setOpaque(false);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.RED);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Updated based on comments...
This is a very specific example designed to provide a direct answer to the presented problem. Basically, what this does is creates a custom border and uses an Image to render the "border"
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import javax.swing.border.MatteBorder;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
try {
BufferedImage img = ImageIO.read(getClass().getResource("/FieldBorder.png"));
field.setBorder(new ImageBorder(img, 8, 6));
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImageBorder implements Border {
private BufferedImage img;
private int bottomMargin;
private int leftMargin;
public ImageBorder(BufferedImage img, int leftMargin, int bottomMargin) {
this.img = img;
this.bottomMargin = bottomMargin;
this.leftMargin = leftMargin;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.drawImage(img, x, y + height - img.getHeight(), c);
}
#Override
public Insets getBorderInsets(Component c) {
return new Insets(0, leftMargin, bottomMargin, 0);
}
#Override
public boolean isBorderOpaque() {
return false;
}
}
}
Now, this could also be done using custom painting within the custom Border instead, but was quicker this way ;)
Another option...
Is to simply use a JPanel and add the field and a JLabel holding the border outline together, for example...
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
field.setBorder(null);
JPanel fieldPane = new JPanel(new GridBagLayout());
fieldPane.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 8, 0, 0);
fieldPane.add(field, gbc);
try {
BufferedImage img = ImageIO.read(getClass().getResource("/FieldBorder.png"));
gbc.insets = new Insets(0, 0, 0, 0);
fieldPane.add(new JLabel(new ImageIcon(img)), gbc);
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(fieldPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
But this will come down to needs and requirements...
Text field with a background
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.Document;
public class TextFieldBackground {
public static void main(String[] args) {
new TextFieldBackground();
}
public TextFieldBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
TextFieldWithBackground field = new TextFieldWithBackground(40);
try {
field.setBackgroundImage(ImageIO.read(getClass().getResource("/clouds.jpg")));
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TextFieldWithBackground extends JTextField {
private BufferedImage bg;
public TextFieldWithBackground() {
}
public TextFieldWithBackground(String text) {
super(text);
}
public TextFieldWithBackground(int columns) {
super(columns);
}
public TextFieldWithBackground(String text, int columns) {
super(text, columns);
}
public TextFieldWithBackground(Document doc, String text, int columns) {
super(doc, text, columns);
}
public void setBackgroundImage(BufferedImage bg) {
this.bg = bg;
setOpaque(bg == null);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
if (bg != null) {
int x = 0;
int y = (getHeight() - bg.getHeight()) / 2;
while (x < getWidth()) {
g.drawImage(bg, x, y, this);
x += bg.getWidth();
}
}
super.paintComponent(g);
}
}
}

On using Nimbus look and feel, JButton vanishes totally in a JFrame if there is a background image

I have a JFrame. In that i have used:
JTabbed panes.
JButton.
background images in a Jlabel which is added in JPanel.
Nimbus look and feel.
My problem is that whenever i use Nimbus look and feel the JButton vanishes only if there is a background image added. But this doesn't happen with other look and feel. Can anyone help me in getting the button visible?
Here is my code:
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.*;
class ImageTest
{
JTabbedPane tp;
JLabel lab1;
JPanel welcome;
JFrame frame;
ImageIcon image2;
JButton b1;
public void createUI()
{
frame=new JFrame("JTabbedPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton();
welcome= new JPanel(null);
welcome.setPreferredSize(new Dimension(1366,786));
ImageIcon icon = new ImageIcon(ImageTest.class.getResource("icloud.jpg"));
tp=new JTabbedPane();
Container pane = frame.getContentPane();
pane.add(tp);
tp.addTab("Welcome", welcome);
lab1=new JLabel();
lab1.setIcon(icon);
b1.setBounds(100,100,100,100);
lab1.setBounds(0,0,1500,700);
welcome.add(lab1);
welcome.add(b1);
b1.setVisible(true);
frame.setSize(500,500);
frame.setVisible(true);
frame.setTitle("I-Cloud");
}
public static void main(String[] args)
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
ImageTest w = new ImageTest();
w.createUI();
}
}
EDIT:
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.*;
class ImageTest
{
JTabbedPane tp;
JLabel lab1;
JPanel welcome,w;
JFrame frame;
ImageIcon image2;
JButton b1;
public void createUI()
{
frame=new JFrame("JTabbedPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton();
welcome= new JPanel(new GridLayout(1,1,15,15));
w=new JPanel (new GridLayout(1, 1, 15, 15));
welcome.setPreferredSize(new Dimension(1366,786));
ImageIcon icon = new ImageIcon(ImageTest.class.getResource("icloud.jpg"));
tp=new JTabbedPane();
Container pane = frame.getContentPane();
pane.add(tp);
lab1=new JLabel();
lab1.setIcon(icon);
w.setOpaque(false);
w.add(b1);
b1.setVisible(true);
welcome.add(lab1);
welcome.add(w);
tp.addTab("Welcome", welcome);
frame.setSize(500,500);
frame.pack();
frame.setVisible(true);
frame.setTitle("I-Cloud");
}
public static void main(String[] args)
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
ImageTest w = new ImageTest();
w.createUI();
}
}
Thanks.
Your use of Swing GUI is out of kilter by use of null layouts and then adding one component on top of another, essentially covering up one of the components (the JButton) with another (the JLabel with the image).
Don't use null layout like you're doing. While to a newbie using null layout and setBounds seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.
Don't add one component on top of another in the same container.
Instead give your JLabel with the image a layout manager.
Then add the JButton to the JLabel.
Then add the JLabel to the JTabbedPane.
Edit
Your latest edit did not use the JLabel as the container as suggested above. So if you use a separate container, then the button and the label will be shown side by side. To solve this, you either need to give the JLabel a layout manager, and then add the button to it as suggested above, or draw directly in a JPanel's paintComponent(...) method, and add the button to the JPanel.
For an example of the latter:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class MyImageTest extends JPanel {
// public static final String SPEC = "https://duke.kenai.com/SunRIP/.Midsize/SunRIP.jpg.png";
public static final String SPEC = "http://upload.wikimedia.org/wikipedia/commons/3/37/"
+ "Mandel_zoom_14_satellite_julia_island.jpg";
private static final int PREF_H = 786;
private static final int GAP = 100;
private BufferedImage img;
public MyImageTest() {
try {
URL imgUrl = new URL(SPEC);
img = ImageIO.read(imgUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
setLayout(new FlowLayout(FlowLayout.LEADING));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
JButton b = new JButton();
b.setPreferredSize(new Dimension(GAP, GAP));
add(b);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
#Override
public Dimension getPreferredSize() {
if (img == null) {
return super.getPreferredSize();
} else {
int width = (img.getWidth() * PREF_H) / img.getHeight();
return new Dimension(width, PREF_H);
// return new Dimension(img.getWidth(), img.getHeight());
}
}
private static void createAndShowGui() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
MyImageTest mainPanel = new MyImageTest();
JFrame frame = new JFrame("MyImageTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I think setting a background image in JLabel and then adding buttons even after adding containers is a very complex issue. Believe me tried it and it was a very complex task. you can do it by directly drawing as Hovercraft suggested, but remember you would get not so much good image quality with that method. :-|

Java Swing programming panel title

Looking at the screen short
how do i add the Steps and Choose project
is it a jabel or a title in the panel
This would be done by utilising the Border API available within the Swing. Take a closer look at How to use borders for more details.
As a very rough example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
public class PanelTitles {
public static void main(String[] args) {
new PanelTitles();
}
public PanelTitles() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TitlePane(), BorderLayout.NORTH);
frame.add(new JLabel("This is the content"));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TitlePane extends JPanel {
public TitlePane() {
setLayout(new BorderLayout());
setBorder(new CompoundBorder(new EmptyBorder(4, 4, 4, 4), new MatteBorder(0, 0, 1, 0, Color.BLACK)));
JLabel label = new JLabel("This is a title");
label.setFont(label.getFont().deriveFont(Font.BOLD));
add(label);
}
}
}

Inserting Images into a JTextPane Error

I asked about this before, but, I decided to start a new thread with a SCCE, it compiles sucessfully but it doesn't insert the image. Can anyone troubleshoot as to why it does this? Thanks, Chris.
Here is the full code:
package mathnotesplus;
import java.awt.Dimension;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.text.*;
/**
*
* #author ChrisCates
*/
public class MathNotesPlus extends JFrame implements TreeSelectionListener {
/**
* #param args the command line arguments
*/
public MathNotesPlus() {
setTitle("Math Notes Plus");
setSize(800, 600);
initUI();
}
JPanel panel;
JTextPane textpane;
JTree navigation;
StyledDocument document;
public void initUI(){
//The panel.
panel = new JPanel();
//Textpane and JTree
textpane = new JTextPane();
navigation = new JTree();
navigation.addTreeSelectionListener(this);
//Preferred Resolution Size
navigation.setPreferredSize(new Dimension(100, 600));
textpane.setPreferredSize(new Dimension(700, 600));
//Insertion of image into the document.
try {
document = (StyledDocument)textpane.getDocument();
Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon("sigma.png"));
document.insertString(document.getLength(), "ignored text", style);
} catch (BadLocationException e){
System.err.println("ERROR");
}
//Putting everything into the program.
panel.add(navigation);
panel.add(textpane);
add(panel);
pack();
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MathNotesPlus app = new MathNotesPlus();
app.setVisible(true);
}
});
}
#Override
public void valueChanged(TreeSelectionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Base on this working example (a very close variant of your code) that works, I can only guess that your code is failing because the image is not being found.
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.text.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class MathNotesPlus extends JFrame {
JPanel panel;
JTextPane textpane;
StyledDocument document;
public MathNotesPlus() {
setTitle("Math Notes Plus");
setSize(800, 600);
initUI();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void initUI(){
//The panel.
panel = new JPanel();
//Textpane
textpane = new JTextPane();
textpane.setPreferredSize(new Dimension(700, 600));
//Insertion of image into the document.
try {
Image image = ImageIO.read(new URL(
"http://pscode.org/media/stromlo1.jpg"));
document = (StyledDocument)textpane.getDocument();
Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
} catch (Exception e){
e.printStackTrace();
}
//Putting everything into the program.
panel.add(textpane);
add(panel);
pack();
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MathNotesPlus app = new MathNotesPlus();
app.setVisible(true);
}
});
}
}

Categories

Resources