JScrollPane doesn't update scrollbar when window is maximized - java

In my GUI, I have a JSplitPane containing two JTextArea controls enclosed in a JScrollPane, all enclosed in a JFrame.
I am having problems with the scrollbar updating when the window is maximized. The scrollbar updates correctly when the window is minimized, but fails to appear when I try to create a new line in one of the text areas. It updates when I minimize the window, but I am trying to get the scroll bar to update when the window is maximized.
this.text = new JTextArea(15, 70);
this.text.getDocument().addDocumentListener(this);
this.text.setBorder(BorderFactory.createLineBorder(Color.BLACK));
this.text.setLineWrap(true);
//Create lines
JTextArea lines = new JTextArea(15, 2);
lines.setBorder(BorderFactory.createLineBorder(Color.BLACK));
int lineHeight = lines.getRows();
int i = 1;
while (i <= lineHeight + 1) {
lines.append(Integer.toString(i) + "\n");
i++;
}
lines.setEditable(false);
//Pack it all
JSplitPane combo = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, lines,
this.text);
combo.setResizeWeight(0d / 10d);
//Create scrolling area
JScrollPane scroller = new JScrollPane(combo);
scroller.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
I have some more code regarding a menu and putting everything into a frame if that is important. I believe I am using the default layout manager.

Related

How do I limit the width of components of a JScrollPane

I have a JScrollPane with a number of JLabel objects in a panel using a GridBagLayout. Each of the labels is displaying HTML text with rich elements which varies at run time.
I would like all labels to have the same width (driven by the width of the scroll pane) but vary in height depending on their content with the text wrapping (as is handled automatically by JLabel). If the labels exceed the scroll pane's height then a vertical scroll bar should appear.
Here is some sample code to demonstrate the problem:
public class ScrollLabels extends JFrame {
private final JPanel labelPanel = new JPanel(new GridBagLayout());
private final GridBagConstraints c = new GridBagConstraints();
public ScrollLabels() throws HeadlessException {
super("Scroll Labels");
}
public void createUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scroller = new JScrollPane(labelPanel);
add(scroller);
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.fill = GridBagConstraints.HORIZONTAL;
addLabel("Here is <em>Rich Text</em>");
addLabel("Here is <ul><li>A</li><li>List</li></ul>");
addLabel("Here is <table><tr><th>A</th><th>Table></th></tr></table");
addLabel("Here is more <em>Rich Text</em>");
addLabel("Here is even more <b>Rich Text</b>");
addLabel("Here is a long sentence that should wrap when the panel "
+ "is too small for the text.");
pack();
}
private void addLabel(String text) {
JLabel label = new JLabel("<html>" + text + "</html>");
label.setBorder(BorderFactory.createEtchedBorder());
labelPanel.add(label, c);
}
public static void main(String[] args) {
ScrollLabels frame = new ScrollLabels();
frame.createUI();
frame.setVisible(true);
}
}
It correctly resizes the labels horizontally and shows scroll bars where appropriate. What it doesn't do is resize labels vertically to fit them within the scroll pane.
Here are the various things I have tried:
Changing the GridBagConstraint values. There are good controls for how to expand and contract components but I can't see any way to set a min or max width.
Setting the JScrollPane scroll bar policy to never show horizontal scroll bars. This just cuts off the label text rather than wrapping the text.
Manually setting the label size - i.e. setting the width from the scroll pane and the height depending on the text. I can't see an easy way to get the correct height of rich HTML text given a fixed width. In any case I'd prefer to have a layout manager that can do the job rather than manually coding preferred sizes.
The one thing I haven't tried yet is creating a custom layout manager. I suspect this might be the right answer but would like to see if any of you have an easier solution that I'm not seeing.
I would like all labels to have the same width (driven by the width of the scroll pane) but vary in height depending on their content
You need to implement the Scrollable interface on your panel and override the getScrollableTracksViewportWidth() method to return true. You will also need to provide default implementations for the other methods of the interface.
Or you can use the Scrollable Panel which provides method that allow you to set the scrolling properties.

Adding a text area to a tabbed pane in java

I have two files that I need to display in a program. I need to use JTabbedPane and each file should be displayed in its own tab. I can make the text appear in the tab, but the scroll bar won't appear, so I can't see all of the information in the file. How do I add the scroll bar to the text area?
I made one method that creates a panel with the text in it (this is for one file). Then, I made another method that has JTabbedPane and I added the panel to a tab.
Panel method:
private void makeTextPanel() throws IOException
{
textPanel = new JPanel();
textArea = new JTextArea();
textArea.setEditable(false);
//width: 770 height: 1000
textAreaDimensions = new Dimension(TEXT_AREA_WIDTH, TEXT_AREA_HEIGHT);
textArea.setPreferredSize(textAreaDimensions);
BufferedReader inputFile = new BufferedReader(new FileReader(FILE_ONE));
String lineOfText = inputFile.readLine();
while(lineOfText != null)
{
textArea.append("\n" + lineOfText);
lineOfText = inputFile.readLine();
}
// Add a scroll bar
scrollPane = new JScrollPane(textArea);
// Add the text area and scroll bar to the panel
textPanel.add(textArea);
textPanel.add(scrollPane);
}
Tabbed pane method:
private void makeTabbedPane() throws IOException
{
frame = new JFrame("Project");
tabbedPane = new JTabbedPane();
frame.add(tabbedPane, BorderLayout.PAGE_START);
// add panel to the tab
makeTextPanel();
tabbedPane.addTab("Tab 1", textPanel);
// dimensions
frameDimensions = new Dimension(FRAME_WIDTH, FRAME_HEIGHT);
frame.setPreferredSize(frameDimensions);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
To reiterate:
How do I make the scroll bar visible?
I set the height of the text area to 1000. Will the scroll bar be able to scroll through everything? If not, how do I set the height of the text area to fit everything in the file?
The component you want scroll bars for should always a child of the JScrollPane. Adding the textArea and then the scrollPane to that tabbedPane probably isn't doing what you think it is. Make sure that textArea is the child of scrollPane, and add just the scrollPane to the tabbedPane, ensuring you've specified a layout that dictates how the scrollPane is to take up the space you want within tabbedPane.
The scrollpane will automatically add scrollbars only when it decides the textArea is bigger than it can render in the space it's been given.
Question 1) The JScrollPane methods setVerticalScrollBarPolicy() and setHorizontalScrollBarPolicy() will allow you to force the scrollbars to be always visible.
Question 2) The "preferred" height of the textArea is what your scrollPane will use to determine the scrollbar behaviour (see this example). It's all taken care of for you. If not, you'd be forced yourself to consider font rendering height, how much text you put in the textArea etc.
Generally speaking, just throwing a JTextArea into a JScrollPane will see the desired behaviour you're seeking without you having to do anything "special" with JTextArea size.

JButton Appears on One Computer, But Not Others (BorderLayout)

I am new to Swing. I am building a JFrame with a JScrollPane inside it using Eclipse IDE. Inside of the JScrollPane is a JPanel in Border Layout. I tried to add a JButton (called "submitAnswers") to the JFrame using the code below, but for some reason the button only appears at the end of the frame on my computer, but not on other computers (my friend tried it on his Mac and I tried it on a separate Windows OS like mine). Some proposed solutions that I have tried and from other sites that have not worked include:
Use the pack() method. Reason: since the preferred size of the JPanel is much longer in height than the JFrame (hence I employed a JScrollPane), packing the JFrame only causes the text to be not visible on the desktop.
Place button on content JPanel. Reason: I don't know. It just wouldn't appear on another desktop computer or my friend's mac computer.
Use BorderLayout.SOUTH instead of BorderLayout.PAGE_END. Reason: There was absolutely no change. The button would still be visible on my computer, but invisible on others.
Place button directly on JFrame. Reason: I don't know.
In addition, my JFrame is nested within a static method; hence, I've only included the relevant code for the specific method I'm having issues with.
Has anyone had this issue before? I would really appreciate your insight.
Code:
public static void createTestPage() {
JFrame testFrame = new JFrame("testing...1,2,3");
//Customizes icon to replace java icon
try {
testFrame.setIconImage(ImageIO.read(new File("src/icon.png")));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Centers location of introFrame to center of desktop
Dimension screenDimensions = Toolkit.getDefaultToolkit().getScreenSize();
testFrame.setLocation(screenDimensions.width / 16,screenDimensions.height / 14);
//Size and display the introFrame.
Insets insets = testFrame.getInsets();
//Format size of screen itself
testFrame.setSize(1200 + insets.left + insets.right,
400 + insets.top + 250 + insets.bottom);
//Temporarily set screen so that it cannot be resized
testFrame.setResizable(false);
//Set background color of testFrame
testFrame.getContentPane().setBackground(new Color(75, 0, 130));
testFrame.setLayout(new BorderLayout());
//Set layout of testFrame
testFrame.setLayout(new BorderLayout(10, 1));
//Test content
JPanel testContentPanel = new JPanel();
testContentPanel.setBackground(new Color(75, 0, 130));
testContentPanel.setSize(new Dimension(900,2060));
testContentPanel.setPreferredSize(new Dimension(900, 2060));
//Test content pane layout
testContentPanel.setLayout(new BoxLayout(testContentPanel, BoxLayout.PAGE_AXIS));
//Create panel to hold instructions text
JPanel instructionsPanel = new JPanel();
instructionsPanel.setBackground(new Color(75, 0, 130));
instructionsPanel.setLayout(new BorderLayout(10,1));
//Create JPanel for submit answers button
JPanel submitAnswersPanel = new JPanel(new BorderLayout());
submitAnswersPanel.setBackground(new Color(75, 0, 130));
submitAnswersPanel.setVisible(true);
//Create button to submit personality test answers
JButton submitAnswers = new JButton("Submit Answers");
submitAnswers.setVisible(true);
submitAnswers.setBorder(new EmptyBorder(10, 400, 10, 400));
//Add submitAnswers button to panel
submitAnswersPanel.add(submitAnswers);
//Add submitAnswersPanel to test content panel
testContentPanel.add(submitAnswersPanel);
//Create scroll pane to allow for scrollable test (contents cannot fit one page)
JScrollPane testScrollPane = new JScrollPane();
testScrollPane.setViewportView(testContentPanel);
//Get rid of horizontal scroll bar and add vertical scrollbar
testScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
testScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//Speed up scrolling
testScrollPane.getVerticalScrollBar().setUnitIncrement(16);
testFrame.add(testScrollPane);
//Experiment to show button
testFrame.setVisible(true);
}
I've refactored your code a little to use method to create the individual components of the GUI. You can find the full code at this ideone link
What I saw when I first copied your code to my machine was that the only thing visible was the button. So I create all the components in their own methods and then added them to the frame and panels using the Border Layout. This then enabled me to put the instructions in the NORTH sections, the button in the SOUTH section and then the main bits would go in the CENTER section.
One thing to note about the sections: (From the documentation)
The components are laid out according to their preferred sizes and the constraints of the container's size. The NORTH and SOUTH components may be stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may stretch both horizontally and vertically to fill any space left over.
So you should add the component you want to scale in size to the CENTER section.
My main method now looks like this:
public static void main(final String[] args) {
final JButton submitAnswers = createSubmitAnswersButton();
final JPanel instructionsPanel = createInstructionsPanel();
final JPanel testContentPanel = createContentPanel();
testContentPanel.add(instructionsPanel, BorderLayout.NORTH);
testContentPanel.add(submitAnswers, BorderLayout.SOUTH);
final JScrollPane scrollingContentPane = createScrollPaneFor(testContentPanel);
final JFrame testFrame = createJFrame();
testFrame.add(scrollingContentPane, BorderLayout.CENTER);
testFrame.setVisible(true);
}

Java Applet gridlayout issue

im having a little issue with my code. I have created a gridlayout of 5,1,0,0. I have a textfield, 3 buttons and a label where the result analysis of whatever the user had input is displayed at the bottom. Now the results can come on multiple lines depending on how big words are in the sentence, my problem is when multiple lines of results are displayed, the layout of my program changes and i dont know how to keep it the same but just the label or Applet window itself resize if need be?
public class assignment_tauqeer_abbasi extends JApplet implements ActionListener {
JTextArea textInput; // User Input.
JLabel wordCountLabel; // To display number of words.
public void init() {
// This code from here is the customisation of the Applet, this includes background colour, text colour, text back ground colour, labels and buttons
setBackground(Color.black);
getContentPane().setBackground(Color.black);
textInput = new JTextArea();
textInput.setBackground(Color.white);
JPanel south = new JPanel();
south.setBackground(Color.darkGray);
south.setLayout( new GridLayout(5,1,0,0) );
/* Creating Analyze and Reset buttons */
JButton countButton = new JButton("Analyze");
countButton.addActionListener(this);
south.add(countButton);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
south.add(resetButton);
JButton fileButton = new JButton("Analyze Text File");
fileButton.addActionListener(this);
south.add(fileButton);
/* Labels telling the user what to do or what the program is outputting */
wordCountLabel = new JLabel(" No. of words:");
wordCountLabel.setBackground(Color.black);
wordCountLabel.setForeground(Color.red);
wordCountLabel.setOpaque(true);
south.add(wordCountLabel);
/* Border for Applet. */
getContentPane().setLayout( new BorderLayout(2,2) );
/* Scroll bar for the text area where the user will input the text they wish to analyse. */
JScrollPane scroller = new JScrollPane( textInput );
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(south, BorderLayout.SOUTH);
} // end init();
public Insets getInsets() {
// Border size around edges.
return new Insets(2,2,2,2);
}
// end of Applet customisation
This is my code for the layout. Any help would be apprecited!
A GridLayout will size every cell according to the content of the largest cell. Consider using a different layout, or a combination of layouts instead.
The gridLayout that you have used would possibly complicate the five contents that you have used. Try using flow Layout instead this would automatically make space for the new contents that are being entered.

Is there any 'top to bottom' and 'right to left' in boxlayout?

I have some tables which should draw from right to left and top to bottom at the frame. Right now I used absolute layout and working with coordination. Is there any BoxLayout or any other Java layout can do it? I should mention that the number of tables is dynamic.
My second question is how can I dock these tables to frame? I mean I want when the frame resize, tables keep their positions on the screen.
Most layout managers will respect the orientation of the component:
panel.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT );
panel.add(...);
Or you can always just add the components to the beginning of the container
panel.add(component1, 0);
panel.add(component2, 0);
You may want to use a grid if you are arranging things into a table. All of the elements in a grid should be the same size.
To arrange some items vertically where the size of each row can vary, try this:
static JPanel buildPanel() {
JPanel vPanel = new JPanel();
BoxLayout layout = new BoxLayout(vPanel, BoxLayout.Y_AXIS);
vPanel.setLayout(layout);
JPanel[] rowPanels = new JPanel[5];
int counter=1;
for (int i = 0; i < rowPanels.length; i++) {
rowPanels[i] = new JPanel();
rowPanels[i].setLayout(new FlowLayout(FlowLayout.LEFT, 2, 2));
rowPanels[i].add(new JButton("button " + counter++));
rowPanels[i].add(new JButton("Your button " + counter++));
rowPanels[i].add(new JButton("Shabutton"));
vPanel.add(rowPanels[i]);
}
return vPanel;
}
public static void main(String[] args) {
JFrame gridFrame = new JFrame();
gridFrame.add(buildPanel() );
gridFrame.pack();
gridFrame.setVisible(true);
}
You can prevent the whole JFrame from resizing using gridFrame.setResizable(false);
You can prevent sapce from being added between the rows when the window is resized with a method call like this:
rowPanels[i].setMaximumSize(new Dimentsion(400,32));

Categories

Resources