Writing at the bottom of JTextArea - java

I have a JScrollPane and a JTextArea (editable) with 10 rows. I want the first user input to appear at the bottom of the JTextArea and the most recent input should push the previous input upward. To achieve this I use textArea.setMargin(new Insets(x,0,0,0)); and everything works as it should - except that my second input will toggle the JScrollPane.
How can I start at the bottom of the JTextArea and only enable scrolling when the entire original viewport is filled?

Basically, you could add the JTextText onto a JPanel with another JPanel which acts a filler, causing the JTextArea to occupy the smallest space it actually needs.
I did this by using GridBagLayout to force the fill to occupy the most of space it could...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextArea {
public static void main(String[] args) {
new TestTextArea();
}
public TestTextArea() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(new TestPane()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea ta;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JPanel filler = new JPanel();
filler.setBackground(Color.WHITE);
add(filler, gbc);
gbc.gridy = 1;
gbc.weighty = 0;
ta = new JTextArea(1, 20);
add(ta, gbc);
}
}
}

To achieve this I use textArea.setMargin(new Insets(x,0,0,0)); and everything works as it should - except that my second input will toggle the JScrollPane.
Well I would guess that you would need to reset the margin every time you add text to the text area to take into account the new preferred size of the text area in relation to the size of the scroll pane.
You should be able to add a DocumentListener to the text area and make your adjustment whenever text is added to the Document.

I don't think that using margins and insets is the way to go because you are using layout adjustments to achieve text (content) functionality. This should be controlled by the Document object, which is what JTextArea makes its calls to regarding its content.
If you are calling append internally, then override it in a new class extending JTextArea:
public class Test {
static MyTextArea ta = new MyTextArea();
static int x = 0;
public static void main(String[] args) {
ta.setRows(10);
ta.setText("\n\n\n\n\n\n\n\n\n");
ta.setCaretPosition(ta.getDocument().getLength());
JButton append = new JButton("Append");
append.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ta.append("\n" + x);
x++;
}
});
JFrame frame= new JFrame();
frame.setContentPane(new JPanel(new BorderLayout()));
frame.getContentPane().add(new JScrollPane(ta), BorderLayout.CENTER);
frame.getContentPane().add(append, BorderLayout.LINE_START);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static class MyTextArea extends JTextArea {
#Override
public void append(String str) {
super.append(str);
try {
if (getDocument().getText(0, 1).equals("\n"))
getDocument().remove(0, 1);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
If you are editing it manually, add a DocumentListener:
public class Test {
public static void main(String[] args) {
JTextArea ta = new JTextArea();
ta.setRows(10);
ta.setText("\n\n\n\n\n\n\n\n\n");
ta.setCaretPosition(ta.getDocument().getLength());
ta.getDocument().addDocumentListener(new MyDocListener());
JFrame frame= new JFrame();
frame.setContentPane(new JPanel(new BorderLayout()));
frame.getContentPane().add(new JScrollPane(ta), BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static class MyDocListener implements DocumentListener {
#Override
public void insertUpdate(DocumentEvent e) {
final DocumentEvent de = e;
Runnable pushUp = new Runnable() {
#Override
public void run() {
String t = null;
try {
t = de.getDocument().getText(de.getOffset(), de.getLength());
if (t.equals("\n") && de.getDocument().getText(0, 1).equals("\n"))
ta.getDocument().remove(0, 1);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
};
SwingUtilities.invokeLater(pushUp);
}
#Override
public void removeUpdate(DocumentEvent e) {}
#Override
public void changedUpdate(DocumentEvent e) {}
}
}
Note that all you need from the code are the inner classes, the rest is just so you can see it working. I also don't have information regarding the initial state of the text area. Here I just set the number of rows to 10 and the text to 10 empty lines. I'm also not sure what you're allowed to do in the text area. This solution assumes that you can't jump lines and each time you insert a line it's not blank and it follows the previous line.

Related

Update JLabel text

I'm working on a simple GUI. On Button press i want to increase/decrease a variable and update the corresponding JLabel.
class JFrameSetUp
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameSetUp extends JFrame implements ActionListener {
private int RecHeight = 0;
private int RecWidth = 0;
//Here Buttons
JButton HeightIncrease = new JButton("+");
JButton HeightDecrease = new JButton("-");
JLabel height = new JLabel(Integer.toString(RecHeight));
JLabel width = new JLabel(Integer.toString(RecWidth));
GridLayout gridLayout = new GridLayout(2, 4);
public JFrameSetUp(){
}
public void addComponentsToPane(final Container pane){
//Create GridPanel and set Layout
JPanel grid = new JPanel();
grid.setLayout(gridLayout);
//Create buttondrawPanel and set Layout
JPanel buttondraw = new JPanel();
buttondraw.setLayout(new GridLayout(2, 0));
//Adding Components to GridPanel
//Adding Layouts to pane
pane.add(grid, BorderLayout.NORTH);
pane.add(new JSeparator(), BorderLayout.CENTER);
pane.add(buttondraw, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
//Setting up ActionListener to Buttons
if (e.getSource() == this.HeightDecrease) {
RecHeight -= 1;
height.setText(Integer.toString(RecHeight));
} else if (e.getSource() == this.HeightIncrease) {
RecHeight += 1;
height.setText(Integer.toString(RecHeight));
}
}
}
Class with MainMethod
import javax.swing.JFrame;
public class Program {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrameSetUp frame = new JFrameSetUp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
I'm aware, that's kind a newbish question. I think I'm wrong with my Code Structure. Any help is appreciated.
Thanks in advance.
You never register any ActionListeners to the buttons...
HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);
You also never add the buttons to the GUI
buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);
You also never add the labels to the GUI either...
grid.add(height);
grid.add(width);
I reworked the code, because your example was messing with my mind, hope you don't mind...
It's conceptually the same idea, just done slightly more efficently
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int recHeight = 0;
private int recWidth = 0;
//Here Buttons
JButton heightIncrease = new JButton("+");
JButton heightDecrease = new JButton("-");
JLabel height = new JLabel(Integer.toString(recHeight));
JLabel width = new JLabel(Integer.toString(recWidth));
GridLayout gridLayout = new GridLayout(2, 4);
public TestPane() {
setLayout(new BorderLayout());
//Create GridPanel and set Layout
JPanel grid = new JPanel();
grid.setLayout(gridLayout);
grid.add(height);
grid.add(width);
//Create buttondrawPanel and set Layout
JPanel buttondraw = new JPanel();
buttondraw.setLayout(new GridLayout(2, 0));
heightIncrease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recHeight += 1;
height.setText(Integer.toString(recHeight));
}
});
heightDecrease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recHeight -= 1;
height.setText(Integer.toString(recHeight));
}
});
buttondraw.add(heightIncrease);
buttondraw.add(heightDecrease);
//Adding Components to GridPanel
//Adding Layouts to pane
add(grid, BorderLayout.NORTH);
add(new JSeparator(), BorderLayout.CENTER);
add(buttondraw, BorderLayout.SOUTH);
}
}
}
I would encourage you to spend some time having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
After changing the value call
frame.repaint();
Good to see you learning Java! A few things I should point out.
Firstly, your variable names are good, but they don't follow the Java naming convention. Even though it seems small, it's just good practice to follow.
Of course, your actual problem; the action listener you've implemented is on the JFrame. (See how you extend JFrame and implement ActionListener?) This ActionListener should be on the button. You'll can do this a few ways.
Method 1: By adding it inline with your code
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(new ActionListener(){
#Override
public void run(){
//run method here
}
});
Method 2: Create a class which implements ActionListener
class ButtonListener implements ActionListener{
#Override
public void run(){
//actionListener code here
}
}
And then instantiate an object of this type and add it directly to your code.
ActionListner buttonListener = new ButtonListener(); //or ButtonListener buttonListener = new ButtonListener();
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(buttonListener);
Of course, as in MadProgrammers answer, don't forget to add the labels and such to your JFrame or JPanel. Good luck learning Java!
I bet that your program just shows nothing, isn't it? That's because in addComponentsToPane method, you didn't add any component but empty JPanels. After the comment //Adding Components to GridPanel, you should:
buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);
grid.add(height);
grid.add(width);
Then, to listen to button event, you should also add :
HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);
"this" is because your frame JFrameSetUp implements ActionListener, so when either bootton is clicked the method actionPerformed is invoked.
As JLabel.setText method will repaint itself and consequently its component hierarchi is repainted as well, you haven't to do anything othr.

How to execute a .java file on clicking a jbutton in jframe?

On clicking the jbutton in a jframe, I want Start.java file to be executed;what to do?
The Start.java is executing well. I want the same execution to be done when clicked on jbutton in jframe, please help me out.
My jframe code has jbutton
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
// i want to execute Start.java file on clicking the button
Start s = new Start();
String in = s.getTxt;
System.out.println(in);
repaint();
}
My Start.java file is :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Start extends JPanel{
public String getTxt;
public Start()
{
final JTextField jf = new JTextField(20);
jf.setBounds(30, 30, 250, 30);
final JButton j1 = new JButton("OK");
j1.setBounds(80, 80, 100, 30);
setLayout(null);
add(jf);
add(j1);
j1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getTxt = jf.getText();
System.out.println(getTxt);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310,250));
f.setMaximumSize(new Dimension(310,250));
f.setMinimumSize(new Dimension(310,250));
f.pack();
f.setVisible(true);
}
}
So, based on what you seem to be doing in your code, I would strongly recommend that you have a look at How to Make Dialogs, the main reason for this is, a modal dialog will cause the execution of your program to stop at the point where the dialog is made visible and resume when it's closed, this way, allowing you to inspect the values the user might have changed.
So, when I first tried to get your program to work, this is what happened...
So, after digging into your code, I noticed you'd done setLayout(null);. This is going to keep on coming back to haunt you and I strongly recommend that you don't do this and learn how to use the layout management API.
So, I jumped into you code and add a layout manager...
public class Start extends JPanel {
public String getTxt;
public Start() {
final JTextField jf = new JTextField(20);
final JButton j1 = new JButton("OK");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(jf, gbc);
add(j1, gbc);
j1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getTxt = jf.getText();
System.out.println(getTxt);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310, 250));
f.setMaximumSize(new Dimension(310, 250));
f.setMinimumSize(new Dimension(310, 250));
f.pack();
f.setVisible(true);
}
}
Now I get...
Okay, but now there's two buttons, and unless the user clicks the middle button, the text is never set!
The fact is, for this kind of thing, you don't need the button! You just need a method which can return the current text of the JTextField, for example...
public class Start extends JPanel {
final JTextField jf = new JTextField(20);
public Start() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(jf, gbc);
}
public String getText() {
return jf.getText();
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310, 250));
f.setMaximumSize(new Dimension(310, 250));
f.setMinimumSize(new Dimension(310, 250));
f.pack();
f.setVisible(true);
}
}
And then I can use...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Surprise");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Start start = new Start();
JOptionPane.showMessageDialog(TestPane.this, start, "Surprise", JOptionPane.PLAIN_MESSAGE);
System.out.println(start.getText());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
to show it!
I'd strongly recommend that you take the time to have a look at Laying Out Components Within a Container

Java Set Layout

I need to create a JFrame which has three JPanels laid out as shown:
Could anybody please tell me how I can achieve this layout? I have already tried using BorderLayout, but in BorderLayout, if I add the topmost pane at BorderLayout.NORTH, the one in the center at BorderLayout.CENTER, and the one at the bottom to BorderLayout.SOUTH, the topmost pane becomes too small (in height) and the pane in the center becomes too big (in height).
P.S. I have already made the 3 panes and set their preferred sizes properly.
You could use all sorts of things, compound layouts (using two BorderLayouts for example) or other layouts, it will depend on what you ultimately want to achieve.
For simplicity, I'd use a GridBagLayout, for example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout {
public static void main(String[] args) {
new TestLayout();
}
public TestLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new ABigPanel(), gbc);
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new ASmallPanel(), gbc);
add(new ASmallerPanel(), gbc);
}
}
public class ABigPanel extends JPanel {
public ABigPanel() {
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
}
public class ASmallPanel extends JPanel {
public ASmallPanel() {
setBackground(Color.GREEN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 180);
}
}
public class ASmallerPanel extends JPanel {
public ASmallerPanel() {
setBackground(Color.CYAN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 40);
}
}
}
See How to Use GridBagLayout for more details

Center JLabel in BorderLayout with a button at line end

I have a header on a section of my swing layout, and I want to have text centered horizontally across the whole width of the section, but also have a button on only the right side. It should look like this:
/------Same width------\ /------Same width------\
[------------------------]Text here[----------------[Button]]
I am currently using a BorderLayout, with the text in the center and the button at the line end, but the text is centered not counting the button, as such:
/----Same width----\ /---Same width----\
[--------------------]Text here[-------------------][Button]]
I'm not sure if this is the answer you really want, but you could use a different layout manager, like GridBagLayout
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JavaApplication295 {
public static void main(String[] args) {
new JavaApplication295();
}
public JavaApplication295() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
// gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(new JLabel("Look ma, no hands"), gbc);
gbc.anchor = GridBagConstraints.EAST;
add(new JButton("No Allowance"), gbc);
}
}
}
Now, the problem with this, is both components are actually positioned at the same location, the difference is, the button is anchored to the right position of the cell, this means that when the layout is been calculated, they will overlap....
Here is an approach using the OverlayLayout which was designed to have multiple components painted on the z axis:
import java.awt.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JLabel label = new JLabel("I'm a Centered Label");
Box labelBox= Box.createHorizontalBox();
labelBox.add(Box.createHorizontalGlue());
labelBox.add(label);
labelBox.add(Box.createHorizontalGlue());
JButton button = new JButton("Button");
Box buttonBox= Box.createHorizontalBox();
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(button);
setLayout( new OverlayLayout(this) );
add(buttonBox);
add(labelBox);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE(), BorderLayout.NORTH);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
As the width decreases the button will paint over the label.

List of JPanels that eventually uses a scrollbar

im trying to build a GUI for my Java application.
I dynamically add JPanels, which are a "row" in my GUI. Under the List of the Panels there is a button to add a new Panel. As the List grows, it reaches the end of the parent Container. Then I want to use scrollbars, so that the user is able to reach every panel in the List.
So far I experimented with JScrollPanes and Layouts but I have no Idea how to get it working.
Can you give me some advice?
this.setLayout(new BorderLayout());
JPanel listContainer = new JPanel();
listContainer.setLayout(BoxLayout(listContainer, BoxLayout.Y_AXIS);
this.add(new JScrollPane(listContainer), BorderLayout.CENTER);
this.add(new JButton(), BorderLayout.PAGE_END);
//then i add panels to the listContainer. this wont work, when the space is complettly used there is no scrollbar.
It's difficult to assertain from your code snippet exactly where you might be having problems.
public class DynamicPanelList {
public static void main(String[] args) {
new DynamicPanelList();
}
public DynamicPanelList() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel mainList;
public TestPane() {
setLayout(new BorderLayout());
mainList = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
mainList.add(new JPanel(), gbc);
add(new JScrollPane(mainList));
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.add(new JLabel("Hello"));
panel.setBorder(new MatteBorder(0, 0, 1, 0, Color.GRAY));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainList.add(panel, gbc, 0);
validate();
repaint();
}
});
add(add, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
You really need to provide a SSCCE which would allow us to diagnose the problems you are having.
Personally, and this will depend on you requirements, a better layout manager might be VerticalLayout from SwingLabs SwingX libraries.
You probably forgot to call revalidate() on your listContainer (and you made a bunch of syntax errors). BoxLayout does not do a great job in my opinion, but that is not the matter here.
Here is a small demo code which seems to work quite well:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestScollpane {
private int i;
private JPanel listContainer;
private void initUI() {
final JFrame frame = new JFrame(TestScollpane.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
listContainer = new JPanel();
listContainer.setLayout(new BoxLayout(listContainer, BoxLayout.Y_AXIS));
frame.add(new JScrollPane(listContainer), BorderLayout.CENTER);
JButton button = new JButton("Add");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final JPanel newPanel = new JPanel();
newPanel.add(new JLabel("Label " + i++));
listContainer.add(newPanel);
listContainer.revalidate();
// Scroll down to last added panel
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
newPanel.scrollRectToVisible(newPanel.getBounds());
}
});
}
});
frame.add(button, BorderLayout.PAGE_END);
frame.setSize(300, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestScollpane().initUI();
}
});
}
}

Categories