Repaint doesn't work and the value of my private fields won't change?

不想你离开。 提交于 2019-12-25 02:31:08

问题


I am making a graphical interface in Netbeans where you can put a series of numbers (example: 7 8 5 4 10 13) in the textfield "punten" and when you press the button "ververs" a graphical linechart of all the numbers should appear (in my panel). I made a class "Gui" that extends JFrame with the Textfield, the button and a panel in it. I also made a class "Grafiek" that extends JPanel and that is linked with the panel in my "Gui".

The problems that I experience are: the repaint(); command won't go to the paintComponent(Graphics g)-method and my private variables won't change (the length of punt and punti stays 0).

Can somebody please help me, I've been working on this project for days.

My Gui-class:

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                   
}

And my "Grafiek"-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:


The code does not work because you add your points to the wrong object.

First of all, your panel object is not of type Grafiek, second of all it is first initialized in the method initComponents() and then overwritten again in the constructor.

Second problem, in the method verversActionPerformed called by the action listener, you create a new instance of Grafiek that is obviously not the one you have created/added before.

Thus, to make it work alter the code as follows:

The constructor should look the following:

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

The method like this:

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

Thus, it works as you expected.

However, this is far away from good code. You should set the type of variable panel to the correct type Grafiek.



来源:https://stackoverflow.com/questions/23310564/repaint-doesnt-work-and-the-value-of-my-private-fields-wont-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!