用JLabel作为背景,然后组件添加在JLabel上,就是把JLabel看作是跟JPanel同等级的容器,这样就没有你重绘时覆盖组件的问题了,给你个示例
package my.test.mainimport java.awt.BorderLayout
public class First extends JDialog {
private final JPanel contentPanel = new JPanel()
private JTextField textField
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
First dialog = new First()
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE)
dialog.setVisible(true)
} catch (Exception e) {
e.printStackTrace()
}
}
/**
* Create the dialog.
*/
public First() {
setBounds(100, 100, 450, 300)
getContentPane().setLayout(new BorderLayout())
contentPanel.setLayout(new GridLayout(1, 1))
getContentPane().add(contentPanel, BorderLayout.CENTER)
JLabel bgLb = new JLabel()
bgLb.setIcon(new ImageIcon("bg.jpg"))
bgLb.setHorizontalAlignment(SwingConstants.CENTER)
contentPanel.add(bgLb)
bgLb.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 50))
textField = new JTextField()
bgLb.add(textField)
textField.setColumns(10)
}
}
//重写JPanel的这个方法就可以了@Override
public void paintComponent(Graphics gs) {
Graphics2D g = (Graphics2D) gs
super.paintComponent(g)
//画背景图片
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource(imgPath))
g.drawImage(image, 0, 0,width,height, this)
}
一个完整的代码:
package testimport java.awt.Graphics
import java.awt.Image
import java.net.URL
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JPanel
//为窗口添加背景图片
public class JFrameBackground {
private JFrame frame = new JFrame("带背景图片的JFrame")
private JPanel imagePanel
private ImageIcon backgroundimg
public JFrameBackground() {
imagePanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g)
URL location = this.getClass().getResource("grapes.gif")
backgroundimg = new ImageIcon(location)
Image img = backgroundimg.getImage()
g.drawImage(img, 0, 0, backgroundimg.getIconWidth(),
backgroundimg.getIconHeight(),
backgroundimg.getImageObserver())
frame.setSize(backgroundimg.getIconWidth(),
backgroundimg.getIconHeight())
}
}
frame.add(imagePanel)
frame.setVisible(true)
frame.pack()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
public static void main(String[] args) {
new JFrameBackground()
}
}
这是运行的一个截图:
参考网址:
http://www.linuxidc.com/Linux/2011-08/41689.htm 两种设置背景的方法
http://blog.csdn.net/one_and_only4711/article/details/6594770 动态改变背景大小
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)