i'm working with swing builder in java, the form:
but I can't access the components from main:
how can I get access to the form components?
access class members from main
202 Views Asked by roni At
2
There are 2 best solutions below
0
On
This is how I solved it
public class firstSwingForm {
private JPanel config;
private JTextField startTxt;
private JTextField dogTextField;
private JPanel mainPanel;
private JTextField a5TextField;
private JButton startBtn;
private static firstSwingForm instance;
public static void main(String args[]) {
JFrame frame = new JFrame("App");
instance = new firstSwingForm();
frame.setContentPane(instance.mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
instance.startBtn.setText("text can be set");
The issue is that your
private JButton startBtnneeds to be declared static in order to be accessed within the main method:private static JButton startBtn;You should also instantiate it as a new object within the main before calling anything on it:
startBtn = new JButton(...);It's also worth noting, by convention, your class name should be
FirstSwingForm, and think through whether or not those instance variables will be used elsewhere or if they can be defined within main.