JScrollPane仅使用水平滚动条显示内容

时间:2014-01-08 13:27:39

标签: java swing

我想在窗口中显示字符串列表,我试图使用JScrollPane包围的JPanel,因为字符串列表的大小未知。问题是窗口正在水平显示文本,我希望逐行显示。如何解决这个问题?这是我到目前为止编写的代码。

package interface_classes;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

public class ErrorMessageW {

    private JFrame errorMessageW;
    private ArrayList<String> errors;
    private JPanel panel;
    private JScrollPane scrollPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        final ArrayList<String> err = new ArrayList<>();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ErrorMessageW window = new ErrorMessageW(err);
                    window.errorMessageW.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ErrorMessageW(ArrayList<String> err) {
        errors = err;
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        errorMessageW = new JFrame();
        errorMessageW.setTitle("Unfilled forms");
        errorMessageW.setBounds(100, 100, 367, 300);
        errorMessageW.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton btnOk = new JButton("OK");
        btnOk.setBounds(239, 208, 89, 23);
        btnOk.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                errorMessageW.dispose();
            }
        });
        errorMessageW.getContentPane().setLayout(null);
        errorMessageW.getContentPane().add(btnOk);

        scrollPane = new JScrollPane();
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setBounds(10, 10, 330, 175);
        errorMessageW.getContentPane().add(scrollPane);

        panel = new JPanel();
        for(String s : errors){
            JTextArea text = new JTextArea(1,20);
            text.setText(s);
            text.setFont(new Font("Verdana",1,10));
            text.setForeground(Color.RED);
            panel.add(text);

        }   
        scrollPane.setViewportView(panel);
    }

    public JFrame getErrorMessageW() {
        return errorMessageW;
    }

    public void setErrorMessageW(JFrame errorMessageW) {
        this.errorMessageW = errorMessageW;
    }


}

这就是我得到的 enter image description here

这就是我想要的,但使用JScrollPane: enter image description here

3 个答案:

答案 0 :(得分:2)

enter image description here

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ErrorMessageW {

    private JFrame errorMessageW;
    private ArrayList<String> errors;
    private JPanel panel;
    private JScrollPane scrollPane;
    private JTextArea errorMessage = new JTextArea(3, 30);

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        final ArrayList<String> err = new ArrayList<String>();
        err.add("Short String");
        err.add("A very very very very very very very very very very very "
                + "very very very very very very very very very very very "
                + "very very very very very very very very long String");
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    ErrorMessageW window = new ErrorMessageW(err);
                    window.errorMessageW.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ErrorMessageW(ArrayList<String> err) {
        errors = err;
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        errorMessageW = new JFrame();
        JPanel contentPane = new JPanel(new BorderLayout(5, 15));
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
        errorMessage.setLineWrap(true);
        errorMessage.setWrapStyleWord(true);
        JScrollPane jsp = new JScrollPane(
                errorMessage,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
                );
        contentPane.add(jsp, BorderLayout.PAGE_START);

        errorMessageW.add(contentPane);
        errorMessageW.setTitle("Unfilled forms");
        errorMessageW.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JButton btnOk = new JButton("OK");
        btnOk.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent arg0) {
                errorMessageW.dispose();
            }
        });
        JPanel btnConstrain = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        btnConstrain.add(btnOk);
        contentPane.add(btnConstrain, BorderLayout.PAGE_END);

        scrollPane = new JScrollPane();
        scrollPane.setVerticalScrollBarPolicy(
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        contentPane.add(scrollPane, BorderLayout.CENTER);

        DefaultListModel<String> listModel = new DefaultListModel<String>();
        for (String s : errors) {
            listModel.addElement(s);
        }
        final JList<String> errorList = new JList<String>(listModel);
        Dimension preferredSize = new Dimension(errorMessage.getPreferredSize().width,200);
        errorList.setPreferredSize(preferredSize);
        ListSelectionListener errorSelect = new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                errorMessage.setText(errorList.getSelectedValue());
            }
        };
        errorList.addListSelectionListener(errorSelect);
        scrollPane.setViewportView(errorList);
        errorMessageW.pack();
    }

    public JFrame getErrorMessageW() {
        return errorMessageW;
    }

    public void setErrorMessageW(JFrame errorMessageW) {
        this.errorMessageW = errorMessageW;
    }
}

答案 1 :(得分:0)

首先,您可以尝试,而不是创建JTextArea的多个实例,只使用一个并将每个错误附加到它上面:

    JTextArea text = new JTextArea(1, 20);
    text.setFont(new Font("Verdana",1,10));
    text.setForeground(Color.RED);
    for(String s : errors) {
        text.append(s + "\n");
    }
    panel.add(text);

但是,如果您确实需要创建多个JTextArea,则可以使用BoxLayout这样的内容:

    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

答案 2 :(得分:0)

您只需编写一个函数,在ArrayList中的每个其他元素之后添加一个新的行字符作为ArrayList的元素。下面我做了一个测试程序,展示了如何做到这一点。我还检查了oputput。只需粘贴代码并了解代码的工作原理即可。一切顺利!

       import java.util.ArrayList;

   public class TestingArraylist {


static ArrayList<String> errors = new ArrayList<String>();
static final String[] warnings = new String[]{"Error 0 occured","Error 1 occured","Error 2 occured","Error 3 occured","Error 4 occured"};;


   public static void addNewLineToArrayList(String[] elementofarraylist){

     for(int i =0;i<elementofarraylist.length;i++){
     errors.add(elementofarraylist[i]);
     errors.add("\n"); //this is what you need to do!
     }
 }

public static void main(String[] args) {

  addNewLineToArrayList(warnings);
  //checking below if our work has really succeded or not!!
  for(int j =0;j<errors.size();j++){

   System.out.print(errors.get(j));

  }

}

}