Java swing error ‘void’ type ‘is not allowed here

See the English answer > "'void 'type not allowed here" error (Java) 6

Code:

public void create(JPanel jp){
    jp.add(new JButton().setPreferredSize(new Dimension(40,40)));        
}

But when I use No Setpreferredsize (new dimension (40,40)) works normally

Work code

public void create(JPanel jp){
    jp.add(new JButton());
}

Solution

Setpreferredsize "returns" a void, so it cannot be passed as a parameter to add You must break down the code and break it into several statements:

public void create(JPanel jp){
    JButton myButton = new JButton();
    myButton.setPreferredSize(new Dimension(40,40));
    jp.add(myButton);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>