如何添加图片。我想在线上方添加图像而不是在整个jframe上如何在jframe swing中执行此操作。我试过但我可以在整个屏幕上设置背景图像。我需要在线上方设置背景。
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);
}
}
答案 0 :(得分:2)
要添加图片,您可以在g.drawImage(Image img, int x, int y, ImageObserver observer)
函数中使用paint()
。
或
制作JLabel
并向其添加image icon
答案 1 :(得分:1)
//全球宣言
private BufferedImage bi;
//某处
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);
答案 2 :(得分:0)
class MyImagePanel extends JPanel{
BufferedImage image;
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null){
g.drawImage(image, 0, 0, this);
}
}
}