首页 > 解决方案 > 在 JOptionPane 内的 JScrollPane 上方添加文本

问题描述

我有以下代码:

            JTextArea textArea = new JTextArea(5, 120);
            textArea.setText("Error message more detail");
            textArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(textArea);
            JOptionPane.showMessageDialog(ScenariosUploader.this, scrollPane, "Error Message", JOptionPane.ERROR_MESSAGE);  

这将创建以下 JOptionPane:

在此处输入图像描述

我的问题是如何在窗格上方添加类似“错误详细信息”的文本?

标签: javaswingjframe

解决方案


与其给showMessageDialog方法提供 scrollPane,不如给它一个面板(使用BorderLayout),其中包含滚动窗格和一个“errorDetail”标签:

public static void main(String[] args) {
    JTextArea textArea = new JTextArea(5, 120);
    textArea.setText("Error message more detail");
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea);

    JPanel panel = new JPanel(new BorderLayout());

    JLabel errorDetailLabel = new JLabel("Error detail:");
    panel.add(errorDetailLabel, BorderLayout.PAGE_START);
    panel.add(scrollPane, BorderLayout.CENTER);

    JOptionPane.showMessageDialog(null, panel, "Error Message", JOptionPane.ERROR_MESSAGE);
}

结果:

预习


推荐阅读