I’m building a much much larger program, and I’ve tried several methods (all of which work) but I’m liking this method currently, although I don’t know if certain aspects of it represent bad programming practice. The code used in this example is just to get the idea across without pasting the whole code.
This code (pasted below) creates a new ClassMain object with a label and a static method to edit the label. ClassEditor is instantiated from ClassMain, which returns a button.
Now here is where I want to know if it’s bad practice, I have an action on the button which, when clicked, calls the static method in ClassMain and sets the label to a random number. The reason I’m wondering whether it’s bad practice is because I don’t actually call the method from a direct instantiation of the ClassMain object, I just do: ClassMain.setLabel("");. And I’m not entirely sure what this is calling. I have one instantiation of ClassMain, but if I had multiple, would it still work? So how can I edit aspects of a created object through this way of doing it rather than using a reference variable? If I had multiple classes would it create issues?
Sorry if these questions are rambled, it’s hard to ask exactly. I’ve provided the code below so you can see what I’m on about.
PS: Relating to the issue of if it would be an issue of more than one object of ClassMain, I created another an both buttons in both windows only updated one label. Why is this? And does this mean it’s not bad practice if used for one instantiation but bad if used for more? I hope someone can help me out with these issues!
ClassMain:
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ClassMain extends JFrame {
private static JLabel l;
public static void main(String[] args) {
new ClassMain();
}
public ClassMain() {
super("This is my app");
setSize(450,80);
setLayout(new GridLayout(0,2));
l = new JLabel("Hi");
ClassEditor ce = new ClassEditor();
add(l);
add(ce.getButton());
setVisible(true);
}
public static void setLabel(String stringA) {
l.setText(stringA);
}
}
ClassEditor:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class ClassEditor implements ActionListener {
public ClassEditor() {
ClassMain.setLabel("Click the button for a random number!");
}
public JButton getButton() {
JButton b = new JButton("Click me!");
b.addActionListener(this);
return b;
}
public void actionPerformed(ActionEvent arg0) {
int i = (int) (Math.random()*10);
ClassMain.setLabel("Random Number: "+i);
}
}
Big thanks to anyone who can help me out, very much appreciated. Just trying to learn and understand good practices and why they work.
I probably wouldn’t use static metods and variables and simply rewrite it like this (I also changed names – a good practice is to have everything named in a way that everyone knows what does it mean):
ClassMain:
ClassEditor: