简体   繁体   中英

access class members from main

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?

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 startBtn needs 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM