Refer to this link to see the image:
https://www.dropbox.com/s/byeah81vg1cck5m/output.jpg
I want a panel like the picture above.
hello , i am a beginner on Java , i would like to know how is it possible to add this icon within a panel with the scrollbar . I have tried with JLabel, here is my code:
JPanel panel = new JPanel();
panel.setLayout(null);
JScrollPane txtstmtPane = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
ImageIcon icon=new ImageIcon ( "icon/filter.jpg" );
JLabel label = new JLabel();
label.setIcon(icon);
label.setBounds(600, 600, 40, 30);
panel.add(label);
txtstmtPane.setViewportView(panel);
add(txtstmtPane);
See this:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
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.*;
public class ImagePanel extends JPanel{
private BufferedImage bi;
public ImagePanel() {
try {
bi = ImageIO.read(new File("Your Image Path"));
} catch (IOException ex) {
Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex);
}
final JPanel panel = new JPanel(){
#Override
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.drawImage(bi, 0, 0, getWidth(), getHeight(), null);
g2.dispose();
}
#Override
public Dimension getPreferredSize(){
return new Dimension(bi.getWidth()/2, bi.getHeight()/2);
//return new Dimension(200, 200);
}
};
add(panel);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ImagePanel imgPanel=new ImagePanel();
JOptionPane.showMessageDialog(
null, imgPanel, "Image Panel", JOptionPane.PLAIN_MESSAGE);
}
});
}
}
Output
Tips
Don't use NULL layout (as #camickr suggested)
Use proper Layout Manager
Using this code I don't thing you need ScrollPane
Don't use null layouts!!!
A scrollpane will only work when the preferred size of the component added to the viewport is greater than the size of the viewport.
You can just add the label directly to the scrollpane, you don't need to add it to the panel first.
Related
Are any methods available to set an image as background in a JFrame?
There is no built-in method, but there are several ways to do it. The most straightforward way that I can think of at the moment is:
Create a subclass of JComponent.
Override the paintComponent(Graphics g) method to paint the image that you want to display.
Set the content pane of the JFrame to be this subclass.
Some sample code:
class ImagePanel extends JComponent {
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
// elsewhere
BufferedImage myImage = ImageIO.read(...);
JFrame myJFrame = new JFrame("Image pane");
myJFrame.setContentPane(new ImagePanel(myImage));
Note that this code does not handle resizing the image to fit the JFrame, if that's what you wanted.
Try this :
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame();
try {
f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
} catch (IOException e) {
e.printStackTrace();
}
f.pack();
f.setVisible(true);
}
}
By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.
You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
JButton b1;
JLabel l1;
public BackgroundImageJFrame() {
setSize(400,400);
setVisible(true);
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful_design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
}
public static void main(String args[])
{
new BackgroundImageJFrame();
}
}
check out the below link
http://java-demos.blogspot.in/2012/09/setting-background-image-in-jframe.html
I want to create a java Application like a widget. Here is my code below
package newpackage;
public class MainFrame extends JFrame {
JLabel imageLabel = new JLabel();
public MainFrame() {
try {
this.setUndecorated(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(360, 360));
ImageIcon ii = new ImageIcon(this.getClass().getResource("imageexcel.gif"));
imageLabel.setIcon(ii);
add(imageLabel, java.awt.BorderLayout.CENTER);
this.setVisible(true);
Shape shape=new Ellipse2D.Float(0,0,360,360);
AWTUtilities.setWindowShape(this, shape);
AWTUtilities.setWindowOpaque(this, false);
imageLabel.add(new JButton("START"));
} catch (Exception exception) {
exception.printStackTrace();
}
}
public static void main(String[] args) {
new MainFrame();
}
}
In the above code, I have done the following:
Created a Frame
Removed the Title Bar
Added the Background using JLabel
Changed the shape of window as circle according to the shape of image
Now I would like to add some components in to it and perform some action with them but no component is visible after adding.
I have tried adding to Frame as well as JLabel and no use from either.
This is the image i used for background
Please help me to proceed further....
Thanking you
JLabels use null layouts by default, and so your button will default to size 0,0. Try giving it a decent layout manager, even FlowLayout would likely work. Another solution is to keep the null layout and set the sizes and positions of added components, but this route is a dangerous route and one I don't recommend.
Actually a GridBagLayout works nice to center the components. Also add all components before calling setVisible(true):
imageLabel.setLayout(new GridBagLayout());
this.setUndecorated(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(360, 360));
ImageIcon ii = new ImageIcon(this.getClass().getResource("imageexcel.gif"));
imageLabel.setIcon(ii);
add(imageLabel, java.awt.BorderLayout.CENTER);
imageLabel.add(new JButton("START"));
this.setVisible(true);
or better?
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Shape;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.net.URL;
import javax.swing.*;
import com.sun.awt.AWTUtilities;
#SuppressWarnings("serial")
public class MainPanelOvalFrame extends JPanel {
private static final String RESOURCE_PATH = "imageexcel.gif";
private Window window;
private Image img;
public MainPanelOvalFrame(Window window, Image image) {
this.window = window;
this.img = image;
setLayout(new GridBagLayout());
add(new JButton(new StartAction("Start", KeyEvent.VK_S)));
int w = image.getWidth(this);
int h = image.getHeight(this);
Shape shape = new Ellipse2D.Float(0, 0, w, h);
AWTUtilities.setWindowShape(window, shape);
AWTUtilities.setWindowOpaque(window, false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || img == null) {
return super.getPreferredSize();
}
int w = img.getWidth(this);
int h = img.getHeight(this);
return new Dimension(w, h);
}
private class StartAction extends AbstractAction {
public StartAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
window.dispose();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.setUndecorated(true);
URL imgUrl = MainPanelOvalFrame.class.getResource(RESOURCE_PATH);
Image image = new ImageIcon(imgUrl).getImage();
MainPanelOvalFrame mainPanel = new MainPanelOvalFrame(frame, image);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You just need to set a Layout manager for imageLabel ,or use null as the Layout manager, then set the size and location of the JButton manually.
to use Layout Manager
imageLabel.setIcon(ii);
imageLabel.setLayout(new FlowLayout());
imageLabel.add(new JButton("START"));
//need to setLayout and add JButton before setVisible(true)
add(imageLabel, java.awt.BorderLayout.CENTER);
this.setVisible(true);
to use null layout
JButton j=new JButton("START");
j.setSize(100,50);
j.setLocation(imageLabel.getWidth()/2-j.getWidth()/2, imageLabel.getHeight()/2-j.getHeight()/2);
//then add Button into imageLabel
imageLabel.add(j);
Layout manager is usually recommended because it can fit different environment.
I've been searching on way's to replace a JTextField with an Image & nothing comes up. Is it possible to add a jtextfield onto an image or replace on with an image?
I'm using a JPanel & I am trying to put the JtextField inside the image below:
There are several ways this might be achieved...
The simplest might be to use a JLabel, set it's layout manager to something BorderLayout and simply add the text field to it...
JTextField field = new JTextField();
field.setOpaque(false);
JLabel label = new JLabel();
label.setIcon(...);
label.setLayout(new BorderLayout());
label.add(field);
For example...
This will generate...
If you prefer the text field to be transparent, you could add field.setBackground(new Color(0, 0, 0, 0));, which generates...
And if you don't want the border, add field.setBorder(null);, which generates...
Updated with another example...
Or perhaps you'd prefer a self contained class...
This is a little tricky, because paintComponent not only paints the background, but the text, you need some way to insert the background under the text. To this end, I don't actually call super.paintComponent, but instead, we cheat, and call getUI().paint directly. This ensures that the text of the field is painted, but allows us to paint our own background before it...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class BackgroundTextField {
public static void main(String[] args) {
new BackgroundTextField();
}
public BackgroundTextField() {
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 TextFieldBackground());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TextFieldBackground extends JTextField {
private BufferedImage img;
public TextFieldBackground() {
setColumns(10);
setOpaque(false);
setBorder(new EmptyBorder(2, 2, 2, 2));
setBackground(new Color(0, 0, 0, 0));
try {
img = ImageIO.read(getClass().getResource("/y9yBe.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(img, 0, 0, this);
getUI().paint(g2d, this);
g2d.dispose();
}
}
}
There are limitations to this, the field should never be bigger then the image, as the image is not repeated, but I'm sure you could use a for-loop to stitch a bunch of images together...
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.
In the below example, how can I get the JPanel to take up all of the JFrame? I set the preferred size to 800x420 but it only actually fills 792x391.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BSTest extends JFrame {
BufferStrategy bs;
DrawPanel panel = new DrawPanel();
public BSTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout()); // edited line
setVisible(true);
setSize(800,420);
setLocationRelativeTo(null);
setIgnoreRepaint(true);
createBufferStrategy(2);
bs = getBufferStrategy();
panel.setIgnoreRepaint(true);
panel.setPreferredSize(new Dimension(800,420));
add(panel, BorderLayout.CENTER); // edited line
panel.drawStuff();
}
public class DrawPanel extends JPanel {
public void drawStuff() {
while(true) {
try {
Graphics2D g = (Graphics2D)bs.getDrawGraphics();
g.setColor(Color.BLACK);
System.out.println("W:"+getSize().width+", H:"+getSize().height);
g.fillRect(0,0,getSize().width,getSize().height);
bs.show();
g.dispose();
Thread.sleep(20);
} catch (Exception e) { System.exit(0); }
}
}
}
public static void main(String[] args) {
BSTest bst = new BSTest();
}
}
If you are having only one panel in frame and nothing else then try this:
Set BorderLayout in frame.
Add panel in frame with BorderLayout.CENTER
May be this is happening because of while loop in JPanel.(Not sure why? finding actual reason. Will update when find it.) If you replace it with paintComponent(g) method all works fine:
public BSTest() {
//--- your code as it is
add(panel, BorderLayout.CENTER);
//-- removed panel.drawStuff();
}
public class DrawPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
System.out.println("W:" + getSize().width + ", H:" + getSize().height);
g2d.fillRect(0, 0, getSize().width, getSize().height);
}
}
//your code as it is.
Here's an alternative using pack instead.
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PackExample extends JFrame {
public PackExample(){
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(800,600));
panel.setBackground(Color.green);
add(panel);
pack();
setVisible(true);
}
public static void main(String[] args){
new PackExample();
}
}
This took me forever to figure out but its actually the simplest code ever.
Just create a parent panel and pass GridLayout then add your child panel like this.
JPanel parentPanel= new JPanel(new GridLyout());
JPanel childPanel= new JPanel();
parentPanel.add(childPanel);
If you want to fill the JFrame with the whole of JPanel you need to setUndecorated to true i.e. frame.setUndecorated(true);. But now you have to worry about your MAXIMIZE< MINIMIZE, and CLOSE Buttons, towards the top right side(Windows Operating System)