import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.JFrame; import java.util.function.Consumer; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.ArrayList; import java.util.Arrays; import static java.util.Arrays.asList; public class HelloPanel extends JPanel { int whichaction; String somemessage=""; JLabel displayLabel; public static void main( String[] args ) { JFrame helloFrame = new JFrame( "Hello, World!" ); helloFrame.getContentPane().add( new HelloPanel()); helloFrame.setSize( 300, 150 ); helloFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); helloFrame.setVisible( true ); HelloPanel hp=new HelloPanel(); } public HelloPanel() { setLayout( new BorderLayout() ); List<Consumer<String>> aa=new ArrayList<Consumer<String>>(); aa.add( (theaddedmessage) -> {displayLabel.setText("Hello World !");}); aa.add( (theaddedmessage) -> {displayLabel.setText("Hello World "+theaddedmessage);}); JPanel ButtonPanel = new JPanel(); JButton theButton = new JButton( "Press Me." ); whichaction=0; theButton.addActionListener((e)->{aa.get(whichaction).accept(somemessage);}); whichaction=1; somemessage="is changed!"; ButtonPanel.add( theButton ); add( ButtonPanel, BorderLayout.NORTH ); displayLabel = new JLabel( "Press the Button", JLabel.CENTER ); displayLabel.setOpaque( true ); add( displayLabel, BorderLayout.CENTER ); } }