Hello,
I have created a simple frame, and in it there are 3 panels.I have a button in the bottom panel, and when pressed should display the text "You pressed the button", in the mainPanel.However this is not working.Can anyone shed some light as to what I am doing wrong as everything looks in order to me.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.Random;
public class GUI extends JFrame implements ActionListener {
private JPanel buttonPanel;
private JPanel mainPanel;
private JButton press;
GUI(){
setTitle("Simple Frame");
setSize(649,480);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(createPane());
setVisible(true);
}
private Container createPane() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(Color.GREEN);
mainPanel.add(createButtonPanel(), BorderLayout.SOUTH);
return mainPanel;
}
public Container createButtonPanel() {
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
// Action listener added to button.
press = new JButton("Press me");
press.addActionListener(this);
buttonPanel.add(deal);
return buttonPanel;
}
// The actionPerformed method.
public void actionPerformed(ActionEvent e){
if(e.getSource() == deal) {
// add the text(JLabel) to the main panel, pane.
JLabel text = new JLabel("You pressed button!");
mainPanel.add(text);
//I have tried a variation of this without the following line uncommented out.
//setContentPane(createPane());
}
}
}