mercredi 30 août 2017

Using If Statement to Alter a Label's Contents

I am very new to Java, and really enjoy coding. However, I, personally, have found it is much more difficult to really understand than certain other languages (like Visual Basic or Lua).

It is only through 3 or 4 straight days or searching up hundreds of different questions on Google pertaining to various aspects of Java and the NetBeans compiler that I've made it this far.

I explain more in my comments in the code below:

private JLabel label;
private JTextField field;

public CalcTest() {
  
  super("Experimentation");                 // This sets the title of the
                                           // program to "Experimentation"(?)
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  
  setPreferredSize(new Dimension(400, 90));
  ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13));
  setLayout(new FlowLayout());
  JButton btn = new JButton("Change");
  
  btn.setActionCommand("myButton"); // Need Confirmation: What exactly
  btn.addActionListener(this);     // do these two lines do? Please
                                  // explain like I am 5.
  
  label = new JLabel("Hello World");
  add(btn);
  add(label);
  
  pack();     // This makes it so that all components in the program
             // are at or above their preferred sizes(?)
  
  setLocationRelativeTo(null);
  setVisible(true);
  setResizable(false);
}
public void actionPerformed(ActionEvent e)
  // I am trying create a program where you click a button that will
 // change label back and forth from "Hello Universe" and "Hello World"

{

    // Another thread suggested creating a String
   // variable to store the contents of a label
  String text = label.getText();

  if (e.getActionCommand().equals("myButton"))
    // Need Confirmation: This basically says "If the button is clicked(?)..." 

  {
    if (text = ("Hello World")) {
      // However, the compiler states that String cannot be converted to boolean
      label.setText("Hello Universe");
    } else
        label.setText("Hello World");

  }

Aucun commentaire:

Enregistrer un commentaire