Java Swing-如何使下一个和上一个按钮显示数组中对象的变量?

比格朗加

每个人。我创建了一个自定义类“人类”的数组以创建一个“城市”。
每个人都有一个随机生成的姓名和年龄。
我想使用下一个和上一个按钮滚动查看每个人并查看其信息。
我将如何去做呢?
这是我的源代码:

JamiesCity.java:

package jamiesCity;

import javax.swing.*;

import net.miginfocom.swing.MigLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JamiesCity {

    public static void main(String[] args) {
        JamiesCity j = new JamiesCity();
        j.createMainGUI();
    }

    City newCity;

    public void createMainGUI(){    
        JFrame startGUI;
        startGUI = new JFrame();
        startGUI.setSize(485, 85);
        startGUI.setLocationRelativeTo(null);
        startGUI.setTitle("Jamie's City");
        startGUI.setLayout(null);
        startGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        startGUI.setResizable(false);

        JButton create;
        create = new JButton("New City");
        create.setBounds(15, 15, 130, 25);
        startGUI.add(create);

        JTextField title;
        title = new JTextField("City Name");
        title.setBounds(155, 15, 305, 25);
        startGUI.add(title);

        create.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                createCity(title.getText());
            }
        });
        startGUI.setVisible(true);
    }

    public void createCity(String name){
        newCity = new City(name);
        dispCityInfo(name, newCity);        
    }

    public void dispCityInfo(String name, City city){
        JFrame dispCity = new JFrame(name);
        dispCity.setLocationRelativeTo(null);
        dispCity.setResizable(false);
        dispCity.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel panel = new JPanel();

        panel.setLayout(new MigLayout("insets 30"));

        JLabel personMarker = new JLabel("-------Person-------");
        JLabel cityName = new JLabel("City Name: ");
        JLabel cityPopulation = new JLabel("City Population: ");
        JLabel personName = new JLabel("Name: ");
        JLabel personAge = new JLabel("Age: ");
        JLabel personGender = new JLabel("Gender: ");

        String theName = new String(city.getFirstNameOfPerson(0) + " " + newCity.getLastNameOfPerson(0));
        String theAge = new String(city.getAgeOfPersonAsString(0));
        String theGender = new String(city.getGenderOfPerson(0));

        JLabel theCityName = new JLabel(city.getCityName());
        JLabel theCityPopulation = new JLabel(city.getPopulationAsString());
        JLabel thePersonName = new JLabel(theName);
        JLabel thePersonAge = new JLabel(theAge);
        JLabel thePersonGender = new JLabel(theGender);

        JButton next = new JButton("Next");
        JButton previous = new JButton("Previous");

        //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        dispCity.add(panel);
        panel.add(cityName);
        panel.add(theCityName, "wrap");
        panel.add(cityPopulation);
        panel.add(theCityPopulation, "wrap");
        panel.add(personMarker, "span 2, align center, wrap");
        panel.add(personName);
        panel.add(thePersonName, "wrap");
        panel.add(personAge);
        panel.add(thePersonAge, "wrap");
        panel.add(personGender);
        panel.add(thePersonGender, "wrap");
        panel.add(next, "cell 0 6 2 1, width 200");
        panel.add(previous, "cell 0 7 2 1, width 200");

        //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        next.addActionListener(new ActionListener() { //show info of next person
            public void actionPerformed(ActionEvent e) {

            }
        });

        previous.addActionListener(new ActionListener() { //show info of previous person
            public void actionPerformed(ActionEvent e) {

            }
        });

        //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        dispCity.pack();
        dispCity.setVisible(true);
    }

}

City.java:

package jamiesCity;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class City {

    //Variables

    private String CityName;
    private int population;
    private int popLength;
    public Human[] thePeople;
    private ArrayList<String> maleFirsts = new ArrayList<String>();
    private ArrayList<String> femaleFirsts = new ArrayList<String>();
    private ArrayList<String> lasts = new ArrayList<String>();

    //Constructor

    public City(String cityName){

        this.CityName = cityName;

        Random rand = new Random();
        int randomNum = rand.nextInt((8000000 - 10000) + 1) + 10000;
        this.setPopulation(randomNum);  

        thePeople = new Human[(int) population];

        MaleFirstNames();
        FemaleFirstNames();
        LastNames();

        for(int i = 0; i < thePeople.length; i++){

            String MFirstName = "";
            Random MfirstNames = new Random();
            int MfirstNameRand = MfirstNames.nextInt((maleFirsts.size() - 0) + 0);
            MFirstName = maleFirsts.get(MfirstNameRand);

            String FFirstName = "";
            Random FfirstNames = new Random();
            int FfirstNameRand = FfirstNames.nextInt((maleFirsts.size() - 0) + 0);
            FFirstName = femaleFirsts.get(FfirstNameRand);

            String LastName = "";
            Random LastNameRand = new Random();
            int LastNameRandomNumber = LastNameRand.nextInt((lasts.size() - 0) + 0);
            LastName = lasts.get(LastNameRandomNumber);

            Random AgeRand = new Random();
            int Age = AgeRand.nextInt((101 - 1) + 1);

            if(i < thePeople.length / 2){
                thePeople[i] = new Human(MFirstName, LastName, Age, "Male");
            }
            if(i == thePeople.length / 2){
                thePeople[i] = new Human(FFirstName, LastName, Age, "Female");
            }   
        }
        this.popLength = thePeople.length;
    }

    //Scan CSVs

    private void MaleFirstNames(){
        File maleFirstsCSV = new File("src/jamiesCity/male.firstnames.csv");
        try {
            Scanner maleFirstNames = new Scanner(maleFirstsCSV);
            while(maleFirstNames.hasNext()){
                String input = maleFirstNames.next();
                String values[] = input.split(",");
                maleFirsts.add(values[0]);
            }
            maleFirstNames.close();
        } catch (FileNotFoundException e) {
            System.out.println("Cannot Find Male First Names CSV File");
        }
    }

    private void FemaleFirstNames(){
        File maleFirstsCSV = new File("src/jamiesCity/female.firstnames.csv");
        try {
            Scanner femaleFirstNames = new Scanner(maleFirstsCSV);
            while(femaleFirstNames.hasNext()){
                String input = femaleFirstNames.next();
                String values[] = input.split(",");
                femaleFirsts.add(values[0]);
            }
            femaleFirstNames.close();
        } catch (FileNotFoundException e) {
            System.out.println("Cannot Find Female First Names CSV File");
        }
    }

    private void LastNames(){
        File maleFirstsCSV = new File("src/jamiesCity/CSV_Database_of_Last_Names.csv");
        try {
            Scanner lastNames = new Scanner(maleFirstsCSV);
            while(lastNames.hasNext()){
                String input = lastNames.next();
                String values[] = input.split(",");
                lasts.add(values[0]);
            }
            lastNames.close();
        } catch (FileNotFoundException e) {
            System.out.println("Cannot Find Last Names CSV File");
        }
    }

    //Getters and Setters

    public String getFirstNameOfPerson(int HumanCount){
        String name = thePeople[HumanCount].getFirstName();
        return name;
    }
    public String getGenderOfPerson(int HumanCount){
        String gender = thePeople[HumanCount].getGender();
        return gender;
    }
    public String getLastNameOfPerson(int HumanCount){
        String name = thePeople[HumanCount].getLastName();
        return name;
    }
    public int getAgeOfPerson(int HumanCount){
        int age = thePeople[HumanCount].getAge();
        return age;
    }

    public String getAgeOfPersonAsString(int HumanCount){
        StringBuilder age = new StringBuilder();
        age.append(thePeople[HumanCount].getAge());
        String theAge = age.toString();
        return theAge;
    }

    public int getPopLength() {
        return popLength;
    }

    public void setPopLength(int i){
        this.popLength = i;
    }

    public int getPopulation() {
        return population;
    }

    public String getPopulationAsString() {
        StringBuilder builder = new StringBuilder();
        builder.append(population);
        String pop = builder.toString();
        return pop;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public String getCityName() {
        return CityName;
    }

    public void setCityName(String cityName) {
        CityName = cityName;
    }

    //End of Getters and Setters
}

Human.java:

package jamiesCity;

public class Human {

    private String firstName = "firstName";
    private String lastName = "lastName";
    private int Age = 99;
    private String gender = null;

    public int getAge(){
        return Age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setAge(int age){
        Age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Human(String firstName, String lastName, int Age, String gender){
        this.firstName = firstName;
        this.lastName = lastName;
        this.Age = Age;
        this.gender = gender;
    }

}

任何帮助将非常感激。谢谢 :)

充满鳗鱼的气垫船

意见建议:

  • 由于这似乎是一项任务,因此我将避免为您提供代码,而是提供一些一般性的建议,希望它们可以帮助您入门。
  • 为容纳您的Humans的任何数组或集合创建一个int索引变量-此处看起来是thePeople数组。将此索引设置为非静态字段。
  • 在下一个按钮的ActionListener中,推进索引,确保其大小不等于或大于数组或集合,获取该索引的Human,并将其显示在GUI中。
  • 相反,在上一个按钮中,递减索引,确保索引为0或更大,然后获取该索引的Human,然后将其显示在GUI中。
  • 您将要确定如果索引到达边界时该怎么做-变得小于0或等于数组的长度。如果要循环搜索,则如果搜索结果小于零,length - 1则将其分配给,或者将其分配给长度大小,然后将其分配给0。

不相关的建议:

  • 避免使用空布局。空布局和setBounds()Swing新手似乎是创建复杂GUI的最简单,最好的方法,但您创建的Swing GUI越多,使用它们时就会遇到更大的困难。当GUI调整大小时,它们不会重新调整组件的大小;它们是要增强或维护的皇家女巫;放置在滚动窗格中时,它们会完全失败;在所有平台或与原始分辨率不同的屏幕分辨率下,它们看起来都令人作呕。
  • 您将要学习和使用Java命名约定变量名都应以小写字母开头,而类名应以大写字母开头。学习和遵循此规则将使我们能够更好地理解您的代码,并使您能够更好地理解其他人的代码。

好吧,我撒谎并确实创造了一些东西来测试概念:

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("serial")
public class SimpleCityGui extends JPanel {
    private SimpleCity city = new SimpleCity();
    private SimpleHumanPanel humanPanel = new SimpleHumanPanel();

    public SimpleCityGui() {
        humanPanel.setFocusable(false);
        humanPanel.setBorder(BorderFactory.createTitledBorder("Current Human"));

        JPanel btnPanel = new JPanel();
        btnPanel.add(new JButton(new AddHumanAction("Add")));
        btnPanel.add(new JButton(new NextAction("Next")));
        btnPanel.add(new JButton(new PreviousAction("Previous")));

        setLayout(new BorderLayout());
        add(humanPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.PAGE_END);
    }

    private class AddHumanAction extends AbstractAction {
        SimpleHumanPanel innerHumanPanel = new SimpleHumanPanel();

        public AddHumanAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            innerHumanPanel.clear();
            Component parentComponent = SimpleCityGui.this;
            SimpleHumanPanel message = innerHumanPanel;
            String title = "Create a Human";
            int optionType = JOptionPane.OK_CANCEL_OPTION;
            int messageType = JOptionPane.PLAIN_MESSAGE;
            int selection = JOptionPane.showConfirmDialog(parentComponent,
                    message, title, optionType, messageType);

            if (selection == JOptionPane.OK_OPTION) {
                city.addHuman(innerHumanPanel.createHuman());
                humanPanel.setHuman(city.getCurrentHuman());
            }
        }
    }

    private class NextAction extends AbstractAction {

        public NextAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            SimpleHuman nextHuman = city.next();
            if (nextHuman != null) {
                humanPanel.setHuman(nextHuman);
            }
        }
    }

    private class PreviousAction extends AbstractAction {

        public PreviousAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            SimpleHuman previousHuman = city.previous();
            if (previousHuman != null) {
                humanPanel.setHuman(previousHuman);
            }
        }
    }

    private static void createAndShowGui() {
        SimpleCityGui mainPanel = new SimpleCityGui();

        JFrame frame = new JFrame("SimpleCityGui");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

@SuppressWarnings("serial")
class SimpleHumanPanel extends JPanel {
    private static final int COLS = 10;
    private static final Insets INSETS = new Insets(5, 5, 5, 5);
    private JTextField firstNameField = new JTextField(COLS);
    private JTextField lastNameField = new JTextField(COLS);
    private JTextComponent[] textComponents = { firstNameField, lastNameField };
    private SimpleHuman human;

    public SimpleHumanPanel() {
        setLayout(new GridBagLayout());
        add(new JLabel("First Name:"), createGbc(0, 0));
        add(firstNameField, createGbc(1, 0));
        add(new JLabel("Last Name:"), createGbc(0, 1));
        add(lastNameField, createGbc(1, 1));
    }

    @Override
    public void setFocusable(boolean focusable) {
        super.setFocusable(focusable);
        for (JTextComponent jTextComponent : textComponents) {
            jTextComponent.setFocusable(focusable);
        }
    }

    public void setHuman(SimpleHuman human) {
        this.human = human;
        firstNameField.setText(human.getFirstName());
        lastNameField.setText(human.getLastName());
    }

    public SimpleHuman getHuman() {
        return human;
    }

    public void clear() {
        this.human = null;
        for (JTextComponent jTextComponent : textComponents) {
            jTextComponent.setText("");
        }
    }

    public SimpleHuman createHuman() {
        String firstName = firstNameField.getText();
        String lastName = lastNameField.getText();
        human = new SimpleHuman(firstName, lastName);
        return human;
    }

    private static GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.insets = INSETS;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }
}

class SimpleCity {
    private List<SimpleHuman> humanList = new ArrayList<>();
    private int humanListIndex = -1; // start with a nonsense value

    public void addHuman(SimpleHuman h) {
        humanList.add(h);
        if (humanListIndex == -1) {
            humanListIndex = 0;
        }
    }

    public SimpleHuman getHuman(int index) {
        return humanList.get(index);
    }

    public SimpleHuman getCurrentHuman() {
        if (humanListIndex == -1) {
            return null;
        }
        return humanList.get(humanListIndex);

    }

    public SimpleHuman next() {
        if (humanListIndex == -1) {
            return null;
        }

        humanListIndex++;
        humanListIndex %= humanList.size(); // set back to 0 if == size
        return humanList.get(humanListIndex);
    }

    public SimpleHuman previous() {
        if (humanListIndex == -1) {
            return null;
        }

        humanListIndex--;
        humanListIndex += humanList.size();
        humanListIndex %= humanList.size();
        return humanList.get(humanListIndex);
    }
}

class SimpleHuman {
    private String firstName;
    private String lastName;

    public SimpleHuman(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result
                + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        SimpleHuman other = (SimpleHuman) obj;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "SimpleHuman [firstName=" + firstName + ", lastName=" + lastName
                + "]";
    }

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

当用户在 Java Swing 中单击按钮时从另一个类创建一个新对象

来自分类Dev

如何禁用一个按钮而不是Java Swing中的全部按钮?

来自分类Dev

单击一个按钮将调用JAVA Swing中另一个按钮的actionListener

来自分类Dev

如何让按钮创建一个包含java swing中表单内容的文本文档?

来自分类Dev

Java流在完成上一个之前开始下一个映射

来自分类Dev

用Java Swing创建一个窗口

来自分类Dev

如何从一个对象和一个对象添加一个Swing组件到arraylist中的一个Swing组件中?

来自分类Dev

如何在Java Swing中重定向到另一个窗口?

来自分类Dev

如何从NetBeans中的另一个类方法调用Java swing Jpanel?

来自分类Dev

在Swing Java中打开另一个框架时如何禁用根框架

来自分类Dev

Java Swing-如何从另一个类获取TextField中的文本值

来自分类Dev

Java Swing按钮actionEvent

来自分类Dev

通过按钮Java Swing打开一个新面板

来自分类Dev

Java Swing 中的 GridBagLayout

来自分类Dev

Java中的Swing DJnative Swing示例

来自分类Dev

Java Swing GridBagLayout() 跨越一个对象 3 行不起作用

来自分类Dev

如何从另一个子 JPanel (Java Swing) 中的输入触发一个子 JPanel 中的操作?

来自分类Dev

将所有java swing gui放在一个类中是正常的吗?

来自分类Dev

一个JButton中的Java Swing保留插图的更改边框颜色

来自分类Dev

将所有java swing gui放在一个类中是正常的吗?

来自分类Dev

在Java Swing中定位对象

来自分类Dev

使用Java解析特定节点的xml后尝试获取节点的下一个和上一个同级

来自分类Dev

使用Java解析特定节点的xml后尝试获取节点的下一个和上一个同级

来自分类Dev

在Java Integer数组中获取下一个索引

来自分类Dev

如何在Java Swing中创建一个hello世界?我的代码有什么问题?

来自分类Dev

如何通过单击Java Swing中JMenuBar的另一个子菜单来清除JFrame区域?

来自分类Dev

更改下一个元素时,ArrayList / List中的Java上一个元素将被覆盖

来自分类Dev

更改下一个元素时,ArrayList / List中的Java上一个元素将被覆盖

来自分类Dev

如何编写 Java 代码将 Excel 中的表格一个下一个复制十次

Related 相关文章

  1. 1

    当用户在 Java Swing 中单击按钮时从另一个类创建一个新对象

  2. 2

    如何禁用一个按钮而不是Java Swing中的全部按钮?

  3. 3

    单击一个按钮将调用JAVA Swing中另一个按钮的actionListener

  4. 4

    如何让按钮创建一个包含java swing中表单内容的文本文档?

  5. 5

    Java流在完成上一个之前开始下一个映射

  6. 6

    用Java Swing创建一个窗口

  7. 7

    如何从一个对象和一个对象添加一个Swing组件到arraylist中的一个Swing组件中?

  8. 8

    如何在Java Swing中重定向到另一个窗口?

  9. 9

    如何从NetBeans中的另一个类方法调用Java swing Jpanel?

  10. 10

    在Swing Java中打开另一个框架时如何禁用根框架

  11. 11

    Java Swing-如何从另一个类获取TextField中的文本值

  12. 12

    Java Swing按钮actionEvent

  13. 13

    通过按钮Java Swing打开一个新面板

  14. 14

    Java Swing 中的 GridBagLayout

  15. 15

    Java中的Swing DJnative Swing示例

  16. 16

    Java Swing GridBagLayout() 跨越一个对象 3 行不起作用

  17. 17

    如何从另一个子 JPanel (Java Swing) 中的输入触发一个子 JPanel 中的操作?

  18. 18

    将所有java swing gui放在一个类中是正常的吗?

  19. 19

    一个JButton中的Java Swing保留插图的更改边框颜色

  20. 20

    将所有java swing gui放在一个类中是正常的吗?

  21. 21

    在Java Swing中定位对象

  22. 22

    使用Java解析特定节点的xml后尝试获取节点的下一个和上一个同级

  23. 23

    使用Java解析特定节点的xml后尝试获取节点的下一个和上一个同级

  24. 24

    在Java Integer数组中获取下一个索引

  25. 25

    如何在Java Swing中创建一个hello世界?我的代码有什么问题?

  26. 26

    如何通过单击Java Swing中JMenuBar的另一个子菜单来清除JFrame区域?

  27. 27

    更改下一个元素时,ArrayList / List中的Java上一个元素将被覆盖

  28. 28

    更改下一个元素时,ArrayList / List中的Java上一个元素将被覆盖

  29. 29

    如何编写 Java 代码将 Excel 中的表格一个下一个复制十次

热门标签

归档