How to add image . i want to add image only above line not on whole jframe how can i do this in jframe swing. i tried but i ma able to set background image on whole screen.i need to set an background only above line.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import javax.swing.*;
import java.sql.*;
public class Demo1 extends JFrame
{
public void paint(Graphics g) {
super.paint(g); // fixes the immediate problem.
Graphics2D g2 = (Graphics2D) g;
Line2D lin = new Line2D.Float(20, 150, 1350, 150);
g2.draw(lin);
}
public Demo1( )
{
{
getContentPane().setBackground(new java.awt.Color(240,255,255));
}
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container c = getContentPane();
c.setLayout( new FlowLayout() );
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
}
public static void main( String[] args )
{
Demo1 frame = new Demo1();
frame.setVisible(true);
}
}
And for adding a image you can use g.drawImage(Image img, int x, int y, ImageObserver observer)
in paint()
function.
or
Make a JLabel
and add image icon to it
//Global Declaration
private BufferedImage bi;
//SomeWhere
try {
bi = ImageIO.read(new File("C:/1.jpg"));//Write path of your image here
} catch (IOException ex) {
Logger.getLogger(ClassName.class.getName()).log(Level.SEVERE, null, ex);//Change ClassName to your class Name
}
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);
}
};
mainPanel.add(panel, BorderLayout.CENTER);
//Add other components to mainPanel
frm.add(mainPanel);
class MyImagePanel extends JPanel{
BufferedImage image;
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null){
g.drawImage(image, 0, 0, this);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.