【问题标题】:How do i add a .png to JButton [duplicate]如何将 .png 添加到 JButton [重复]
【发布时间】:2013-11-16 13:32:49
【问题描述】:

我正在开发一个程序的主菜单,我发现很难将 .png 文件应用到我的 JButton,这就是我到达的地方

public class Menu extends JFrame implements ActionListener {
public static void main(String[] args) {
    Color b = new Color(0,89,255);
    Color t = new Color(255,0,0);
    Color bttn = new Color (255,255,0);


    final JFrame frame = new JFrame ("Main Menu");
    frame.setVisible(true);
    frame.setSize(1000,750);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setLayout(null);
    frame.setBackground(b);


    JButton start = new JButton ("Start");
    start.setBounds(300, 300, 150, 75);
    start.setForeground(t);


    JButton exit = new JButton ("Exit");
    exit.setBounds(550, 300, 150, 75);
    exit.setBackground(bttn);
    exit.setForeground(t);

请留下任何答案,因为我想快点

【问题讨论】:

    标签: java image swing jframe jbutton


    【解决方案1】:
    myButton.setIcon(new ImageIcon("/path/to/image.png"));  
    

    是您在创建JButton 后做您想做的事情的方式。如果您想在创建JButton 时添加图像,则可以使用适当的构造函数。

    JButton myButton = new JButton("What The Heck?", new ImageIcon("/path/to/image.png"));  
    

    请不要使用null 布局。请改用LayoutManager

    【讨论】:

    • 我是否保留 start.setBounds(300, 300, 150, 75);
    • 这完全取决于你想如何布局你的JComponents。有时你需要LayoutManagers的组合
    • Do i keep start.setBounds(300, 300, 150, 75);,不,您不应该使用 setBounds。 Swing 旨在与布局管理器一起使用。
    猜你喜欢
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2017-07-23
    • 2023-03-05
    相关资源
    最近更新 更多