java中jpanel 点击按钮生成图片背景
展开全部
我随便写了一个,abc是包名:
public class Test extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
int a=0;
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel(){
ImageIcon backg_img=new ImageIcon(Test.class.getResource("/abc/backg.png"));
public void paintComponent(Graphics g)
{
if(a==1)
g.drawImage(backg_img.getImage(), 0, 0,this.getWidth(),this.getHeight(), this);
}
};
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton button = new JButton("New button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
a=1;
contentPane.updateUI();
}
});
button.setBounds(151, 107, 93, 23);
contentPane.add(button);
}
}
public class Test extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
int a=0;
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel(){
ImageIcon backg_img=new ImageIcon(Test.class.getResource("/abc/backg.png"));
public void paintComponent(Graphics g)
{
if(a==1)
g.drawImage(backg_img.getImage(), 0, 0,this.getWidth(),this.getHeight(), this);
}
};
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton button = new JButton("New button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
a=1;
contentPane.updateUI();
}
});
button.setBounds(151, 107, 93, 23);
contentPane.add(button);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询