当前位置: 代码迷 >> java >> JTextArea追加
  详细解决方案

JTextArea追加

热度:90   发布时间:2023-07-31 12:03:19.0

我正在用一些代码对不同类型的啤酒进行一些计算。 我有一个使用GUI的主类,并具有JTextArea来打印输出。 在主类中调用append可以很好地工作,但是一旦我尝试从外部类中调用append来写入文本区域。没有雪茄。我已经工作了一段时间了,根本不知道。 相当多的代码,但是我认为修复很简单,我想我正在解决它,将NewFileOpener扩展到LagerChooser是否有意义? 还是应该扩展jpanel?

谢谢您的帮助!!

public class NewFinalOpener extends JPanel implements ActionListener {

JFileChooser fc;
private CustomPanel customPanel;
public CustomTextArea customTextArea = new CustomTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList<String> namesForGeneration;
private boolean namesRead = false;

void displayGUI() {

    JFrame frame = new JFrame("Binary Brewing! " + "Version:" + versionID);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel contentPane = new JPanel();
    contentPane.setLayout(new BorderLayout(5, 5));
    contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
    customPanel = new CustomPanel();
//      customTextArea = new CustomTextArea();
    customTextArea
            .append("                                                     Program progress and/or errors will display below:");
    customTextArea
            .append("\n"
                    + "----------------------------------------------------------------------------------------------------");
    customTextArea.append("\n" + "\n"
            + "To Enable Beer recipe Generation please read in Name file!" + "\n");
    contentPane.add(customTextArea, BorderLayout.CENTER);
    contentPane.add(customPanel, BorderLayout.LINE_START);

    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);



}




public static void main(String[] args) {

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            new NewFinalOpener().displayGUI();
        }
    };
    EventQueue.invokeLater(runnable);
}

class CustomPanel extends JPanel implements ActionListener {
    private static final int GAP = 5;
    JButton openButton, b2, b3, b4;

    public CustomPanel() {
        fc = new JFileChooser();
        setOpaque(true);
        setBackground(Color.WHITE);
        setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
        openButton = new JButton("Choose names file");
        openButton.setVerticalTextPosition(AbstractButton.CENTER);
        openButton.setHorizontalTextPosition(AbstractButton.LEADING);

        openButton.setMnemonic(KeyEvent.VK_D);
        openButton.setActionCommand("open");
        openButton.setEnabled(true);
        openButton.addActionListener(this);
        add(openButton);

        b2 = new JButton("Ale");
        b2.setVerticalTextPosition(AbstractButton.CENTER);
        b2.setHorizontalTextPosition(AbstractButton.LEADING);

        b2.setMnemonic(KeyEvent.VK_D);
        b2.setActionCommand("ale");

        if(namesRead == false){
            b2.setEnabled(false);
        }

        b2.addActionListener(this);
        add(b2);

        b3 = new JButton("Lager");
        b3.setVerticalTextPosition(AbstractButton.CENTER);
        b3.setHorizontalTextPosition(AbstractButton.LEADING);

        b3.setMnemonic(KeyEvent.VK_D);
        b3.setActionCommand("lager");

        if(namesRead == false){
            b3.setEnabled(false);
        }

        b3.addActionListener(this);
        add(b3);

        b4 = new JButton("Random");
        b4.setVerticalTextPosition(AbstractButton.BOTTOM);
        b4.setHorizontalTextPosition(AbstractButton.LEADING);

        b4.setMnemonic(KeyEvent.VK_D);
        b4.setActionCommand("lager");

        if(namesRead == false){
            b4.setEnabled(false);
        }

        b4.addActionListener(this);
        add(b4);



    }




    public Dimension getPreferredSize() {
        return (new Dimension(200, 100));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String action = e.getActionCommand();
        if (action.equals("open")) {
            int returnVal = fc.showOpenDialog(NewFinalOpener.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File file = fc.getSelectedFile();
                try {

                    BufferedReader br = new BufferedReader(new FileReader(
                            fc.getSelectedFile()));
                    String line = " ";

                    namesForGeneration = new ArrayList<String>();
                    while (br.ready() == true) {
                        line = br.readLine();
                        namesForGeneration.add(line);

                    }

                    if (br.ready() == false) {
                        customTextArea.append("\n"
                                + "Successfully read all names!" + " "
                                + file + "\n");
                        customTextArea.append("\n" + "Beer Recipe Generator Enabled!" + "\n");
                        namesRead = true;
                        b2.setEnabled(true);
                        b3.setEnabled(true);
                        b4.setEnabled(true);
                        openButton.setEnabled(false);
                        customTextArea
                                .append("\n"
                                        + "---------------------------------------------------------");

                        br.close();
                    }

                } catch (Exception f) {
                    JOptionPane.showMessageDialog(null, e);
                }

            } else {
                customTextArea.append("Open command cancelled by user."
                        + "\n");
            }
        }

        if(action.equalsIgnoreCase("lager")){
            customTextArea.append("\n" + "\n "+ "Ale recipe generation selected proceeding to sub categories...");
            b2.setEnabled(false);
            b3.setEnabled(false);
            b4.setEnabled(false);
            createLagerFrame();

        }

    }




    protected void createLagerFrame(){
        LagerChooser l1 = new LagerChooser();

    }



}

class CustomTextArea extends JTextArea {

    private static final int GAP = 5;

    public CustomTextArea() {

        setEditable(false);
        setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
    }

    public Dimension getPreferredSize() {
        return (new Dimension(800, 800));
    }
}





@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub

}

public void setCustomText(String text){
    customTextArea.append(text);
}


  }

和需要附加到JTextarea的类

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

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

 public class LagerChooser extends NewFinalOpener{


public LagerChooser() {



}
public void tellCustom(String line){
    setCustomText(line);
}
 }

您可以使用:

public static final PrintStream OUT = System.out;
public CustomPanel() throws Throwable
{
    ...
    System.setOut(new PrintStream(new OutputStream(){

                          @Override
                          public void write(int oneByte) throws IOException {
                              if(oneByte<0||oneByte>255)
                                  return;
                              write(new byte[]{(byte)oneByte}, 0, 1);
                          }
                          @Override
                          public void write(byte[] b, int offset, int length) throws IOException {
                              String str = new String(b, offset, length);
                              customTextArea.append(str);
                          }
                      }));

并写入System.out。 它将打印到控制台和文本区域。

PS。 为什么创建自定义textarea类? 您应该使用JTextArea:

customTextArea=new JTextArea();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPrefferedSize(...);

您的代码占用大量内存,对于“简单程序”而言,导出的JAR的大小并不小。 优化的代码:

import java.io.*;
import java.util.*;
class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public JTextArea customTextArea = new JTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList < String > namesForGeneration;
private boolean namesRead = false;
private static final PrintStream SYSOUT = System.out;
public NewFinalOpener() {
    JFrame frame = new JFrame("Binary Brewing! Version:" + versionID);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel contentPane = new JPanel();
    contentPane.setLayout(new BorderLayout(5, 5));
    contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
    customPanel = new CustomPanel();
    customTextArea.setEditable(false);
    customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
    customTextArea.setPreferredSize(new Dimension(800, 800));
    System.setOut(new PrintStream(new OutputStream(){

                          @Override
                          public void write(int oneByte) throws IOException {
                              if(oneByte<0||oneByte>255)
                                  return;
                              write(new byte[]{(byte)oneByte}, 0, 1);
                          }
                          @Override
                          public void write(byte[] b, int offset, int length) throws IOException {
                              String str = new String(b, offset, length);
                              SYSOUT.write(b,offset,length);
                              customTextArea.append(str);
                          }
                      }));
    System.setErr(System.out);
    System.out.println(" Program progress and/or errors will display below:");
    System.out.println("----------------------------------------------------------------------------------------------------\n");
    System.out.println("To Enable Beer recipe Generation please read in Name file!");
    contentPane.add(customTextArea, BorderLayout.CENTER);
    contentPane.add(customPanel, BorderLayout.LINE_START);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new NewFinalOpener();
            }
        });
}
class CustomPanel extends JPanel implements ActionListener {
    private static final int GAP = 5;
    JButton openButton, b2, b3, b4;
    public CustomPanel() {
        setPreferredSize(new Dimension(200, 100));
        fc = new JFileChooser();
        setOpaque(true);
        setBackground(Color.WHITE);
        setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
        openButton = new JButton("Choose names file");
        openButton.setVerticalTextPosition(AbstractButton.CENTER);
        openButton.setHorizontalTextPosition(AbstractButton.LEADING);
        openButton.setMnemonic(KeyEvent.VK_D);
        openButton.setActionCommand("open");
        openButton.setEnabled(true);
        openButton.addActionListener(this);
        add(openButton);
        b2 = new JButton("Ale");
        b2.setVerticalTextPosition(AbstractButton.CENTER);
        b2.setHorizontalTextPosition(AbstractButton.LEADING);
        b2.setMnemonic(KeyEvent.VK_D);
        b2.setActionCommand("ale");
        if (namesRead == false) {
            b2.setEnabled(false);
        }
        b2.addActionListener(this);
        add(b2);
        b3 = new JButton("Lager");
        b3.setVerticalTextPosition(AbstractButton.CENTER);
        b3.setHorizontalTextPosition(AbstractButton.LEADING);
        b3.setMnemonic(KeyEvent.VK_D);
        b3.setActionCommand("lager");
        if (namesRead == false) {
            b3.setEnabled(false);
        }
        b3.addActionListener(this);
        add(b3);
        b4 = new JButton("Random");
        b4.setVerticalTextPosition(AbstractButton.BOTTOM);
        b4.setHorizontalTextPosition(AbstractButton.LEADING);
        b4.setMnemonic(KeyEvent.VK_D);
        b4.setActionCommand("lager");
        if (namesRead == false) {
            b4.setEnabled(false);
        }
        b4.addActionListener(this);
        add(b4);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        String action = e.getActionCommand();
        if (action.equals("open")) {
            int returnVal = fc.showOpenDialog(NewFinalOpener.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                try {
                    BufferedReader br = new BufferedReader(new FileReader(fc.getSelectedFile()));
                    String line = " ";
                    namesForGeneration = new ArrayList < String > ();
                    while (br.ready() == true) {
                        line = br.readLine();
                        namesForGeneration.add(line);
                    }
                    if (br.ready() == false) {
                        System.out.println("Successfully read all names!" + " " + file + "\n");
                        System.out.println("Beer Recipe Generator Enabled!" + "\n");
                        namesRead = true;
                        b2.setEnabled(true);
                        b3.setEnabled(true);
                        b4.setEnabled(true);
                        openButton.setEnabled(false);
                        System.out.println("\n---------------------------------------------------------");
                        br.close();
                    }
                } catch (Throwable f) {
                    f.printStackTrace();
                    JOptionPane.showMessageDialog(null, e);
                }
            } else {
                System.out.println("Open command cancelled by user.");
            }
        }
        if (action.equalsIgnoreCase("lager")) {
            System.out.println("Ale recipe generation selected proceeding to sub categories...");
            b2.setEnabled(false);
            b3.setEnabled(false);
            b4.setEnabled(false);
            createLagerFrame();
        }
    }
    protected void createLagerFrame() {
        LagerChooser l1 = new LagerChooser();
    }
}
}
class LagerChooser extends NewFinalOpener {
public LagerChooser() {}
public void tellCustom(String line) {
    setCustomText(line);
}
}

在主类中创建一个调用append方法的公共方法。 然后从另一个类调用该方法。