0

I read many other questions in here, all suggest the same, still it doesn't work for me, simply nothing happens.

My code is this:

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 is set at beggining of program

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

Thanks in advance :)

EDIT: I made some adjustments, now scrollpane appears, but when it does textArea disappears for some reason.. here's the whole program in pastebin, just search for scrollPane or textArea.

http://pastebin.com/4hS85zZt

THANKS!!

  • 1
    1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Nov 17 '13 at 15:49

2 Answers2

0

Use setPreferedSize() and setMinimumSize() methods on JScrollPane. Don't use them diarectly on JTextArea because of it will not be scrollable. So use

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

instead of

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

and your scrollPane will work.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
alex2410
  • 10,904
  • 3
  • 25
  • 41
  • 2
    See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) The size of a text area can be suggested by the number of rows and columns, combined with the font size. – Andrew Thompson Nov 17 '13 at 15:51
  • That doesn't seem to work either. Could it be that i'm using GroupLayout in WindowBuilder (eclipse)? Sorry still pretty new in Java Swing. – Giwrgos Fakoukakis Nov 17 '13 at 16:38
  • @GiwrgosFakoukakis: we'd love to help you further, but it's anyone's guess what your problem now is without current code. Please consider creating a **small** program that compiles, runs and shows your problem for us, an [sscce](http://sscce.org). And I agree, avoid GroupLayout and GUI-building utilities until you know Swing a bit better. – Hovercraft Full Of Eels Nov 17 '13 at 16:54
  • @Hovercraft Full Of Eels: i edited my post, please take another look, i really appreciate your help. Thank you! Btw i'd appreciate overall suggestions, since i'm new to Java Swing, not to java though <3 – Giwrgos Fakoukakis Nov 17 '13 at 22:47
  • @GiwrgosFakoukakis: please post your code *here* in your question, not in a link that can and often does go stale. Please re-read the [sscce](http://sscce.org) link. We are requesting that you *create* a **new** program, a small one that compiles, runs, and reproduces your problem. We don't want to see your whole program. Please remember that we are all volunteers with work, families, lives. We appreciate anything you can do to make it easier to help you. – Hovercraft Full Of Eels Nov 17 '13 at 22:48
  • I've looked at your code, and it's huge, most of it completely unrelated to your problem. :( – Hovercraft Full Of Eels Nov 17 '13 at 22:52
0

Some problems with your code:

  • You're setting the preferredSize of a JTextArea -- something you should never do. If you put it in a JScollPane, the text area now cannot grow if lines of text are added, and so the scrolling will be useless. This all was already stated in the comments to one of the answers to your question, but you've ignored them -- why?
  • Instead set the JTextArea's columns and rows via its constructor.
  • You're adding a MouseListener to a JButton, something you should almost never do. Instead use an ActionListener as the tutorials will tell you.
  • You're adding the JTextArea to the JScrollPane and then re-adding the JTextArea to the JScrollPane -- why?
  • You're adding the JTextArea to the GUI without the JScrollPane and then adding it to the JScrollPane -- don't do this. You must add a component to one container only. Just add it to the JScrollPane, and add the JScrollPane to the GUI, and be done with it.
  • You're using a windows GUI builder tool before you understand Swing and layout managers. Don't do this. Learn to code with Swing first before misusing these tools and thereby painting yourself in a corner.

Your whole program:

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

Edit
An example sscce that displays a JTextArea in a GUI that uses much simpler layouts:

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);
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks for your answer, really useful. I'm really new to all this, so bare with me, i didn't realize it was so significant and didn't remove preferredsize. I run the program you provided, this is what happens http://imgur.com/Yw1w4s2 btw i added setViewportView() because i read it somewhere and it had this effect.. which i guess was better than not scrollable at all? :D http://imgur.com/wm8YQV9 – Giwrgos Fakoukakis Nov 17 '13 at 23:51
  • @GiwrgosFakoukakis: the program that "I provided" is simply **your** code that you've posted in the link. If you need more help, then you really should create and post an [sscce](http://sscce.org). – Hovercraft Full Of Eels Nov 18 '13 at 00:26
  • See, even if i somehow manage to do that, i still wouldn't know how to fix it this program.. because i actually believe it has something to do with the layout (?) Did you see the 1st screenshot? Any idea why it behaves like that? – Giwrgos Fakoukakis Nov 18 '13 at 00:32
  • @GiwrgosFakoukakis: I can't help you much with the layout since I'm not that familiar with the GroupLayout. It is mainly used by GUI builders because it lends itself well to this, but is much harder than the other layout managers to manipulate by hand. – Hovercraft Full Of Eels Nov 18 '13 at 00:38
  • @GiwrgosFakoukakis: for an example of use of simpler layouts, please see edit above. – Hovercraft Full Of Eels Nov 18 '13 at 01:03