为什么要打印2个jbutton ?


import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TowerDefence extends JPanel {

public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon EasyImage = new ImageIcon("WelcomeImage.png");
Image Image = EasyImage.getImage();
Image newimg = Image.getScaledInstance(1000, 700,  java.awt.Image.SCALE_SMOOTH);
EasyImage = new ImageIcon(newimg);
EasyImage.paintIcon(this, g, 0, 0);
JButton button = new JButton("Click Button");
button.setBounds(100, 100, 100, 100);
super.add(button);
}
public static void main(String[] args) throws Exception {
TowerDefence T = new TowerDefence();
JFrame frame = new JFrame("Sam");
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setBounds(150, 20, 1000, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(T);
}
}

为什么打印出2个JButtons?我真的不知道这是怎么回事,如果能知道就好了。这个想法是打印出一张图片和一个按钮,我甚至不能让它工作,哈哈。主要的问题是我不知道如何使用油漆组件,因为我是java的新手。

  • 首先不要使用setBounds,除非你有一个空类型的布局。
  • 第二,不要使用null布局,除非你想处理布局的所有内容。
ImageIcon easyImage;
public TowerDefense(){
EasyImage = new ImageIcon("WelcomeImage.png");
Image Image = EasyImage.getImage();
Image newimg = Image.getScaledInstance(1000, 700,  java.awt.Image.SCALE_SMOOTH);
JButton button = new JButton("Click Button");
add(button);
}
public void paintComponent(Graphics g) 
{
super.paintComponent(g);
EasyImage.paintIcon(this, g, 0, 0);
}

我重新安排了代码,试图将绘画和初始化分开。我强烈建议你看看Abra提供的链接,因为你会省去很多麻烦。