I have a JButton which I want to create a new JButton with when it is pressed I have added an ActionListener that looks like this, but it doesn't add another JButton.
public void actionPerformed(ActionEvent e){
Object command = e.getSource();
if(command.equals(play)){
ImageIcon i1 = new ImageIcon("NewGame.png");
width = i1.getIconWidth();
height = i1.getIconWidth();
newGame = new JButton(i1);
newGame.setBorderPainted(false);
newGame.setContentAreaFilled(false);
newGame.setSize(width, height);
newGame.setLocation(600,100);
add(newGame);
System.out.println("It Works");
}
}
How would I make it so that when I press the already existing JButton this one will be added?
Make sure to revalidate
and repaint
after adding the button
revalidate();
repaint();
From the use of setSize
and setLocation
, it appears you are using a absolute positioning or null
layout. Use a layout manager.
添加后必须调用repaint()
。
如果没有异常,则需要刷新或重新粉刷容器,该容器将使新按钮变旧。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.