Yuuki Rito
Yuuki Rito

Reputation: 17

how to connect multiple classes?

I am newbie in java

package assigment;

import java.awt.*;
import java.sql.*;
import javax.swing.*;

public class view extends JFrame {

    public static void main(String[] args) {
        new view();
    }

    public view(){
        JFrame f = new JFrame("WELCOME");
        f.setSize(400, 300);
        f.setVisible(true);
        f.setLocationRelativeTo(null);

        controller cl = new controller();

        JButton btnCompany = new JButton ("COMPANY");
        f.add(btnCompany);
        f.setLayout(null);
        btnCompany.setBounds(50, 50, 100, 50);
        btnCompany.addActionListener (cl);
    }
}

contoller class

package assigment;

import java.awt.event.*;
public class controller {

    public static void actioncompany(ActionEvent a,view view) {
        if (a.getSource() == view.btnCompany) {
            System.out.print ("test");
        }
    }
}

Problem:

  1. Cannot use controller class

  2. Cannot access btnCompany in controller class

Upvotes: 1

Views: 191

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

That code shouldn't even compile since there isn't a field, view.btnCompany. The btnCompany variable is local to the constructor and thus invisible everywhere else. Also, as MadProgrammer notes, your controller class (re-name it Controller) doesn't implement ActionListener and so cannot be used as an ActionListener.

I have other issues with your code:

  • Don't use null layout and absolute positioning.
  • Do abide by Java naming rules including starting class and interface names with an upper case letter so that others can more easily understand your code.
  • Yes, separate out your control from your view.
  • Most all fields should be private, and so view.BtnCompany shouldn't be visible, even if the field existed.
  • ActionListeners must implement the ActionListener interface or extend a class that implements the interface such as AbstractAction.

Upvotes: 4

Related Questions