添加图片到JPanel,再将JPanel添加入JFrame?
importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;importjava.net.URL;public...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.URL;
public class Ball{
Ball(){
}
public static void main(String[]args){
JBallPanel jbp=new JBallPanel();
JFrame jf=new JFrame("Ball");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new GridLayout(2,1,0,0));
jf.add(jbp);
Toolkit t=jf.getToolkit();
Dimension d=t.getScreenSize();
jf.setBounds(d.width/4,d.height/4,(int)(d.width/2),d.height/2);
jf.setVisible(true);
}
}
class JBallPanel extends JPanel{ //创建四张图
JBallPanel(){
JImagePanel jip1=new JImagePanel(true);
JImagePanel jip2=new JImagePanel(true);
JImagePanel jip3=new JImagePanel(true);
JImagePanel jip4=new JImagePanel(true);
setBackground(Color.YELLOW);
setLayout(new FlowLayout());
add(jip1);
add(jip2);
add(jip3);
add(jip4);
}
}
class JImagePanel extends JPanel{ //创建带图片的面板
ImageIcon icon;
JImagePanel(boolean isRoll){
URL u=null;
if(isRoll){
u= getClass().getResource("img/bollStatic.png");
}
icon=new ImageIcon(u);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(icon.getImage(), 0, 0,this);
}
}
如上,由于在JFrame中还想加入别的东西,因此想把这几张图片统一放入一个JPanel中管理,可这样图片只显示出四个白色的小框,怎么解决? 展开
import java.awt.event.*;
import javax.swing.*;
import java.net.URL;
public class Ball{
Ball(){
}
public static void main(String[]args){
JBallPanel jbp=new JBallPanel();
JFrame jf=new JFrame("Ball");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new GridLayout(2,1,0,0));
jf.add(jbp);
Toolkit t=jf.getToolkit();
Dimension d=t.getScreenSize();
jf.setBounds(d.width/4,d.height/4,(int)(d.width/2),d.height/2);
jf.setVisible(true);
}
}
class JBallPanel extends JPanel{ //创建四张图
JBallPanel(){
JImagePanel jip1=new JImagePanel(true);
JImagePanel jip2=new JImagePanel(true);
JImagePanel jip3=new JImagePanel(true);
JImagePanel jip4=new JImagePanel(true);
setBackground(Color.YELLOW);
setLayout(new FlowLayout());
add(jip1);
add(jip2);
add(jip3);
add(jip4);
}
}
class JImagePanel extends JPanel{ //创建带图片的面板
ImageIcon icon;
JImagePanel(boolean isRoll){
URL u=null;
if(isRoll){
u= getClass().getResource("img/bollStatic.png");
}
icon=new ImageIcon(u);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(icon.getImage(), 0, 0,this);
}
}
如上,由于在JFrame中还想加入别的东西,因此想把这几张图片统一放入一个JPanel中管理,可这样图片只显示出四个白色的小框,怎么解决? 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询