【问题标题】:Scroll Pane can't be added, no error displayed无法添加滚动窗格,不显示错误
【发布时间】:2013-11-17 15:40:43
【问题描述】:

我在这里阅读了许多其他问题,都提出了相同的建议,但它仍然对我不起作用,根本没有任何反应。

我的代码是这样的:

final JTextArea ta = new JTextArea();
ta.setPreferredSize(new Dimension(310, 325));
ta.setMinimumSize(new Dimension(310, 325));
ta.setEditable(false);
ta.setFont(new Font("Tahoma", Font.PLAIN, 11));

JScrollPane sp = new JScrollPane(ta);
contentPane.add(sp);

contentPane 在程序开始时设置

contentPane = new JPanel();
contentPane.setBackground(Color.GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);

提前致谢:)

编辑:我做了一些调整,现在出现了滚动窗格,但是当它出现时 textArea 因某种原因消失了.. 这是 pastebin 中的整个程序,只需搜索 scrollPane 或 textArea。

http://pastebin.com/4hS85zZt

谢谢!!

【问题讨论】:

标签: java swing scroll pane


【解决方案1】:

JScrollPane 上使用setPreferedSize()setMinimumSize() 方法。不要在JTextArea 上直接使用它们,因为它不能滚动。所以使用

JScrollPane sp = new JScrollPane(ta);
sp.setPreferredSize(new Dimension(310, 325));
sp.setMinimumSize(new Dimension(310, 325));

而不是

JTextArea ta = new JTextArea();
ta.setPreferredSize(new Dimension(310, 325));
ta.setMinimumSize(new Dimension(310, 325));

你的 scrollPane 就可以工作了。

【讨论】:

  • Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?(是的。)文本区域的大小可以通过行数和列数以及字体大小来建议。
  • 这似乎也不起作用。难道是我在 WindowBuilder (eclipse) 中使用 GroupLayout 吗?抱歉,在 Java Swing 中还是很新的。
  • @GiwrgosFakoukakis:我们很乐意为您提供进一步的帮助,但如果没有当前代码,任何人都可以猜测您现在的问题是什么。请考虑创建一个 small 程序来为我们编译、运行和显示您的问题,sscce。我同意,在您更了解 Swing 之前,请避免使用 GroupLayout 和 GUI 构建实用程序。
  • @Hovercraft Full Of Eels:我编辑了我的帖子,请再看一遍,非常感谢您的帮助。谢谢!顺便说一句,我很欣赏整体建议,因为我是 Java Swing 的新手,而不是 java
  • @GiwrgosFakoukakis:请在您的问题中此处发布您的代码,而不是在可能而且经常会过时的链接中。请重新阅读sscce 链接。我们要求您创建一个程序,一个可以编译、运行和重现您的问题的小程序。我们不想看到你的整个节目。请记住,我们都是有工作、有家庭、有生活的志愿者。我们感谢您能做的任何事情,以便更轻松地为您提供帮助。
【解决方案2】:

您的代码存在一些问题:

  • 您正在设置 JTextArea 的 preferredSize——这是您永远不应该做的事情。如果你把它放在一个 JScollPane 中,如果添加了几行文本,文本区域现在就无法增长,因此滚动将毫无用处。这一切已经在 cmets 中对您的问题的一个答案进行了说明,但您忽略了它们 - 为什么?
  • 而是通过其构造函数设置 JTextArea 的列和行。
  • 您正在将 MouseListener 添加到 JButton,这是您几乎不应该做的事情。而是使用 ActionListener,因为教程会告诉你。
  • 您将 JTextArea 添加到 JScrollPane,然后将 JTextArea 重新添加到 JScrollPane - 为什么?
  • 您要在没有 JScrollPane 的情况下将 JTextArea 添加到 GUI,然后将其添加到 JScrollPane - 不要这样做。您只能将组件添加到一个容器中。只需将其添加到 JScrollPane,然后将 JScrollPane 添加到 GUI,即可完成。
  • 在您了解 Swing 和布局管理器之前,您正在使用 Windows GUI 构建器工具。不要这样做。在滥用这些工具之前先学习使用 Swing 进行编码,从而让自己陷入困境。

你的整个程序:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;

public class RateTesterWindow extends JFrame {

   private JPanel contentPane;
   private JTextField textField_1;
   private JTextField textField;

   /**
    * Launch the application.
    */
   public static void main(String[] args) {
      EventQueue.invokeLater(new Runnable() {
         public void run() {
            try {
               RateTesterWindow frame = new RateTesterWindow();
               frame.setVisible(true);
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      });
   }

   /**
    * Create the frame.
    */
   public RateTesterWindow() {
      setResizable(false);
      setTitle("L2PRIDE RATE TESTER v0.1");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setBounds(100, 100, 350, 377);
      contentPane = new JPanel();
      contentPane.setBackground(Color.GRAY);
      contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
      setContentPane(contentPane);

      JLabel lblRateTester = new JLabel("RATE TESTER");
      lblRateTester.setFont(new Font("Tahoma", Font.BOLD, 18));

      JSeparator separator = new JSeparator();
      separator.setBackground(Color.BLACK);

      final JLabel lblPleaseEnterRate = new JLabel("Rate:");
      lblPleaseEnterRate.setFont(new Font("Tahoma", Font.BOLD, 11));

      final JRadioButton rdbtnDreadItem = new JRadioButton("Dread Item");
      rdbtnDreadItem.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent e)
         {
            if (rdbtnDreadItem.isSelected())
            {
               textField.setText("-----");
               textField.setEditable(false);
            }
            else
            {
               textField.setText("");
               textField.setEditable(true);
            }
         }
      });
      rdbtnDreadItem.setToolTipText("Will use dread item chances like they are in game.");

      JLabel lblScrolls = new JLabel("Scrolls:");
      lblScrolls.setFont(new Font("Tahoma", Font.BOLD, 11));

      final JLabel lblResults = new JLabel("ABOUT:");
      lblResults.setFont(new Font("Tahoma", Font.BOLD, 12));


      JSeparator separator_1 = new JSeparator();

      JSeparator separator_2 = new JSeparator();
      separator_2.setBackground(Color.BLACK);

      JSeparator separator_3 = new JSeparator();
      separator_3.setBackground(Color.LIGHT_GRAY);

      textField_1 = new JTextField();
      textField_1.setColumns(10);

      textField = new JTextField();
      textField.setColumns(10);

      final JTextArea textArea = new JTextArea(10, 30);
      // textArea.setPreferredSize(new Dimension(310, 325));
      // textArea.setMinimumSize(new Dimension(310, 325));
      textArea.setEditable(false);
      textArea.setFont(new Font("Tahoma", Font.PLAIN, 11));
      textArea.setText("some info");

      final JScrollPane scrollPane = new JScrollPane(textArea);
      scrollPane.setVisible(false);

      JButton btnNewButton = new JButton("RUN!");
      btnNewButton.addMouseListener(new MouseAdapter()
      {
         @Override
         public void mouseClicked(MouseEvent e)
         {
            lblResults.setText("RESULTS:");
            if ((!rdbtnDreadItem.isSelected() && !isNumeric(textField.getText())) || !isNumeric(textField_1.getText()) || textField.getText().startsWith("0") || textField_1.getText().startsWith("0") || textField.getText().equals("100"))
            {
               textArea.setText("Rate and scrolls must be valid numbers.");
            }
            else
            {
               textArea.setText(doYourMagic(rdbtnDreadItem.isSelected() ? 60 : Integer.parseInt(textField.getText()), Integer.parseInt(textField_1.getText()), rdbtnDreadItem.isSelected()));
               // scrollPane.setViewportView(textArea);
               scrollPane.setVisible(true);
            }
         }
      });

      GroupLayout gl_contentPane = new GroupLayout(contentPane);
      gl_contentPane.setHorizontalGroup(
         gl_contentPane.createParallelGroup(Alignment.TRAILING)
            .addComponent(separator, GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
            .addGroup(gl_contentPane.createSequentialGroup()
               .addGap(185)
               .addComponent(separator_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
               .addContainerGap(158, Short.MAX_VALUE))
            .addGroup(gl_contentPane.createSequentialGroup()
               .addGap(103)
               .addComponent(lblRateTester)
               .addContainerGap(120, Short.MAX_VALUE))
            .addGroup(gl_contentPane.createSequentialGroup()
               .addGap(30)
               .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                  .addGroup(gl_contentPane.createSequentialGroup()
                     .addComponent(lblPleaseEnterRate)
                     .addPreferredGap(ComponentPlacement.RELATED)
                     .addComponent(textField, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
                     .addGap(16)
                     .addComponent(lblScrolls)
                     .addPreferredGap(ComponentPlacement.RELATED)
                     .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
                     .addGap(18)
                     .addComponent(rdbtnDreadItem))
                  .addComponent(separator_3, GroupLayout.PREFERRED_SIZE, 272, GroupLayout.PREFERRED_SIZE))
               .addContainerGap(41, Short.MAX_VALUE))
            .addGroup(gl_contentPane.createSequentialGroup()
               .addGap(135)
               .addComponent(btnNewButton)
               .addContainerGap(151, Short.MAX_VALUE))
            .addGroup(gl_contentPane.createSequentialGroup()
               .addContainerGap()
               .addComponent(separator_2, GroupLayout.PREFERRED_SIZE, 309, GroupLayout.PREFERRED_SIZE)
               .addContainerGap(24, Short.MAX_VALUE))
            .addGroup(gl_contentPane.createSequentialGroup()
               .addGap(136)
               .addComponent(lblResults)
               .addContainerGap(162, Short.MAX_VALUE))
            .addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
               .addContainerGap()
               .addComponent(textArea, GroupLayout.PREFERRED_SIZE, 299, GroupLayout.PREFERRED_SIZE)
               .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 16, GroupLayout.PREFERRED_SIZE)
               .addContainerGap())
      );
      gl_contentPane.setVerticalGroup(
         gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
               .addComponent(lblRateTester)
               .addPreferredGap(ComponentPlacement.RELATED)
               .addComponent(separator, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
               .addPreferredGap(ComponentPlacement.RELATED)
               .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                  .addComponent(lblPleaseEnterRate)
                  .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                     .addComponent(lblScrolls, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                     .addComponent(textField, GroupLayout.PREFERRED_SIZE, 14, GroupLayout.PREFERRED_SIZE))
                  .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, 14, GroupLayout.PREFERRED_SIZE)
                  .addComponent(rdbtnDreadItem, GroupLayout.PREFERRED_SIZE, 14, GroupLayout.PREFERRED_SIZE))
               .addGap(18)
               .addComponent(separator_3, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
               .addPreferredGap(ComponentPlacement.UNRELATED)
               .addComponent(btnNewButton)
               .addPreferredGap(ComponentPlacement.UNRELATED)
               .addComponent(separator_2, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
               .addPreferredGap(ComponentPlacement.RELATED)
               .addComponent(lblResults)
               .addPreferredGap(ComponentPlacement.RELATED)
               .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                  .addGroup(gl_contentPane.createSequentialGroup()
                     .addComponent(textArea, GroupLayout.PREFERRED_SIZE, 163, GroupLayout.PREFERRED_SIZE)
                     .addGap(18)
                     .addComponent(separator_1, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE))
                  .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 163, GroupLayout.PREFERRED_SIZE)))
      );
      contentPane.setLayout(gl_contentPane);
   }

   private String doYourMagic(int rate, int scrolls, boolean dread)
   {
      int success = 0;
      int row = 0, highRow = 0;
      String magic = "";
      Random rand = new Random();

      for (int i = 0; i < scrolls; i++)
      {
         int chance = rand.nextInt(99);
         if (dread && row > 0)
            rate = rate - (5 * row);
         if (chance >= rate)
         {
            row = 0;
         }
         else
         {
            success++;
            if (++row > highRow)
               highRow = row;
         }

         magic = magic + "SCROLL USED: <--- Roll: " + chance + " <--- Scroll Rate: " + rate + "% <--- " + (row > 0 ? "Success" : "Fail") + "\r\n";
         if (dread) // reset dread rate
            rate = 60;
      }

      magic = magic + "\r\n~~~~ TEST RESULTS OF " + rate + "% RATE USING " + scrolls + " SCROLLS ~~~~\r\n";
      magic = magic + "Total Success: " + success + "\r\n";
      magic = magic + "Highest Success Row: " + highRow + "\r\n";
      return magic;
   }

   private boolean isNumeric(String str)  
   {  
      try  
      {  
         Integer.parseInt(str);
      }  
      catch (NumberFormatException nfe)  
      {  
         return false;  
      }
      return true;  
   }
}

编辑
一个示例sscce 在使用更简单布局的 GUI 中显示 JTextArea:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ScrollPaneEg {
   public static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, "
         + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, "
         + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "
         + "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. "
         + "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ";

   public static void main(String[] args) {
      final JTextArea textarea = new JTextArea(10, 30);
      textarea.setWrapStyleWord(true);
      textarea.setLineWrap(true);
      textarea.setEditable(false);
      textarea.setFocusable(false);
      JScrollPane scrollpane = new JScrollPane(textarea);
      scrollpane
            .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

      JPanel topPanel = new JPanel();
      topPanel.add(scrollpane);
      topPanel.add(new JButton(new AbstractAction("Press Me") {

         @Override
         public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < 200; i++) {
               textarea.append(LOREM_IPSUM);
            }
         }
      }));

      JPanel mainPanel = new JPanel(new BorderLayout(4, 4));
      mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));

      mainPanel.add(topPanel, BorderLayout.PAGE_START);
      mainPanel.add(scrollpane, BorderLayout.CENTER);

      JFrame frame = new JFrame("Layout Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }
}

【讨论】:

  • 感谢您的回答,非常有用。我对这一切真的很陌生,所以对我来说很赤裸裸,我没有意识到它是如此重要并且没有删除preferredsize。我运行你提供的程序,这就是imgur.com/Yw1w4s2 btw 我添加了 setViewportView() 因为我在某处读到它并产生了这种效果.. 我想这总比不可滚动好? :D imgur.com/wm8YQV9
  • @GiwrgosFakoukakis:“我提供”的程序只是您在链接中发布的您的代码。如果您需要更多帮助,那么您真的应该创建并发布sscce
  • 看,即使我设法做到了,我仍然不知道如何修复这个程序..因为我实际上相信它与布局有关(?)你看到第一张截图了吗?知道为什么会这样吗?
  • @GiwrgosFakoukakis:由于我对 GroupLayout 不太熟悉,因此我无法在布局方面为您提供太多帮助。它主要由 GUI 构建器使用,因为它非常适合此操作,但比其他布局管理器更难手动操作。
  • @GiwrgosFakoukakis:有关使用更简单布局的示例,请参阅上面的编辑。
猜你喜欢
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多