JTextArea附加

时间:2015-07-19 09:02:18

标签: java swing append jtextarea

我正在研究一些代码来对不同类型的啤酒进行一些计算。我有一个使用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);
}
 }

2 个答案:

答案 0 :(得分:1)

您可以使用:

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。它将打印到控制台和textarea。

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

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

您的代码使用大量内存,导出的JAR的大小对于简单程序&#34;来说并不小。 优化代码:

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);
}
}

答案 1 :(得分:0)

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