【问题标题】:Why is this printing out 2 JButtons为什么这会打印出 2 个 JButton
【发布时间】:2021-12-08 21:14:35
【问题描述】:
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 个 JButton?我真的不知道这是如何工作的,很高兴知道。这个想法是从字面上打印出一张图片和一个按钮,我什至无法让它工作哈哈。主要问题是我不知道如何使用绘画组件,因为我对 java 还很陌生。

【问题讨论】:

  • 埃加德!您在您的paintComponent 方法中添加按钮,不要那样做。只是画画。
  • 你想让你的JPanel 有一个background image 吗?或者你想让你的JButton 有一个icon 吗?

标签: java swing jbutton


【解决方案1】:
  • 首先不要使用 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 提供的链接,因为您会省去不少麻烦。

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多