Variablen non-static variable cannot be referenced from a static content

aykay90

Mitglied
Hallo liebe Forenmitglieder

Nach langem Ausprobieren, bin ich nun am Ende mit meinem Latein (welches leider nicht besonders gross ist, wenn es um OOP geht).
Konkret ist mein Problem: Ich möchte aus einer Klasse, auf eine Methode einer anderen Klasse zugreifen. In dieser Methode soll dann auf eine Instanz des "GpioController" der pi4j Bibliothek etwas geschrieben werden. Nur leider kann ich diese Instanz nicht statisch machen.
Hat von euch jemand eine Idde oder einen Lösungsansatz, der funktionieren könnte?
Das Projekt habe ich als Anhang angefügt und hier noch den Code der beiden Klassen:

Java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gh_beta2;

import com.pi4j.io.i2c.I2CFactory;
import java.awt.Color;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Administrator
*/
public class JFrame extends javax.swing.JFrame {

    /**
     * Creates new form JFrame
     * @throws com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException
     * @throws java.io.IOException
     */
    public JFrame() throws I2CFactory.UnsupportedBusNumberException, IOException {
        initComponents();
      

  
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton_DO_0 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton_DO_0.setText("OFF");
        jButton_DO_0.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DO_0ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(102, 102, 102)
                .addComponent(jButton_DO_0, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE)
                .addGap(88, 88, 88))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(85, 85, 85)
                .addComponent(jButton_DO_0)
                .addContainerGap(106, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(67, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(46, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                      

    private void jButton_DO_0ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        if("OFF".equals(jButton_DO_0.getText())){
            jButton_DO_0.setText("ON");
            jButton_DO_0.setBackground(Color.green);
            IO.setDO(0, "high");
        }// end if
        else{
            jButton_DO_0.setText("OFF");
            jButton_DO_0.setBackground(null);
            IO.setDO(0, "low");
        }// end else
    }                                          

    /**
     * @param args the command line arguments
     * @throws java.lang.InterruptedException
     * @throws java.lang.reflect.InvocationTargetException
     * @throws com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException
     * @throws java.io.IOException
     */


  
    public static void main(String args[]) throws InterruptedException, InvocationTargetException, I2CFactory.UnsupportedBusNumberException, IOException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeAndWait(() -> {
            try {
                new JFrame().setVisible(true);
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
      

        IO io = new IO();
      
    }

    // Variables declaration - do not modify                   
    public static javax.swing.JButton jButton_DO_0;
    public javax.swing.JPanel jPanel1;
    // End of variables declaration                 
}

Java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gh_beta2;


import com.pi4j.gpio.extension.mcp.MCP23008GpioProvider;
import com.pi4j.gpio.extension.mcp.MCP23008Pin;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CFactory;
import java.io.IOException;

/**
*
* @author Administrator
*/
class IO {
  
    public IO() throws I2CFactory.UnsupportedBusNumberException, IOException{
 
}// end constuctor
  
        GpioController gpio = GpioFactory.getInstance();
      
        final MCP23008GpioProvider DO_8Bit = new MCP23008GpioProvider(I2CBus.BUS_1, 0x21);
      
        // provision gpio output pins and make sure they are all LOW at startup
        GpioPinDigitalOutput DO[] = {
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_00, "DO_0", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_01, "DO_1", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_02, "DO_2", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_03, "DO_3", PinState.LOW),      
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_04, "DO_4", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_05, "DO_5", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_06, "DO_6", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_07, "DO_7", PinState.LOW)
          };
  
        static void setDO(int DO_x, String state) {
      
        int DO_x_intern = DO_x;
        String state_intern = state;
      
        if(DO_x_intern == 0 & "high".equals(state_intern)){
            gpio.setState(PinState.HIGH, DO[0]);
        }// end if
        if(DO_x_intern == 0 & "low".equals(state_intern)){
            gpio.setState(PinState.LOW, DO[0]);
        }// end if  
      
        if(DO_x_intern == 1 & "high".equals(state_intern)){
            gpio.setState(PinState.HIGH, DO[1]);
        }// end if
        if(DO_x_intern == 1 & "low".equals(state_intern)){
            gpio.setState(PinState.LOW, DO[1]);
        }// end if
      
      
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }  
      
}// end class

Döchte ich mir dieser Zeile
Java:
IO.setDO(0, "high");
die Methode "setDO(...)" aufrufen, was allerdings nicht geht, da die Instanz "gpio" nicht statisch ist. Gibt es eine andere Möglichkeit das hinzubekommen?

Einen hilfreichen Ansatz wäre erfreulich.
 

Anhänge

  • GH_beta2.zip
    18,8 KB · Aufrufe: 0

aykay90

Mitglied
Danke für den Tip. das funktioniert eigentlich gut, nur ist es so, dass ich jetzt mehrere Digitale Ausgänge habe, welche ich unabhängig voneinander Ein- und Ausschalten möchte.
Wenn ich nun die Methode nicht statisch mache, muss ich die Instanz "gpio" jeweils in der Methode machen, was allerdings dazu führt, dass immer nur ein DO gesetzt und gelöscht werden kann. Falls nun also schon ein DO high ist, wird dieser gelöscht.

Zur Zeit sieht es so aus:
Java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gh_beta2;

import com.pi4j.io.i2c.I2CFactory;
import java.awt.Color;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Administrator
*/
public class JFrame extends javax.swing.JFrame {

    /**
     * Creates new form JFrame
     * @throws com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException
     * @throws java.io.IOException
     */
    public JFrame() throws I2CFactory.UnsupportedBusNumberException, IOException {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton_DO_0 = new javax.swing.JButton();
        jButton_DO_1 = new javax.swing.JButton();
        jButton_DO_2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton_DO_0.setText("OFF");
        jButton_DO_0.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DO_0ActionPerformed(evt);
            }
        });

        jButton_DO_1.setText("OFF");
        jButton_DO_1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DO_1ActionPerformed(evt);
            }
        });

        jButton_DO_2.setText("OFF");
        jButton_DO_2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DO_2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton_DO_1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton_DO_0, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton_DO_2, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton_DO_0)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_DO_1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_DO_2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(98, 98, 98)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(184, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(51, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(44, 44, 44))
        );

        pack();
    }// </editor-fold>                       

    private void jButton_DO_0ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if("OFF".equals(jButton_DO_0.getText())){
            jButton_DO_0.setText("ON");
            jButton_DO_0.setBackground(Color.green);
            try {
                InOut.setDO(0, "high");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end if
        else{
            jButton_DO_0.setText("OFF");
            jButton_DO_0.setBackground(null);
            try {
                InOut.setDO(0, "low");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end else
    }                                           

    private void jButton_DO_1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if("OFF".equals(jButton_DO_1.getText())){
            jButton_DO_1.setText("ON");
            jButton_DO_1.setBackground(Color.green);
            try {
                InOut.setDO(1, "high");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end if
        else{
            jButton_DO_1.setText("OFF");
            jButton_DO_1.setBackground(null);
            try {
                InOut.setDO(1, "low");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end else
    }                                           

    private void jButton_DO_2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if("OFF".equals(jButton_DO_2.getText())){
            jButton_DO_2.setText("ON");
            jButton_DO_2.setBackground(Color.green);
            try {
                InOut.setDO(2, "high");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end if
        else{
            jButton_DO_2.setText("OFF");
            jButton_DO_2.setBackground(null);
            try {
                InOut.setDO(2, "low");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end else
    }                                           

    /**
     * @param args the command line arguments
     * @throws java.lang.InterruptedException
     * @throws java.lang.reflect.InvocationTargetException
     * @throws com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException
     * @throws java.io.IOException
     */


   
    public static void main(String args[]) throws InterruptedException, InvocationTargetException, I2CFactory.UnsupportedBusNumberException, IOException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeAndWait(() -> {
            try {
                new JFrame().setVisible(true);
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
       

       //IO io = new InOut();
       
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton_DO_0;
    private javax.swing.JButton jButton_DO_1;
    private javax.swing.JButton jButton_DO_2;
    public javax.swing.JPanel jPanel1;
    // End of variables declaration                  
}

Java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gh_beta2;


import com.pi4j.gpio.extension.mcp.MCP23008GpioProvider;
import com.pi4j.gpio.extension.mcp.MCP23008Pin;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CFactory;
import java.io.IOException;

/**
*
* @author Administrator
*/
class InOut {

   
    public InOut() throws I2CFactory.UnsupportedBusNumberException, IOException{
       
    }
   

   
    static void setDO(int DO_x, String state) throws I2CFactory.UnsupportedBusNumberException, IOException {
  
        final MCP23008GpioProvider DO_8Bit = new MCP23008GpioProvider(I2CBus.BUS_1, 0x21);
        GpioController gpio = GpioFactory.getInstance();


        // provision gpio output pins and make sure they are all LOW at startup
        GpioPinDigitalOutput DO[] = {
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_00, "DO_0", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_01, "DO_1", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_02, "DO_2", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_03, "DO_3", PinState.LOW),       
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_04, "DO_4", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_05, "DO_5", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_06, "DO_6", PinState.LOW),
            gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_07, "DO_7", PinState.LOW)
        };
        
        int DO_x_intern = DO_x;
        String state_intern = state;
      
       
        if(DO_x_intern == 0 & "high".equals(state_intern)){
            gpio.setState(PinState.HIGH, DO[0]);
        }// end if
        if(DO_x_intern == 0 & "low".equals(state_intern)){
            gpio.setState(PinState.LOW, DO[0]);
        }// end if   
       
        if(DO_x_intern == 1 & "high".equals(state_intern)){
            gpio.setState(PinState.HIGH, DO[1]);
        }// end if
        if(DO_x_intern == 1 & "low".equals(state_intern)){
            gpio.setState(PinState.LOW, DO[1]);
        }// end if
       

    }   
       
}// end class

Das funktioniert, allerdings wird der DO Port bei jedem Zugriff gelöscht und es kann nur 1 Bit aktiv sein.
 

aykay90

Mitglied
EDIT: Ich habs geschafft! Weiss zwar nicht ob das eine elegante Lösung ist, oder diese im Sinne von Java, aber es funktioniert:

Java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gh_beta2;

import com.pi4j.io.i2c.I2CFactory;
import java.awt.Color;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Administrator
*/
public class JFrame extends javax.swing.JFrame {

    /**
     * Creates new form JFrame
     * @throws com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException
     * @throws java.io.IOException
     */
    public JFrame() throws I2CFactory.UnsupportedBusNumberException, IOException {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton_DO_0 = new javax.swing.JButton();
        jButton_DO_1 = new javax.swing.JButton();
        jButton_DO_2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton_DO_0.setText("OFF");
        jButton_DO_0.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DO_0ActionPerformed(evt);
            }
        });

        jButton_DO_1.setText("OFF");
        jButton_DO_1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DO_1ActionPerformed(evt);
            }
        });

        jButton_DO_2.setText("OFF");
        jButton_DO_2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DO_2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton_DO_1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton_DO_0, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton_DO_2, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton_DO_0)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_DO_1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_DO_2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(98, 98, 98)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(184, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(51, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(44, 44, 44))
        );

        pack();
    }// </editor-fold>                       

    private void jButton_DO_0ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if("OFF".equals(jButton_DO_0.getText())){
            jButton_DO_0.setText("ON");
            jButton_DO_0.setBackground(Color.green);
            try {
                InOut.DO_0("high");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end if
        else{
            jButton_DO_0.setText("OFF");
            jButton_DO_0.setBackground(null);
            try {
                InOut.DO_0("low");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end else
    }                                           

    private void jButton_DO_1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if("OFF".equals(jButton_DO_1.getText())){
            jButton_DO_1.setText("ON");
            jButton_DO_1.setBackground(Color.green);
            try {
                InOut.DO_1("high");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end if
        else{
            jButton_DO_1.setText("OFF");
            jButton_DO_1.setBackground(null);
            try {
                InOut.DO_1("low");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end else
    }                                           

    private void jButton_DO_2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if("OFF".equals(jButton_DO_2.getText())){
            jButton_DO_2.setText("ON");
            jButton_DO_2.setBackground(Color.green);
            try {
                InOut.DO_2("high");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end if
        else{
            jButton_DO_2.setText("OFF");
            jButton_DO_2.setBackground(null);
            try {
                InOut.DO_2("low");
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }// end else
    }                                           

    /**
     * @param args the command line arguments
     * @throws java.lang.InterruptedException
     * @throws java.lang.reflect.InvocationTargetException
     * @throws com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException
     * @throws java.io.IOException
     */


   
    public static void main(String args[]) throws InterruptedException, InvocationTargetException, I2CFactory.UnsupportedBusNumberException, IOException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeAndWait(() -> {
            try {
                new JFrame().setVisible(true);
            } catch (I2CFactory.UnsupportedBusNumberException | IOException ex) {
                Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
       

       //IO io = new InOut();
       
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton_DO_0;
    private javax.swing.JButton jButton_DO_1;
    private javax.swing.JButton jButton_DO_2;
    public javax.swing.JPanel jPanel1;
    // End of variables declaration                  
}

Java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gh_beta2;


import com.pi4j.gpio.extension.mcp.MCP23008GpioProvider;
import com.pi4j.gpio.extension.mcp.MCP23008Pin;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CFactory;
import java.io.IOException;

/**
*
* @author Administrator
*/
class InOut {

   
    public InOut() throws I2CFactory.UnsupportedBusNumberException, IOException{
       
    }
   

    static GpioController gpio = GpioFactory.getInstance();
           
           
    static void DO_0(String state) throws I2CFactory.UnsupportedBusNumberException, IOException {
  
        String state_intern = state;
       
        final MCP23008GpioProvider DO_8Bit = new MCP23008GpioProvider(I2CBus.BUS_1, 0x21);
        GpioPinDigitalOutput DO_0 = gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_00, "DO_0", PinState.LOW);

        if("high".equals(state_intern)){
            gpio.setState(PinState.HIGH, DO_0);
        }// end if
        if("low".equals(state_intern)){
            gpio.setState(PinState.LOW, DO_0);
        }// end if   
    }// end DO_0
   
    static void DO_1(String state) throws I2CFactory.UnsupportedBusNumberException, IOException {
  
        String state_intern = state;
        final MCP23008GpioProvider DO_8Bit = new MCP23008GpioProvider(I2CBus.BUS_1, 0x21);
       
        GpioPinDigitalOutput DO_1 = gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_01, "DO_1", PinState.LOW);

        if("high".equals(state_intern)){
            gpio.setState(PinState.HIGH, DO_1);
        }// end if
        if("low".equals(state_intern)){
            gpio.setState(PinState.LOW, DO_1);
        }// end if   
    }// end DO_1   
   
    static void DO_2(String state) throws I2CFactory.UnsupportedBusNumberException, IOException {
  
        String state_intern = state;
        final MCP23008GpioProvider DO_8Bit = new MCP23008GpioProvider(I2CBus.BUS_1, 0x21);
       
        GpioPinDigitalOutput DO_2 = gpio.provisionDigitalOutputPin(DO_8Bit, MCP23008Pin.GPIO_02, "DO_2", PinState.LOW);

        if("high".equals(state_intern)){
            gpio.setState(PinState.HIGH, DO_2);
        }// end if
        if("low".equals(state_intern)){
            gpio.setState(PinState.LOW, DO_2);
        }// end if   
    }// end DO_2      
       
}// end class

Was haltet ihr davon? Gibt es eine bessere/ sicherere Methode um sowas zu realisieren?
 

mrBrown

Super-Moderator
Mitarbeiter
Naja, static ist wieder da...besser sind meistens Instanzen wenn man die an mehreren Stellen braucht, kann man die rumreichen.

@SuppressWarnings("unchecked") ist ganz schlecht ;)

Statt den String "high"/"low" zu übergeben, kann man stattdessen einfach enums nutzen.

Die DO_1/2/3 kann man zu einer Methode zusammenfügen - aus dem Unterschied macht man einfach einen Parameter
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
P Static Variable -> unterschiedliche Werte? Allgemeine Java-Themen 1
J private static final String variable Allgemeine Java-Themen 8
B static Variable / Unterklasse Allgemeine Java-Themen 2
J in einer static Variable Wert ändern Allgemeine Java-Themen 6
J Nicht-static variable in static variable kopieren - wie? Allgemeine Java-Themen 14
E Methoden abstract static Methode Allgemeine Java-Themen 8
N nicht static und auch nicht new Allgemeine Java-Themen 3
P static Blocks und variablen Allgemeine Java-Themen 41
Kirby.exe Cannot make a static reference to the non-static field rimWidth Allgemeine Java-Themen 12
Thallius Ist meine static Helper Class Thread save? Allgemeine Java-Themen 9
S static in Interface und Klasse Allgemeine Java-Themen 2
S static methode im Interface Allgemeine Java-Themen 1
K Static Variablen verbieten Allgemeine Java-Themen 10
C Generic collections und static typing Allgemeine Java-Themen 4
M Warum nicht static ? Allgemeine Java-Themen 10
M Eine static-Methode verlassen Allgemeine Java-Themen 2
B Schlüsselworte [ERLEDIGT] static { } - Was ist das und wofür kann ich das brauchen? Allgemeine Java-Themen 1
L Non-static-Variables in Enumerationen Allgemeine Java-Themen 2
L OOP Klassen-Design (static oder nicht?) Allgemeine Java-Themen 3
T Enumeration/Static Final/Bitfield Allgemeine Java-Themen 6
T Static kann nicht verändert werden Allgemeine Java-Themen 3
W Threads Cannot make a static reference.. Allgemeine Java-Themen 13
H Programierstil: static - Zugriff vs. Staticzugriff Allgemeine Java-Themen 24
N Static oder andere Lösung Allgemeine Java-Themen 5
N Vererbung Static & private fields - Nicht ganz einfach? Allgemeine Java-Themen 4
M Wo hin mit static factory methods? Allgemeine Java-Themen 40
M Public Static importRunning -> Bad Design oder ok ? Allgemeine Java-Themen 5
S Cannot make a static reference to the non-static field MySecondClass.Points Allgemeine Java-Themen 3
M Methoden Static Methoden und Thread??? Allgemeine Java-Themen 4
S auf public void Methode zugreifen ohne static Allgemeine Java-Themen 11
K Static - Problem Allgemeine Java-Themen 10
M Variablen Variablenzugriff aus static void Allgemeine Java-Themen 21
D API - Beispiel + static member in inner (non static) class Allgemeine Java-Themen 2
S static methoden Allgemeine Java-Themen 9
S Performance Frage: Objekt oder static? Allgemeine Java-Themen 33
X HTTP Problem mit static/non static JTextArea Update Allgemeine Java-Themen 17
A Annotation einer Subklasse im static-Block auslesen. Allgemeine Java-Themen 6
woezelmann referenz der outer class aus static nested class heraus Allgemeine Java-Themen 7
I Was macht static { ... } ? Allgemeine Java-Themen 8
G static inner Klassen Allgemeine Java-Themen 7
G static und dynamic linking? Allgemeine Java-Themen 32
J Verständnisfrage - nested static classes Allgemeine Java-Themen 11
G static- Methoden überschreiben Allgemeine Java-Themen 10
E Geschwindigkeit static Allgemeine Java-Themen 6
V Static oder wie? Allgemeine Java-Themen 61
I reflection get inner static classes Allgemeine Java-Themen 2
L static main - Spezifikation? Allgemeine Java-Themen 7
G URLClassLoader stößt static Block nicht an Allgemeine Java-Themen 8
D static Allgemeine Java-Themen 46
P static-Methode aus dem Konstruktor aufrufen Allgemeine Java-Themen 6
oliver1974 "(.) should be accessed in a static way" Falsche W Allgemeine Java-Themen 6
P static Klassenvariable Allgemeine Java-Themen 15
B JPasswordField klassenübergreifend auslesen->static Probl Allgemeine Java-Themen 4
F Methoden: static vs. instance Allgemeine Java-Themen 24
MQue static Methoden/Klassen Allgemeine Java-Themen 7
K Warum static-Methoden nutzen Allgemeine Java-Themen 26
G Java-Befehle Native und Static Allgemeine Java-Themen 2
conan2 static-Block in Klassen Allgemeine Java-Themen 6
M JNI, static.a mit load.Library laden? Allgemeine Java-Themen 2
K Static Members von Superklasse für JEDEN Erben Allgemeine Java-Themen 6
padde479 The static method sleep(long) from the type Thread should. Allgemeine Java-Themen 2
M static-Methode vorschreiben Allgemeine Java-Themen 5
S singleton vs. static Allgemeine Java-Themen 7
G Object mit static Feldern speichern Allgemeine Java-Themen 9
J Warum heißt es eig. "public static void main" ? Allgemeine Java-Themen 4
conan2 "Cannot make a static reference to the non-static field Allgemeine Java-Themen 8
P Singleton vs static Allgemeine Java-Themen 19
J parameterized und static fields Allgemeine Java-Themen 4
A Static reference to non-static field Allgemeine Java-Themen 10
S static umgehen Allgemeine Java-Themen 5
G static oder nicht Allgemeine Java-Themen 4
J Problem mit static/non-static Allgemeine Java-Themen 2
G getAppletContext() in static Methode Allgemeine Java-Themen 3
m@nu Programm-Models in Static-Objekten speichern Allgemeine Java-Themen 5
O does not declare a static final serialVersionUID field of . Allgemeine Java-Themen 6
G static vor einem array Allgemeine Java-Themen 2
K Überschreiben von 'static'-Methoden hat anderes Verhalten? Allgemeine Java-Themen 2
A JSP & static-Variablen Allgemeine Java-Themen 3
B Static Import: Syntaxfrage Allgemeine Java-Themen 2
S Static + Speicher + Bytecode etc. Brauche HILFE :/ Allgemeine Java-Themen 11
Z auf static Methode aus anderen Package zugreifen? Allgemeine Java-Themen 7
N this im public static void Allgemeine Java-Themen 3
C Communication zwischen zwei Projekte - static objects Allgemeine Java-Themen 4
S static mit abstract und in interface Allgemeine Java-Themen 10
W Variable Initialisierung mit dem Ergebnis einer Regex Allgemeine Java-Themen 1
A Clean Code: Variable vs. Methode Allgemeine Java-Themen 8
J Wo kommt der Wert der Variable her ? Allgemeine Java-Themen 6
E Variablen Nach Übergabe einer Variable den Constructor aufrufen Allgemeine Java-Themen 16
H lokale Variable bei Optional verwenden Allgemeine Java-Themen 11
A Variable in if initialisieren Allgemeine Java-Themen 23
S Variable als Objekt Name Allgemeine Java-Themen 3
D "Automatisierte", variable verschachtele for-Schleife Allgemeine Java-Themen 9
T statische Variable und nicht-statische Methode Allgemeine Java-Themen 2
P Variable wird in for - loop nicht richtig hochgezählt Allgemeine Java-Themen 11
A Variable, welche Exeption wirft als "Global" deklarieren Allgemeine Java-Themen 13
A Scanner Variable Klassenimtern deklarieren Allgemeine Java-Themen 12
L Variablen Variable nicht aktualisiert Allgemeine Java-Themen 3
denny86 NetBeans Ordnernamen rekursiv auslesen und in Variable verarbeiten Allgemeine Java-Themen 38
R Variable durch mehrere Methoden ändern und nutzen Allgemeine Java-Themen 17
C Abstrakte Klasse, lokale Variable-Problem Allgemeine Java-Themen 1

Ähnliche Java Themen

Neue Themen


Oben