Swing: create a CompoundBorder with 3 borders? - java

I am creating a JFrame object with some JPanels next to each other side by side.
I want the JPanels to have a 15px margin, etched border, and 15px padding. At first I thought that this would be something really intuitive just like the HTML box model, so I tried to create CompoundBorder inside a CompoundBorder but that wouldn't work.
Here's my code:
import java.awt.Dimension;
import javax.swing.*;
public class StackOverFlowExample extends JFrame {
public static void main() {
stackOverFlowExample window = new stackOverFlowExample();
window.setVisible(true);
}
public StackOverFlowExample() {
// create buttons
JButton foo = new JButton("foo");
JButton bar = new JButton("bar");
JButton foo2 = new JButton("foo2");
JButton bar2 = new JButton("bar2");
// create panels and add buttons to them
JPanel left = new JPanel();
left.setBorder(BorderFactory.createEtchedBorder());
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
left.add(foo);
left.add(bar);
JPanel right = new JPanel();
right.setBorder(BorderFactory.createEtchedBorder());
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
right.add(foo2);
right.add(bar2);
// add panels to frame
this.getContentPane().setLayout(new BoxLayout(
getContentPane(), BoxLayout.LINE_AXIS));
this.getContentPane().add(left);
this.getContentPane().add(right);
// finalize layout
this.setPreferredSize(new Dimension(150,150));
this.pack();
this.setVisible(true);
}
}
I'm aware that I could have just used GridBagConstraints or JButton.setMargin() to create the padding, and then use CompoundBorder to create the etched border with an empty border. What if I don't want to make my code look messy with those techniques though?

I'm not sure what problems you might be having, as you've not supplied an example of what you've tried, but the basic process would be to...
Create the inner border requirements (EtchedBorder wrapping a EmptyBorder), for example, new CompoundBorder(emptyBorder, etchedBorder)
Create the outer border requirements (EmptyBorder wrapping the inner compound border), for example, new CompoundBorder(inner, emptyBorder);
Apply this outer border to the component...
As an example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
public class Test1 {
public static void main(String[] args) {
new Test1();
}
public Test1() {
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());
EmptyBorder emptyBorder = new EmptyBorder(15, 15, 15, 15);
EtchedBorder etchedBorder = new EtchedBorder();
CompoundBorder inner = new CompoundBorder(emptyBorder, etchedBorder);
CompoundBorder outter = new CompoundBorder(inner, emptyBorder);
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(outter);
panel.add(new JButton("Hello"));
add(panel);
}
}
}

import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class ThreePartBorder {
public static void main(String[] args) {
final BufferedImage bi = new BufferedImage(
400, 100, BufferedImage.TYPE_INT_RGB);
Runnable r = new Runnable() {
#Override
public void run() {
JLabel l = new JLabel(new ImageIcon(bi));
Border twoPartBorder = new CompoundBorder(
new EmptyBorder(15, 15, 15, 15),
new EtchedBorder());
Border threePartBorder = new CompoundBorder(
twoPartBorder,
new EmptyBorder(15, 15, 15, 15));
l.setBorder(threePartBorder);
JFrame f = new JFrame("Three Part Border");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(l);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

I came back and just realized I asked a dumb question haha. Both answers above are very helpful and helped me solve the problem so I accepted one of them. Here's my solution after reading the two answers...
left.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(10,10,10,10), // margin
BorderFactory.createEtchedBorder() // border
),
BorderFactory.createEmptyBorder(50,50,50,50) // padding
));
right.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(10,10,10,10), // margin
BorderFactory.createCompoundBorder(
BorderFactory.createEtchedBorder(), // border
BorderFactory.createEmptyBorder(50,50,50,50) // padding
)
));

Related

JTextArea doesn't work when Frame is split in two JPanel

I want split my Frame into two JPanel and the right JPanel serve as a textarea used to input and display.
However, I can't input anything in it and it can't display any thing.
the code as below:
JPanel jp1, jp2;
public DemoFrame() {
jp1 = new JPanel();
jp2 = new JPanel();
JLabel label = new JLabel("text");
JTextArea ta = new JTextArea(100,100);
ta.setText("some text");
ta.setSize(300, 300);
jp2.add(label);
jp2.add(ta);
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jp1, jp2);
this.getContentPane().add(jsp);;
setBounds(300, 200, 500, 500);
setVisible(true);
jsp.setDividerLocation(0.5);//
}
the output as below(it doesnt display anything):
Congratulations, you've fallen victim to a number of conspiring issues.
The main culprit is FlowLayout, which is the default layout manager for JPanel. Essentially, when you add your, rather large, JTextArea to the panel, the FlowLayout is trying to honour the preferred size as best as it can within the constraints of the available space. For reasons I'm not 100% sure of, that means laying out the component beyond the visible bounds of the container.
If you type enough text, you will begin to see it.
While there are a number of ways you might fix this, they are basically the same solution - use a different layout manager.
For this example, I've just used a BorderLayout instead
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
private JPanel jp1, jp2;
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
jp1 = new JPanel();
jp2 = new JPanel(new BorderLayout());
JLabel label = new JLabel("text");
JTextArea ta = new JTextArea(50, 50);
ta.setText("some text");
jp2.add(label, BorderLayout.NORTH);
jp2.add(new JScrollPane(ta));
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jp1, jp2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(jsp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Trying to set the location of a Java Button using JFrame isn't working?

Please look below for Edits.
So I've looking over numerous "solutions" to fix my problem, but I just can't seem to get it working.
This is what my application looks like with the code below:
Basically, I want to set the location of a button, but I can't manage to do so. Here is my code:
package me.cervinakuy.application;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ControlPanel3 extends JFrame {
JPanel panel = new JPanel();
JButton startRobo = new JButton();
JButton stopRobo = new JButton();
JButton restartRobo = new JButton();
public ControlPanel3() {
// setLayout(null);
setSize(1000, 700);
setResizable(false);
setLocation(450, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(new Color(45, 48, 55));
setTitle("Espin Software | Control Panel");
setVisible(true);
startRobo.setIcon(new ImageIcon(getClass().getResource("/resources/startRobo.png")));
stopRobo.setIcon(new ImageIcon(getClass().getResource("/resources/stopRobo.png")));
restartRobo.setIcon(new ImageIcon(getClass().getResource("/resources/restartRobo.png")));
startRobo.setBorder(null);
stopRobo.setBorder(null);
restartRobo.setBorder(null);
startRobo.setLocation(100, 100);
panel.add(startRobo);
panel.add(stopRobo);
panel.add(restartRobo);
panel.setOpaque(false);
add(panel);
validate();
}
}
EDIT:
I have now managed to create a GUI of what I was initially looking for, however, I have a new problem. Buttons are now pressable from different parts of the GUI, rather than only on the image. For those interested, here is what I have been able to accomplish:
New GUI look.
Updated Code:
package me.cervinakuy.application;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ControlPanel3 extends JFrame {
JPanel panel = new JPanel();
JButton startRobo = new JButton();
JButton stopRobo = new JButton();
JButton restartRobo = new JButton();
public ControlPanel3() {
// setLayout(null);
setSize(1000, 700);
setResizable(false);
setLocation(450, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(new Color(45, 48, 55));
setTitle("Espin Software | Control Panel");
setVisible(true);
startRobo.setIcon(new ImageIcon(getClass().getResource("/resources/startRobo.png")));
stopRobo.setIcon(new ImageIcon(getClass().getResource("/resources/stopRobo.png")));
restartRobo.setIcon(new ImageIcon(getClass().getResource("/resources/restartRobo.png")));
startRobo.setBorder(null);
stopRobo.setBorder(null);
restartRobo.setBorder(null);
panel.setLayout(null);
startRobo.setLocation(200, 200);
startRobo.setBounds(5, -95, 300, 300);
stopRobo.setBounds(5, 0, 300, 300);
restartRobo.setBounds(5, 95, 300, 300);
panel.add(startRobo);
panel.add(stopRobo);
panel.add(restartRobo);
panel.setOpaque(false);
add(panel);
validate();
}
}
There are typically a number of ways to layout components that end with the same effect. In this example, we use a panel to contain the buttons in a column (buttonContainer using a GridLayout) then a panel to restrict that container to the top (buttonConstrainPanel using a BorderLayout) then a container to put that panel on the left (ui with BorderLayout).
It could also be achieved using a single GridBagLayout or a GroupLayout, though the logic of achieving it might not be as simple.
The focus border seen on the blue button indicates the limits of where a mouse click would activate the button.
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ThreeButtonAlignedLeft {
private JComponent ui = null;
private String prefix = "http://i.stack.imgur.com/";
private String[] suffix = {"gJmeJ.png","T5uTa.png","wCF8S.png"};
ThreeButtonAlignedLeft() {
try {
initUI();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
public void initUI() throws MalformedURLException {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel buttonContainer = new JPanel(new GridLayout(0, 1, 5, 5));
for (int ii=0; ii<suffix.length; ii++) {
JButton b = new JButton(new ImageIcon(new URL(prefix + suffix[ii])));
b.setBorderPainted(false);
b.setMargin(new Insets(0,0,0,0));
b.setContentAreaFilled(false);
buttonContainer.add(b);
}
JPanel buttonConstrainPanel = new JPanel(new BorderLayout(0, 0));
buttonConstrainPanel.add(buttonContainer, BorderLayout.PAGE_START);
ui.add(buttonConstrainPanel, BorderLayout.LINE_START);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ThreeButtonAlignedLeft o = new ThreeButtonAlignedLeft();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Use a JButton to add new panels at runtime

I feel as beginner I may have bitten off too much in regards to application building. That said, I am working on developing an application for a friend that will have prompts where each JPanel will provide fields to create an object to be used later. What I would like to have happen is that when the panel loads, it displays one object creation panel and a button to dynamically add a new panel if the user wants to make multiples (the plus button would add the new panel).
I have drawn up something in paint to illustrate this:
By my very limited understanding, I can create a panel to hold these sub-panels, and then add a action listener to the '+' button to create new panels. The only way I could think to implement this is to create a constructor for the panel I want to add. Is this possible? Let me show you what I have:
package com.company;
import java.awt.*;
import javax.swing.*;
/**
* Created by Travis on 3/1/2015.
*/
public class MainSnakeGui extends JFrame{
protected int panelCount;
//row 1
JPanel row1 = new JPanel();
JLabel splitSnakeLabel = new JLabel("Create a Split Snake", JLabel.CENTER);
//row 2
JPanel row2 = new JPanel();
JButton addButton = new JButton("+");
public MainSnakeGui() {
super("Snake Channels");
setSize(550, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout = new GridLayout(5, 1, 10, 10);
setLayout(layout);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row1.setLayout(layout1);
row1.add(splitSnakeLabel);
add(row1);
GridLayout layout2 = new GridLayout(1, 2, 10, 10);
row2.setLayout(layout2);
row2.add(addButton);
MainSnakeConstructor snakePanel = new MainSnakeConstructor();
row2.add(snakePanel);
add(row2);
setVisible(true);
}
public static void setLookAndFeel () {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
}
}
public static void main(String[] arg) {
MainSnakeGui.setLookAndFeel();
MainSnakeGui frame = new MainSnakeGui();
}
}
Here is the constructor:
package com.company;
import javax.swing.*;
import java.awt.*;
/**
* Created by Travis on 3/1/2015.
*/
public class MainSnakeConstructor extends JFrame {
public MainSnakeConstructor () {
JPanel splitSnakeRow = new JPanel();
JLabel snakeNameLabel = new JLabel("Snake Name");
JLabel channelCountLabel = new JLabel("Channel Count");
JCheckBox artistSuppliedCheckBox = new JCheckBox("Artist Supplied?");
JTextField snakeNameTextField = new JTextField(30);
JTextField channelCountTextField = new JTextField(3);
GridLayout layout = new GridLayout(3,2,10,10);
splitSnakeRow.setLayout(layout);
splitSnakeRow.add(snakeNameLabel);
splitSnakeRow.add(channelCountLabel);
splitSnakeRow.add(artistSuppliedCheckBox);
splitSnakeRow.add(snakeNameTextField);
splitSnakeRow.add(channelCountTextField);
add(splitSnakeRow);
}
}
Think about it differently. You want a button that allows you to add new panels, so you really only need a single button.
From there, you need some kind common panel which provides the functionality you want to the user (the creation panel). Then, when the user clicks the add button, you create a new creation panel and add it to the container been used to display them, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
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() {
JButton btnAdd = new JButton("+");
setLayout(new BorderLayout());
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
buttons.add(btnAdd);
add(buttons, BorderLayout.NORTH);
JPanel content = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
content.add(new JPanel(), gbc);
add(new JScrollPane(content));
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CreationPane pane = new CreationPane();
int insertAt = Math.max(0, content.getComponentCount() - 1);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
content.add(pane, gbc, insertAt);
content.revalidate();
content.repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public static class CreationPane extends JPanel {
private static int count;
public CreationPane() {
setLayout(new GridBagLayout());
add(new JLabel("Make it so " + (count++)));
setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
}
}
}
Now having done all that, I prefer the VerticalLayout manager from SwingLabs, SwingX library, which basically does the same thing...

Center panel when window resized

I would like to keep a panel I have created using an absolute layout in the center of my window even when the window is resized (if possible). I've come across a couple of suggestions here and [here][2] but no dice! Below is my sample code, any ideas or suggestions? I have no problems centered a single component like a JLable but I want to center a panel with many components!
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.JLabel;
public class TestPanel extends JFrame {
private JLabel lblSetupTitle;
private Border compoundBorder, outlineColorBorder, outlineBorder;
private JTextArea txtrManageData;
private JPanel childPanel;
public TestPanel()
{
setBackground(Color.white);
outlineColorBorder = BorderFactory.createLineBorder(Color.gray);
outlineBorder = BorderFactory.createEmptyBorder(20, 20, 20, 20);
compoundBorder = BorderFactory.createCompoundBorder(outlineColorBorder, outlineBorder);
lblSetupTitle = new JLabel("Setup");
lblSetupTitle.setBounds(443, 288, 44, 23);
txtrManageData = new JTextArea("Text Area Text");
txtrManageData.setBounds(393, 322, 142, 61);
childPanel = new JPanel();
childPanel.setLocation(89, 38);
childPanel.setSize(921, 452);
childPanel.setBorder(compoundBorder);
setupGUIElements();
setupPanel();
}
private void setupGUIElements()
{
txtrManageData.setBackground(null);
txtrManageData.setLineWrap(true);
txtrManageData.setWrapStyleWord(true);
}
private void setupPanel()
{
getContentPane().setLayout(new GridBagLayout()); // set layout of parent panel to GridBagLayout
childPanel.setLayout(null); // set layout of child panel to AbsoluteLayout
childPanel.add(lblSetupTitle);
childPanel.add(txtrManageData);
getContentPane().add(childPanel, new GridBagConstraints());
this.setSize(1020, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestPanel ex = new TestPanel();
ex.setVisible(true);
}
});
}
}
EDIT: Any tips, links, guidance on creating something like this
I'd nest layouts.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class ThreeButtonTextFieldCombo {
private JPanel ui = null;
ThreeButtonTextFieldCombo() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new TitledBorder("Parent Panel"));
JPanel controls = new JPanel(new GridLayout(1,0,10,10));
ui.add(controls);
controls.setBackground(Color.RED);
controls.setBorder(new TitledBorder("Child Panel"));
for (int ii=1; ii<4; ii++) {
addLabelAndField(controls, "String " + ii);
}
}
public JComponent getUI() {
return ui;
}
private void addLabelAndField(JPanel panel, String text) {
JPanel controls = new JPanel(new BorderLayout(3, 3));
controls.setBorder(new EmptyBorder(20,20,20,20));
JLabel l = new JLabel(text);
controls.add(l, BorderLayout.PAGE_START);
JTextArea ta = new JTextArea(text, 2, 8);
controls.add(new JScrollPane(ta));
panel.add(controls);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Three Button/Text Field Combo");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
ThreeButtonTextFieldCombo tbtfc =
new ThreeButtonTextFieldCombo();
f.setContentPane(tbtfc.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
The first problem with your code is that you are adding your child panel using an empty instantiation of GridBagConstraints. I have never seen it used like that before.
getContentPane().add(childPanel, new GridBagConstraints());
Do not set any layout to content pane and just add it like this :
getContentPane().add(childPanel);
Now if you run it you will get the two components in the middle, where you defined them using the setBounds(..) method.
Like almost everyone commenting on your question, you should not use null layout, and use some other layout instead. I would use a GridBagLayout to organise the three buttons and three textfields in your diagram. You could then setBounds(..) on your child panel.
If you really must use absolute layout then you will have to do a bit of maths.
If your first label is like this :
labell1.setBounds(443, 288, 44, 23);
then your second label should be something like this :
labell2.setBounds(443 + someXDisplacement, 288, 44, 23);
..and third :
labell3.setBounds(443 + (someXDisplacement x 2), 288, 44, 23);
You get the picture.

Scrolling to the top JPanel inside a JScrollPane

I know a lot of people asked this question, but i still can't resolve this problem.
I have a JPanel inside a JScrollPane. JPanel contains six panels that are loaded dynamically.
After the panels are loaded the system makes a vertical autoscroll to the middle of the panel.
I have to avoid this, so I tried with this:
panel.scrollRectToVisible(scrollPane.getBounds());
But it doesn't work.
My scrollPane has been created in this way
JScrollPane scrollPane= new JScrollPane();
scrollPane.setBounds(panel.getBounds());
scrollPane.setViewportView(panel);
Can you help me?
panel.scrollRectToVisible(scrollPane.getBounds()); should be panel.scrollRectToVisible(JPanelAddedOnRuntime.getBounds());
rest of code (posted here) coudn't be works,
for better help sooner post an SSCCE, short, runnable, compilable
EDIT
works, again you would need to re_read my above 3rd. point
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class ScrollTesting {
private JPanel panel = new JPanel();
private JScrollPane scrollPane = new JScrollPane(panel);
private Vector<JTextField> fieldsVector = new Vector<JTextField>();
private Dimension preferredSize = new Dimension(400, 40);
private Font font = new Font("Tahoma", 1, 28);
public ScrollTesting() {
panel.setLayout(new GridLayout(100, 1));
for (int i = 0; i < 100; i++) {
fieldsVector.addElement(new JTextField());
fieldsVector.lastElement().setPreferredSize(preferredSize);
fieldsVector.lastElement().setFont(font);
panel.add(fieldsVector.lastElement());
}
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JTextField tf = (JTextField) fieldsVector.lastElement();
panel.scrollRectToVisible(tf.getBounds());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ScrollTesting scrollTesting = new ScrollTesting();
}
});
}
}

Categories

Resources