重绘不起作用,我的私人字段的价值不会改变?

时间:2014-04-26 12:02:10

标签: java netbeans awt paintcomponent repaint

我正在Netbeans中创建一个图形界面,您可以在文本字段中放置一系列数字(例如:7 8 5 4 10 13)" punten"当你按下按钮" ververs"应显示所有数字的图形线图(在我的面板中)。我做了一个班级" Gui"它扩展了JFrame的Textfield,按钮和面板。我还上了一堂课#34; Grafiek"这扩展了JPanel,并与我的" Gui"。

中的面板相关联

我遇到的问题是:重绘();命令不会转到paintComponent(Graphics g) - 方法,我的私有变量不会改变(punt和punti的长度保持为0)。

有人可以帮助我,我已经在这个项目上工作了好几天。

我的贵班:

import java.awt.Graphics;

public class Gui extends javax.swing.JFrame {

public Gui() {
    initComponents();
    panel = new javax.swing.JPanel();
}

/**
 * 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() {

    punten = new javax.swing.JTextField();
    fout = new javax.swing.JLabel();
    javax.swing.JButton ververs = new javax.swing.JButton();
    panel = new Grafiek();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    fout.setText("j");

    ververs.setText("Ververs");
    ververs.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            verversActionPerformed(evt);
        }
    });

    panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));

    javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
    panel.setLayout(panelLayout);
    panelLayout.setHorizontalGroup(
        panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 0, Short.MAX_VALUE)
    );
    panelLayout.setVerticalGroup(
        panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 195, 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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(punten, javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                    .addComponent(ververs)
                    .addGap(6, 6, 6)
                    .addComponent(fout)
                    .addGap(0, 302, Short.MAX_VALUE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(punten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(fout)
                .addComponent(ververs))
            .addContainerGap())
    );

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

private void verversActionPerformed(java.awt.event.ActionEvent evt) {                                        
    Grafiek graf = new Grafiek();
    graf.verwerkData(punten.getText());
}                                       

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* 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(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Gui().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel fout;
private javax.swing.JPanel panel;
private javax.swing.JTextField punten;
// End of variables declaration                   
}

我的&#34; Grafiek&#34; -class:

import java.awt.Graphics;

public class Grafiek extends javax.swing.JPanel {

private String[] punt;
private int[] punti;
private int afstandX, afstandY, puntX1=0, puntY1=0, puntX2=0, puntY2=0;
private int max=1;

/**
 * Creates new form Grafiek
 */
public Grafiek() {
    initComponents();
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    try{
        for(int i=0; i<punti.length; i++) {
            if(max <= punti[i]) {
                max = punti[i];
            }
        }

        afstandX = getWidth()/punt.length;
        afstandY = getHeight()/max;

        for(int i=0; i<punti.length; i++) {
            puntX1 = puntX2;
            if(i == 0) {
                puntY1 = getHeight();
            }
            else puntY1 = puntY2;
            puntX2 += afstandX;
            puntY2 = getHeight() - punti[i]*afstandY;

            g.drawLine(puntX1, puntY1, puntX2, puntY2);
        }

        puntX2 = 0;
        puntY2 = 0;
    }catch(java.lang.NullPointerException npe) {
        super.paintComponent(g);
    }
}

public void verwerkData(String s) {
    punt = s.split(" ");

    punti = new int[punt.length];

    for(int i=0; i<punt.length; i++) {
        punti[i] = Integer.parseInt(punt[i]);
    }

    repaint();
}

/**
 * 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() {

    setBackground(new java.awt.Color(255, 255, 255));

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );
}// </editor-fold>                        

}

1 个答案:

答案 0 :(得分:0)

代码不起作用,因为您将点添加到错误的对象。

首先,您的panel对象不是Grafiek类型,其次是首先在方法initComponents()中初始化,然后在构造函数中再次覆盖。

第二个问题,在动作监听器调用的方法verversActionPerformed中,您创建了一个Grafiek的新实例,该实例显然不是您之前创建/添加的实例。

因此,为了使其工作改变代码如下:

构造函数应该如下所示:

public Gui() {
    initComponents();
    //panel = new javax.swing.JPanel();
}

这样的方法:

private void verversActionPerformed(java.awt.event.ActionEvent evt) {                                        
    Grafiek graf = (Grafiek)panel;
    graf.verwerkData(punten.getText());
}

因此,它按预期工作。

但是,这远远不是好的代码。您应该将变量panel的类型设置为正确的类型Grafiek