由于扫描仪或while循环,JFrame没有显示?

时间:2013-11-27 09:49:38

标签: java swing while-loop jframe java.util.scanner

我试图用扫描仪读取文件,我认为下面写的代码是我需要的代码,可以做我想要的。

傀儡:我可以读取关卡,之后我可以读取边缘(来自kochfractal)和颜色。

当我尝试运行JFrame时,它正在运行但没有显示,当我注释掉下面的代码时,它显示了框架。

正在读取的文件包含(int只发生在文件1的顶部,然后是3的双重颜色并不是固定的,它取决于int中的数字,它们将发生多少次在文件中)

int
double
double
double
color
double
double
double
color
double
double
double
color
double
double
double
color

try {
    Scanner fileScanner = new Scanner(new File(filepath+"wwob.txt"));

    while(fileScanner.hasNextInt()){
        levelInFile = fileScanner.nextInt();
        lblLvl.setText("Level: "+levelInFile);
    }
    while(fileScanner.hasNextLine()){
    while(fileScanner.hasNextDouble()){
        str1 = str1+fileScanner.nextDouble()+"--";
        str2 = str2+fileScanner.nextDouble()+"--";
        str3 = str3+fileScanner.nextDouble()+"--";
        String color= fileScanner.next().toString();
    }
    }
    lblEdgesBottom.setText(str1);
    lblEdgesLeft.setText(str2);
    lblEdgesRight.setText(str3);

请求的额外代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * KochPanel.java
 *
 * Created on 2-jul-2011, 10:08:42
 */
package gui;

import java.awt.Graphics;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import timeutil.TimeStamp;

/**
 *
 * @author Peter Boots
 */
public class KochPanel extends javax.swing.JPanel{ 

    private timeutil.TimeStamp ts;
    private static String filepath =File.separator+"media"+File.separator+"new_disk"+File.separator;

    /**
     * Creates new form KochPanel
     */
    @SuppressWarnings("LeakingThisInConstructor")
    public KochPanel() {
        initComponents();
    }

    public void changeLevel(int nxt) {

            ts = new TimeStamp();
            ts.setBegin("Generate koch edges");

            int levelInFile=0;
            String str1="";
            String str2="";
            String str3="";

            try {
            Scanner fileScanner = new Scanner(new File(filepath+"wwob.txt"));

            while(fileScanner.hasNextInt()){
                levelInFile = fileScanner.nextInt();
                lblLvl.setText("Level: "+levelInFile);
            }
            while(fileScanner.hasNextLine()){
            while(fileScanner.hasNextDouble()){
                str1 = str1+fileScanner.nextDouble()+"--";
                str2 = str2+fileScanner.nextDouble()+"--";
                str3 = str3+fileScanner.nextDouble()+"--";
                String color= fileScanner.next().toString();
            }
            }
            lblEdgesBottom.setText(str1);
            lblEdgesLeft.setText(str2);
            lblEdgesRight.setText(str3);

            ts.setEnd("Einde koch edges");
            System.out.println(ts.toString());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(KochPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

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

        lblLvl = new javax.swing.JLabel();
        lblEdgesLeft = new javax.swing.JLabel();
        lblEdgesRight = new javax.swing.JLabel();
        lblEdgesBottom = new javax.swing.JLabel();

        setBackground(new java.awt.Color(0, 0, 0));
        setDoubleBuffered(false);

        lblLvl.setForeground(new java.awt.Color(255, 0, 0));
        lblLvl.setText("jLabel1");

        lblEdgesLeft.setForeground(new java.awt.Color(255, 0, 0));
        lblEdgesLeft.setText("jLabel2");

        lblEdgesRight.setForeground(new java.awt.Color(255, 0, 0));
        lblEdgesRight.setText("jLabel3");

        lblEdgesBottom.setForeground(new java.awt.Color(255, 0, 0));
        lblEdgesBottom.setText("jLabel4");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblLvl)
                    .addComponent(lblEdgesLeft)
                    .addComponent(lblEdgesRight)
                    .addComponent(lblEdgesBottom))
                .addContainerGap(356, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblLvl)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblEdgesLeft)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblEdgesRight)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblEdgesBottom)
                .addContainerGap(211, Short.MAX_VALUE))
        );
    }// </editor-fold>                        

    // Variables declaration - do not modify                     
    private javax.swing.JLabel lblEdgesBottom;
    private javax.swing.JLabel lblEdgesLeft;
    private javax.swing.JLabel lblEdgesRight;
    public javax.swing.JLabel lblLvl;
    // End of variables declaration                   


    @Override
    public synchronized void paintComponent(Graphics g) {
        ts = new TimeStamp();
        ts.setBegin("Begin paintComponent");
        super.paintComponent(g);




        ts.setEnd(" Einde paintComponent");
        System.out.println(ts.toString());
        System.out.println("Aantal hoekpunten: ");
//        lblLvl.setText("Number of edges: ");
//        lblEdgesLeft.setText(ts.toString());
}

}

包含主类的代码,这个类我正在编辑:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * KochFrame.java
 *
 * Created on 2-jul-2011, 10:00:05
 */
package gui;

import calculate.Edge;


/**
 *
 * @author Peter Boots
 */
public class KochFrame extends javax.swing.JFrame {

    private static int zoomTranslateX = 0;
    private static int zoomTranslateY = 0;
    private static double zoom = 1;
    private int lastDragX = 0;
    private int lastDragY = 0;
    private int level = 1;

    /** Creates new form KochFrame */
    public KochFrame() {
        initComponents();
        level = 1;
        resetZoom();
        kochPanel.changeLevel(level);
    }

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

        fitFractalBtn = new javax.swing.JButton();
        levelSpinner = new javax.swing.JSpinner();
        jLabel1 = new javax.swing.JLabel();
        kochPanel = new gui.KochPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Koch Fractal");

        fitFractalBtn.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        fitFractalBtn.setText("Fit Fractal");
        fitFractalBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fitFractalBtnActionPerformed(evt);
            }
        });

        levelSpinner.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        levelSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
        levelSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                levelSpinnerStateChanged(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Level: ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(levelSpinner))
                        .addComponent(fitFractalBtn, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(kochPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(81, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(kochPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(levelSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fitFractalBtn)
                .addContainerGap())
        );

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

    private void fitFractalBtnActionPerformed(java.awt.event.ActionEvent evt) {                                              
        resetZoom();
        kochPanel.repaint();
    }                                             

private void levelSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {                                          
    kochPanel.changeLevel((Integer) (levelSpinner.getValue()));
}                                         

    private void kochPanelMouseClicked(java.awt.event.MouseEvent evt) {                                       
        double originalPointClickedX = (zoomTranslateX + evt.getX()) / zoom;
    double originalPointClickedY = (zoomTranslateY + evt.getY()) / zoom;

    if (evt.getButton() == java.awt.event.MouseEvent.BUTTON1) {
        zoom *= 2;
    } else if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
        zoom /= 2;
    }
    zoomTranslateX = (int) (originalPointClickedX * zoom - evt.getX());
    zoomTranslateY = (int) (originalPointClickedY * zoom - evt.getY());
    kochPanel.repaint();
    }                                      

    private void kochPanelMouseDragged(java.awt.event.MouseEvent evt) {                                       
        zoomTranslateX = zoomTranslateX + lastDragX - evt.getX();
    zoomTranslateY = zoomTranslateY + lastDragY - evt.getY();
    lastDragX = evt.getX();
    lastDragY = evt.getY();
    kochPanel.repaint();
    }                                      

    private void kochPanelMousePressed(java.awt.event.MouseEvent evt) {                                       
        lastDragX = evt.getX();
    lastDragY = evt.getY();
    }                                      

    private void resetZoom() {
        int kpWidth = kochPanel.getWidth();
        int kpHeight = kochPanel.getHeight();
        int kpSize = Math.min(kpWidth, kpHeight);
        zoom = kpSize;
        zoomTranslateX = -(kpWidth - kpSize) / 2;
        zoomTranslateY = -(kpHeight - kpSize) / 2;
    }

    static public Edge edgeAfterZoomAndDrag(Edge e) {
        return new Edge(
                e.X1 * zoom - zoomTranslateX,
                e.Y1 * zoom - zoomTranslateY,
                e.X2 * zoom - zoomTranslateX,
                e.Y2 * zoom - zoomTranslateY,
                e.color);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new KochFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton fitFractalBtn;
    private javax.swing.JLabel jLabel1;
    private gui.KochPanel kochPanel;
    private javax.swing.JSpinner levelSpinner;
    // End of variables declaration
}

1 个答案:

答案 0 :(得分:1)

您的KochiPanel中有更新:

public void changeLevel(int nxt) {

    ts = new TimeStamp();
    ts.setBegin("Generate koch edges");

    int levelInFile=0;
    String str1="";
    String str2="";
    String str3="";

    try {
        Scanner fileScanner = new Scanner(new File("c:/test.txt"));

        //read line by line
        int doubleNO=1;
        while(fileScanner.hasNextLine()){
            String line = fileScanner.nextLine();


            //if its integer
            try{
             int level = Integer.parseInt(line);  
             lblLvl.setText("Level: "+level);
             continue;
            }catch(NumberFormatException e){
                //ignore
            }

            try{
                double value = Double.parseDouble(line);

                if(doubleNO==1){
                    str1 = str1+value+"--";                       
                }else if(doubleNO==2) { 
                    str2 = str2+value+"--";                       
                }else if (doubleNO==3){
                    str3 = str3+value+"--";                       
                }
                doubleNO++;
                continue;
            }catch(NumberFormatException e){

                //reset 
               //its color here
                System.out.println("Color " + line );
                doubleNO=1;
            }
        }

        lblEdgesBottom.setText(str1);
        lblEdgesLeft.setText(str2);
        lblEdgesRight.setText(str3);

        ts.setEnd("Einde koch edges");
        System.out.println(ts.toString());
    } catch (FileNotFoundException ex) {
        Logger.getLogger(KochPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

这基于输入文本文件:

1
3.4
4.5
5.6
color
3.4
4.5
5.6
color
3.44
4.55
5.67
color
3.4
4.5
5.6
color

输出:

enter image description here