将ImageIcon添加到JButton使其消失

时间:2015-08-18 19:50:38

标签: java

BufferedImage buttonIcon = ImageIO.read(new File("res//Login Button.png"));
loginButton = new JButton(new ImageIcon(buttonIcon));

我一直在使用上面的代码尝试将图像添加到JButton,但按钮没有显示在框架上,并且我一直收到NullPointerException。这是创建按钮的实际代码:

JButton loginButton = new JButton("Login");
    loginButton.setFont(new Font("Franklin Gothic Demi Cond", Font.PLAIN, 20));
    loginButton.setBounds(212, 252, 211, 55);
    try {
        ImageIcon image = new ImageIcon(getClass().getResource("res/LoginButton.png"));
        loginButton = new JButton("", image);
        panel.add(loginButton);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    panel.add(loginButton);

2 个答案:

答案 0 :(得分:0)

您正在创建JButton的两个实例/覆盖First的Text以替换第二个。将您的代码更改为:

ng-bind

答案 1 :(得分:0)

JButton loginButton = null;   
try {
        ImageIcon image = new ImageIcon(getClass().getResource("res/LoginButton.png"));
        loginButton = new JButton("", image);
        panel.add(loginButton);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
            loginButton = new LoginButton("Login")(;
            loginButton.setFont(new Font("Franklin Gothic Demi Cond", Font.PLAIN, 20));
        }
    panel.add(loginButton);

调用loginButton.setBounds()可能没有效果 - 让布局管理器放置按钮。