首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >显示来自高级for循环的文本字段中的数据

显示来自高级for循环的文本字段中的数据
EN

Stack Overflow用户
提问于 2022-11-09 14:49:09
回答 1查看 44关注 0票数 -1

A如下面的代码所示,当按钮被按下时,我想要将数据输入到textfield中,此时我要将其打印为控制台,如何添加到textfield?是text.add吗?

代码语言:javascript
复制
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import javax.swing.*;


public class displayGui extends JFrame implements WindowListener, ActionListener {

    JButton showData;

    JButton hideData;

    private static final int FRAME_WIDTH = 100;
    private static final int FRAME_HEIGHT = 100;
    JTextField text = new JTextField(20);
    ArrayList<Phone> phones = new ArrayList<>();
    public displayGui() {

        phones.add(new Phone("Sony", "Experia X", 32, 12.5 , 4.6 , "Yes" , 150));
        phones.add(new Phone("Sony", "Experia Y", 64, 14.2 , 5.6 , "Yes" , 175));
        phones.add(new Phone("Samsung", "Galaxy M", 64, 14.5 , 5.4 , "Yes" , 180));
        phones.add(new Phone("Nokia", "3330", 16, 13.2 , 2.3 , "No" , 90));
        phones.add(new Phone("Motorola", "M1", 8, 11.3 , 4.9 , "Yes" , 100));
        phones.add(new Phone("Iphone", "6", 32, 13.5 , 6.4 , "Yes" , 250));
        phones.add(new Phone("Alcatel", "A3", 8, 9.3 , 2.4 , "No" , 50));
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();

        addWindowListener(this);
        showData = new JButton("Show Data");
        add(showData);
        panel.add(text);
        showData.addActionListener(this);


        panel.add(showData);
        hideData = new JButton("Hide Data");
        panel.add(hideData);
        hideData.addActionListener(this);
        frame.add(panel);

        frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    @Override

    public void actionPerformed(ActionEvent e) {
        if(e.getSource().equals(showData)) {
            if (showData.isSelected()){

                for (Phone phone : phones){
                    System.out.println("Phone Make: " + phone.getMake());
                    System.out.println("Phone Model: " + phone.getModel());
                    System.out.println("Phone Memory: " + phone.getMemory());
                    System.out.println("Phone Camera: " + phone.getCamera());
                    System.out.println("Phone screen-size: " + phone.getScreensize());
                    System.out.println("Is the phone a smart phone: " + phone.getSmart());
                    System.out.println("The phone costs: " + phone.getPrice());
                };

            }
        }



        for (Phone phone : phones){
            System.out.println("Phone Make: " + phone.getMake());
            System.out.println("Phone Model: " + phone.getModel());
            System.out.println("Phone Memory: " + phone.getMemory());
            System.out.println("Phone Camera: " + phone.getCamera());
            System.out.println("Phone screen-size: " + phone.getScreensize());
            System.out.println("Is the phone a smart phone: " + phone.getSmart());
            System.out.println("The phone costs: " + phone.getPrice());
        }

        text.setText("Testing");

    }

    @Override
    public void windowOpened(WindowEvent e) {

    }

    @Override
    public void windowClosing(WindowEvent e) {
        dispose();
        System.exit(0);
    }

    @Override
    public void windowClosed(WindowEvent e) {

    }

    @Override
    public void windowIconified(WindowEvent e) {

    }

    @Override
    public void windowDeiconified(WindowEvent e) {

    }

    @Override
    public void windowActivated(WindowEvent e) {

    }

    @Override
    public void windowDeactivated(WindowEvent e) {

    }
}
代码语言:javascript
复制
import java.io.*;
import java.util.ArrayList;

public class Tester {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        ArrayList<Phone> phones = new ArrayList<>();
        phones.add(new Phone("Sony", "Experia X", 32, 12.5 , 4.6 , "Yes" , 150));
        phones.add(new Phone("Sony", "Experia Y", 64, 14.2 , 5.6 , "Yes" , 175));
        phones.add(new Phone("Samsung", "Galaxy M", 64, 14.5 , 5.4 , "Yes" , 180));
        phones.add(new Phone("Nokia", "3330", 16, 13.2 , 2.3 , "No" , 90));
        phones.add(new Phone("Motorola", "M1", 8, 11.3 , 4.9 , "Yes" , 100));
        phones.add(new Phone("Iphone", "6", 32, 13.5 , 6.4 , "Yes" , 250));
        phones.add(new Phone("Alcatel", "A3", 8, 9.3 , 2.4 , "No" , 50));

        try {
            System.out.println("Check to see if file exists");
            FileInputStream fileIn = new FileInputStream("phone.ser");
            System.out.println("It exists");
            ObjectInputStream objectIn = new ObjectInputStream(fileIn);
            System.out.println("Reading now");


            phones = (ArrayList<Phone>) objectIn.readObject();
            for (Phone phone : phones){
                System.out.println("Phone Make: " + phone.getMake());
                System.out.println("Phone Model: " + phone.getModel());
                System.out.println("Phone Memory: " + phone.getMemory());
                System.out.println("Phone Camera: " + phone.getCamera());
                System.out.println("Phone screen-size: " + phone.getScreensize());
                System.out.println("Is the phone a smart phone: " + phone.getSmart());
                System.out.println("The phone costs: " + phone.getPrice());
            }

            objectIn.close();
            } catch (FileNotFoundException e1) {
            System.out.println("file does not exist");

            try {
                System.out.println("Creating it now ....");
                FileOutputStream fileOut = new FileOutputStream("phone.ser");

                ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);

                objectOut.writeObject(phones);

                objectOut.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            ///deserialization///
            try {
                FileInputStream fileIn = new FileInputStream("phone.ser");

                ObjectInputStream objectIn = new ObjectInputStream(fileIn);
                Phone newPhone = (Phone) objectIn.readObject();

                objectIn.close();
                System.out.println("Phone Make: " + newPhone.getMake());
                System.out.println("Phone Model: " + newPhone.getModel());
                System.out.println("Phone Memory: " + newPhone.getMemory());
                System.out.println("Phone Camera: " + newPhone.getCamera());
                System.out.println("Phone screen-size: " + newPhone.getScreensize());
                System.out.println("Is the phone a smart phone: " + newPhone.getSmart());
                System.out.println("The phone costs: " + newPhone.getPrice());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
代码语言:javascript
复制
import java.io.*;
import java.util.ArrayList;

public class MainSer {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        new displayGui();

        ArrayList<Phone> phones = new ArrayList<>();
        phones.add(new Phone("Sony", "Experia X", 32, 12.5 , 4.6 , "Yes" , 150));
        phones.add(new Phone("Sony", "Experia Y", 64, 14.2 , 5.6 , "Yes" , 175));
        phones.add(new Phone("Samsung", "Galaxy M", 64, 14.5 , 5.4 , "Yes" , 180));
        phones.add(new Phone("Nokia", "3330", 16, 13.2 , 2.3 , "No" , 90));
        phones.add(new Phone("Motorola", "M1", 8, 11.3 , 4.9 , "Yes" , 100));
        phones.add(new Phone("Iphone", "6", 32, 13.5 , 6.4 , "Yes" , 250));
        phones.add(new Phone("Alcatel", "A3", 8, 9.3 , 2.4 , "No" , 50));



        //serialization//
        try {
            FileOutputStream fileOut = new FileOutputStream("phone.ser");
            ObjectOutputStream Out = new ObjectOutputStream(fileOut);
            Out.writeObject(phones);
            Out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ////deserialization///
        try {
            FileInputStream fileIn = new FileInputStream("phone.ser");

            ObjectInputStream objectIn = new ObjectInputStream(fileIn);

            phones = (ArrayList<Phone>) objectIn.readObject();
            for (Phone phone : phones){
                System.out.println("Phone Make: " + phone.getMake());
                System.out.println("Phone Model: " + phone.getModel());
                System.out.println("Phone Memory: " + phone.getMemory());
                System.out.println("Phone Camera: " + phone.getCamera());
                System.out.println("Phone screen-size: " + phone.getScreensize());
                System.out.println("Is the phone a smart phone: " + phone.getSmart());
                System.out.println("The phone costs: " + phone.getPrice());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        }
    }
代码语言:javascript
复制
import java.io.Serializable;

public class Phone implements Serializable {
    private String make;
    private String model;
    private double memory;
    private double camera;
    private double screensize;
    private String smart;
    private int price;

    public Phone(String make , String model , double memory , double camera, double screensize, String smart , int price){
        this.make = make;
        this.model = model;
        this.memory = memory;
        this.camera = camera;
        this.screensize = screensize;
        this.smart = smart;
        this.price = price;

    }

    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public double getMemory() {
        return memory;
    }

    public double getCamera() {
        return camera;
    }

    public double getScreensize() {
        return screensize;
    }

    public String getSmart() {
        return smart;
    }

    public int getPrice() {
        return price;
    }
}

当我运行它时,我现在让它在控制台上运行。但需要输入到文本字段中。谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-09 17:10:40

在我看来,你看过一本旧的Swing教程。Swing应用程序不需要扩展类JFrame,也不需要实现WindowListener

我建议您在JTable中而不是在文本字段中显示数据。

您的Phone类可以是记录

代码语言:javascript
复制
import java.io.Serializable;

public record Phone(String make,
                    String model,
                    double memory,
                    double camera,
                    double screensize,
                    String smart,
                    int price) implements Serializable {

    public static int getFieldCount() {
        return 7;
    }
}

GUI代码中使用了fieldCount方法。(见下文)

我使用一个自定义表模型来显示Phone对象的列表。

从Java 8开始,我更喜欢使用ActionListener实现方法参考

我创建了两个表model_s -一个空的和一个非空的。单击_Show数据按钮时,我设置非空模型,单击隐藏数据按钮时设置空模型。

代码语言:javascript
复制
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class DisplayGui {
    private PhoneModel emptyModel;
    private PhoneModel model;
    private JTable table;

    private void buildAndDisplayGui() {
        JFrame frame = new JFrame("Phones");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createTable(), BorderLayout.CENTER);
        frame.add(createButtons(), BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createButtons() {
        JPanel panel = new JPanel();
        JButton showData = new JButton("Show Data");
        showData.addActionListener(this::showData);
        panel.add(showData);
        JButton hideData = new JButton("Hide Data");
        hideData.addActionListener(this::hideData);
        panel.add(hideData);
        return panel;
    }

    private void createModel() {
        model = new PhoneModel(new Phone("Sony", "Experia X", 32, 12.5 , 4.6 , "Yes" , 150),
                               new Phone("Sony", "Experia Y", 64, 14.2 , 5.6 , "Yes" , 175),
                               new Phone("Samsung", "Galaxy M", 64, 14.5 , 5.4 , "Yes" , 180),
                               new Phone("Nokia", "3330", 16, 13.2 , 2.3 , "No" , 90),
                               new Phone("Motorola", "M1", 8, 11.3 , 4.9 , "Yes" , 100),
                               new Phone("Iphone", "6", 32, 13.5 , 6.4 , "Yes" , 250),
                               new Phone("Alcatel", "A3", 8, 9.3 , 2.4 , "No" , 50));
    }

    private JScrollPane createTable() {
        createModel();
        emptyModel = new PhoneModel();
        table = new JTable(emptyModel);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        JScrollPane scrollPane = new JScrollPane(table);
        return scrollPane;
    }

    private void hideData(ActionEvent event) {
        table.setModel(emptyModel);
    }

    private void showData(ActionEvent event) {
        table.setModel(model);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new DisplayGui().buildAndDisplayGui());
    }
}

class PhoneModel extends AbstractTableModel {
    private List<Phone> phones;

    public PhoneModel(Phone... phones) {
        this(Arrays.asList(phones));
    }

    public PhoneModel(List<Phone> phones) {
        this.phones = phones;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        Class<?> theClass;
        switch (columnIndex) {
            case 0:
            case 1:
            case 5:
                theClass = String.class;
                break;
            case 2:
            case 3:
            case 4:
                theClass = Double.class;
                break;
            case 6:
                theClass = Integer.class;
                break;
            default:
                throw new ArrayIndexOutOfBoundsException(columnIndex);
        }
        return theClass;
    }

    @Override
    public int getColumnCount() {
        return Phone.getFieldCount();
    }

    @Override
    public String getColumnName(int column) {
        String name;
        switch (column) {
            case 0:
                name = "Make";
                break;
            case 1:
                name = "Model";
                break;
            case 2:
                name = "Memory";
                break;
            case 3:
                name = "Camera";
                break;
            case 4:
                name = "Screen Size";
                break;
            case 5:
                name = "Smart";
                break;
            case 6:
                name = "Price";
                break;
            default:
                throw new ArrayIndexOutOfBoundsException(column);
        }
        return name;
    }

    @Override
    public int getRowCount() {
        return phones == null ? 0 : phones.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Phone phone = phones.get(rowIndex);
        Object val;
        switch (columnIndex) {
            case 0:
                val = phone.make();
                break;
            case 1:
                val = phone.model();
                break;
            case 2:
                val = Double.valueOf(phone.memory());
                break;
            case 3:
                val = Double.valueOf(phone.camera());
                break;
            case 4:
                val = Double.valueOf(phone.screensize());
                break;
            case 5:
                val = phone.smart();
                break;
            case 6:
                val = Integer.valueOf(phone.price());
                break;
            default:
                throw new ArrayIndexOutOfBoundsException(columnIndex);
        }
        return val;
    }
}

隐藏的数据如下所示:

(这是最初的显示,因为我最初设置了空表模型。)

所显示的数据:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74376800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档