簡體   English   中英

Java GUI 存儲在數組列表中

[英]Java GUI storing in an arraylist

使用 GUI 時如何添加、刪除和搜索數組列表中的項目? 我想將用戶輸入添加到程序數組列表中。 另外我如何檢查一個名為 INFO.TXT 的文件是否存在——如果它存在——將 info.txt 文件中的所有信息設置為 TEXTAREA——見下文:

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import javax.swing.*;
import java.io.File;
import java.io.*;
import static java.lang.System.out;

public class FinalMainFrame extends  
 JFrame {
     BufferedReader br = null;
private Container pane;
private JTextField textField;
public FinalMainFrame() {
    pane=getContentPane();
            pane.setLayout(null);

    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile = new JMenu();
    JMenuItem menuFileExit = new     
    JMenuItem();

    menuFile.setText("File");
    menuFileExit.setText("Exit");
    menuFileExit.addActionListener
    (       (ActionEvent e) -> {
        FinalMainFrame.this.windowClosed();
            });
    menuFile.add(menuFileExit);
    menuBar.add(menuFile);

    setTitle("Final Project...");
    setJMenuBar(menuBar);
    setSize(new Dimension(250, 200));


    JLabel label = new JLabel("Enter Info:");
    label.setFont(new Font("Serif", 
    Font.PLAIN, 18));
    pane.add(label);
    label.setLocation(0, 10);
    label.setSize(100, 30);

    textField = new JTextField(20);
    pane.add(textField);
    textField.setSize(100, 30);
    textField.setLocation(120, 10);

    JButton button1 = new JButton("Save");
    pane.add(button1);
    button1.setLocation(30, 70);
    button1.setSize(150, 50);
    button1.addActionListener
    (
        new ActionListener() {
            public void 
     actionPerformed(ActionEvent e) {

  JOptionPane.showMessageDialog(    
   null,"You pressed: " + 
   e.getActionCommand() );
   try{

         FileReader read = new 
         FileReader("info.txt");
         BufferedReader br = new 
         BufferedReader(read);
            String txt = "";            
            String line = br.readLine();
            while (line != null){
                txt += line;
                line = br.readLine();
              out.println(line);
            }


         String text = textField.getText();
        FileWriter stream = new 
        FileWriter("info.txt");
        try (BufferedWriter out = new 
        BufferedWriter(stream)) {
            out.write(text);
   }

        JOptionPane.showMessageDialog( 
        null,"You entered: " + text );
    }
    catch (Exception ex) {}                   
            }
        }
    );   
    this.addWindowListener
    (
        new WindowAdapter() {
            public void 
       windowClosing(WindowEvent e) {

      FinalMainFrame.this.windowClosed();
            }
        }
    );
         }
     protected void windowClosed() {
    System.exit(0);
               }
      }

在談論 GUI 時,您應該想到事件。 因此,在單擊事件等時將用戶輸入添加到您的數組列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM