在将ArrayList填充到JList的程序中重叠

时间:2015-01-13 18:51:21

标签: java

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class IsPrimeNumber {
    private static JTextField input;
    private static JLabel title;

    private static final int START = 2;
    private static int end = 0;
    public static void main(String[] args) {
        runner();
    }
    static void runner(){
        makeFrame();
    }
    private static boolean isPrime(int num) {
        if (num % 2 == 0 && num!=2)// checks if number is even, even numbers other than 2 are always not prime.
            return false;
        for (int i = 3; i * i <= num; i += 2) 
            if (num % i == 0) return false; return true;
    }
    private static void makeFrame()//creates and builds JFrame 
    {
        final JFrame frame = new JFrame("isPrime");
        final JPanel contentPane = (JPanel)frame.getContentPane();//organize content.
        contentPane.setLayout(new BorderLayout(8, 8));
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));

        title = new JLabel();
        title.setText("Enter a # then press Enter!");
        contentPane.add(title, BorderLayout);//adds title
        input = new JTextField();
        input.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {//waits for enter press to add number.
                try {
                    end = Integer.parseInt(input.getText()); //parses end grabbed from JTextField from String to Int

                    if(end<=1) 
                        throw new RuntimeException();  
                    JList primeRangeList = new JList(makeList().toArray());
                    JList primeFactorList = new JList(primeFactors().toArray());

                    contentPane.add(primeRangeList, BorderLayout.NORTH);
                    contentPane.add(primeFactorList, BorderLayout.SOUTH);
                    title.setText("Press enter to try another #!");
                } catch (NumberFormatException a) {
                    title.setText("Not a Valid #, try again!");//changes title in even of error.
                    end = 0;
                } catch (RuntimeException r) {
                    if (end == 1)
                        title.setText("There are no prime #s below 1 :(");
                    else
                        title.setText("You cannot use negative numbers :(");
                }
                frame.pack();
            }
        });
        contentPane.add(input, BorderLayout.SOUTH); 
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static ArrayList<Integer> primeFactors() {
        ArrayList<Integer> factors = new ArrayList<Integer>();
        for (int i = 2; i <=end; i++) {
            while (end % i == 0) {
                factors.add(i);
                end /= i;
            }
        }
        return factors;
    }

    public static ArrayList<Integer> makeList(){//creates array list of possible numbers.
        ArrayList<Integer>makeList= new ArrayList<Integer>();
        for (int i = START; i <= end; i++) 
            if (isPrime(i))
                makeList.add(i);
        return makeList;
    }
}

我在使元素正确传播到帧时遇到了一些困难。 如果输入一个返回带有10个点的JList的数字,但是尝试检查返回5个点的JList,则会反过来使标签,文本域和两个JL列重叠。

如果有人能告诉我哪里出错,那就太酷了。

感谢。

1 个答案:

答案 0 :(得分:2)

通常,您只需创建一次Swing组件,然后更改GUI中的文本。

我无法使整数列表正常工作,因此我改为使用DefaultListModels。

这是我创建的GUI。

JFrame

这是代码。

package com.ggl.testing;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class IsPrimeNumber implements Runnable {

    private DefaultListModel<Integer> primeRangeModel;
    private DefaultListModel<Integer> primeFactorModel;

    private JLabel message;

    private JList<Integer> primeRangeList;
    private JList<Integer> primeFactorList;

    private JTextField input;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new IsPrimeNumber());
    }

    public IsPrimeNumber() {
        this.primeRangeModel = new DefaultListModel<Integer>();
        this.primeFactorModel = new DefaultListModel<Integer>();
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("isPrime");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));

        JPanel numberPanel = new JPanel();
        numberPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 10));
        numberPanel.setLayout(new BoxLayout(numberPanel, BoxLayout.PAGE_AXIS));

        JLabel title = new JLabel();
        title.setText("Enter a number, then press Enter");
        numberPanel.add(title); // adds title

        input = new JTextField();
        input.addActionListener(new PrimeActionListener());
        numberPanel.add(input);

        message = new JLabel(" ");
        message.setForeground(Color.RED);
        numberPanel.add(message);

        mainPanel.add(numberPanel);
        mainPanel.add(Box.createVerticalStrut(10));

        JPanel primeRangePanel = new JPanel();
        primeRangePanel.setBorder(BorderFactory
                .createTitledBorder("Prime Range"));

        primeRangeList = new JList<Integer>(primeRangeModel);
        JScrollPane primeRangeScrollPane = new JScrollPane(primeRangeList);
        primeRangePanel.add(primeRangeScrollPane);

        mainPanel.add(primeRangePanel);

        JPanel primeFactorPanel = new JPanel();
        primeFactorPanel.setBorder(BorderFactory
                .createTitledBorder("Prime Factors"));

        primeFactorList = new JList<Integer>(primeFactorModel);
        JScrollPane primeFactorScrollPane = new JScrollPane(primeFactorList);
        primeFactorPanel.add(primeFactorScrollPane);

        mainPanel.add(primeFactorPanel);

        frame.add(mainPanel);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public class PrimeActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            clearModels();
            int start = 2;
            int end = 0;
            try {
                end = Integer.parseInt(input.getText().trim());
                if (end <= 1) {
                    throw new RuntimeException();
                }
                primeRanges(start, end);
                primeFactors(end);
                message.setText(" ");
            } catch (NumberFormatException a) {
                message.setText("Not a valid number, try again :(");
            } catch (RuntimeException r) {
                if (end >= 0) {
                    message.setText("There are no prime numbers below 2 :(");
                } else {
                    message.setText("You cannot use negative numbers :(");
                }
            }
        }

        private void clearModels() {
            primeRangeModel.clear();
            primeFactorModel.clear();
        }

        private void primeRanges(int start, int end) {
            for (int i = start; i <= end; i++) {
                if (isPrime(i)) {
                    primeRangeModel.addElement(i);
                }
            }
        }

        private void primeFactors(int end) {
            for (int i = 2; i <= end; i++) {
                while (end % i == 0) {
                    primeFactorModel.addElement(i);
                    end /= i;
                }
            }
        }

        private boolean isPrime(int num) {
            if (num % 2 == 0 && num != 2) {
                return false;
            }

            for (int i = 3; i * i <= num; i += 2) {
                if (num % i == 0) {
                    return false;
                }
            }

            return true;
        }
    }
}