Adding a custom component manually in swing group layout - java

I have this class which creates a grid:
class GridPane extends JPanel{
public GridPane(int row,int col){
setLayout(new GridLayout(row,col));
setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
for (int i =1; i<=(row*col); i++)
{
JPanel pan = new JPanel();
pan.setBackground(Color.RED);
pan.setPreferredSize(new Dimension(3,3));
pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(pan);
}
}
And this which sets up the empty main frame with the group layout:
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGap(0, 440, Short.MAX_VALUE)
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGap(0, 268, Short.MAX_VALUE)
);
contentPane.setLayout(gl_contentPane);
}
I am not very experienced with SWING and I have been trying to add a GridPane object to the Right of the Main Frame for some time. It keeps telling me something like :
java.lang.IllegalStateException: GridPane[,0,0,0x0,invalid,layout=java.awt.GridLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.border.EmptyBorder#6ba7508a,flags=9,maximumSize=,minimumSize=,preferredSize=] is not attached to a vertical/horizontal group
Does anyone know what is going on? What should I do to accomplish what I need? Sorry for posting lots of code. Thanks for the help.

I would suggest that in this case you make use of BorderLayout.
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(pan, BorderLayout.LINE_END);
Here is the full code. I hope this is what you are looking for.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
GridPane gp = new GridPane(5, 5);
frame.add(gp, BorderLayout.EAST);
frame.setVisible(true);
frame.setSize(250, 250);
}
}
class GridPane extends JPanel {
public GridPane(int row, int col) {
setLayout(new GridLayout(row, col));
setPreferredSize(new Dimension(125, 125));
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
for (int i = 1; i <= (row * col); i++) {
JPanel pan = new JPanel();
pan.setBackground(Color.RED);
pan.setPreferredSize(new Dimension(3, 3));
pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(pan);
}
}
}
Useful links:
A Visual Guide to Layout Managers
How to Use BorderLayout
How to Use GroupLayout

Related

How to use any other layout manager for jscrollpane with it instead of using null layout

I had created this view by using null layout:
This is the Code i had used to create above layout
public class Page1311 extends JPanel {
// private JTable table;
// public JScrollPane pane=null;
public JPanel panel=null;
public JButton back=null;
/**
* Create the panel.
*/
public Page1311() {
setLayout(null);
back = new JButton("back");
back.setFont(new Font("Arial", Font.PLAIN, 20));
back.setBounds(10,10, 150, 27);
add(back);
List<List<String>> list=new ArrayList<List<String>>();
for(int j=0;j<=5;j++)
{
List<String> list1=new ArrayList<>();
list1.add("Honda Showroom"+j);
list1.add("Mandsaur");
list1.add("25 Chakrawati Colony Railway Station Road");
list1.add("Activa");
list1.add("2017");
list1.add("Honda");
list.add(list1);
}
getLayout(list,this);
back = new JButton("back");
back.setFont(new Font("Arial", Font.PLAIN, 20));
back.setBounds(10,10, 150, 27);
add(back);
}
public static void getLayout(List<List<String>> list,JPanel pane)
{
int i=0;
int x=100;
int y=100;
int height=20;
int width=200;
int size=list.size();
JLabel[] lblSName=new JLabel[size];
JLabel[] lblSAddress=new JLabel[size];
JLabel[] lblSCity=new JLabel[size];
JLabel[] lblVName=new JLabel[size];
JLabel[] lblVVersion=new JLabel[size];
JLabel[] lblVCompanies=new JLabel[size];
JButton[] lblGo=new JButton[size];
Iterator<List<String>> it=list.iterator();
while(it.hasNext())
{
System.out.println(x+" "+y+" "+width+" "+height+" "+i);
Iterator iit=it.next().iterator();
lblSName[i]= new JLabel();
lblSName[i].setText("Name:"+iit.next());
lblSName[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
lblSName[i].setBounds(x,y,width,height);
pane.add(lblSName[i]);
lblSCity[i] = new JLabel();
lblSCity[i].setText("City:"+iit.next());
lblSCity[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+240)+" "+y+" "+width+" "+height+" "+i);
lblSCity[i].setBounds(x+240,y,width,height);
pane.add(lblSCity[i]);
lblSAddress[i]= new JLabel();
lblSAddress[i].setText("Address:"+iit.next());
lblSAddress[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+470)+" "+y+" "+(width+256)+" "+height+" "+i);
lblSAddress[i].setBounds(x+470,y, width+256, height);
pane.add(lblSAddress[i]);
lblVName[i]= new JLabel();
lblVName[i].setText("Vehicle Name:"+iit.next());
lblVName[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println(x+" "+(y+35)+" "+width+" "+height+" "+i);
lblVName[i].setBounds(x,y+35,width, height);
pane.add(lblVName[i]);
lblVVersion[i] = new JLabel();
lblVVersion[i].setText("Vehicle Version:"+iit.next());
lblVVersion[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+240)+" "+y+35+" "+width+" "+height+" "+i);
lblVVersion[i].setBounds(x+240,y+35, width, height);
pane.add(lblVVersion[i]);
lblVCompanies[i]= new JLabel();
lblVCompanies[i].setText("Vehicle Companies:"+iit.next());
lblVCompanies[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+470)+" "+(y+35)+" "+(width+256)+" "+height+" "+i);
lblVCompanies[i].setBounds(x+470,y+35, width+256,height);
pane.add(lblVCompanies[i]);
lblGo[i]= new JButton("Go ");
lblGo[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 15));
System.out.println(x+" "+(y+70)+" "+(width-130)+" "+height+" "+i);
lblGo[i].setBounds(x,y+70,width-130, height);
pane.add(lblGo[i]);
i++;
y=y+160;
System.out.println("new height"+y);
}
}
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.add(new Page1311());
frame.setExtendedState(frame.MAXIMIZED_BOTH);
frame.setLocation(0, 0);
frame.setVisible(true);
}
}
But now i found that i cant use jscrollpane with null layout manager.So i want to create same layout by using any other layout manager.Can any one please help with with this or you can provide me any other way to use jscrollpane with null layout manager.
Thanks in advance
I'd use a combination of a GridBagLayout for each 'show room' panel, then a single column GridLayout panel to stack the collection of show room panels in a single container. The second panel would go in the scroll pane.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ShowRoomLayout {
private JComponent ui = null;
ShowRoomLayout() {
initUI();
}
private JPanel getShowRoomPanel(int num) {
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(new TitledBorder("GridBagLayout"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
p.add(new JLabel("Name:Honda Showroom" + num), gbc);
gbc.gridx = 1;
p.add(new JLabel("City:Mandsaur"), gbc);
gbc.gridx = 2;
p.add(new JLabel("Address:25 Chakrawati Colony Railway Station Road"), gbc);
gbc.gridy = 1;
gbc.gridx = 0;
p.add(new JLabel("Vehicle Name:Activa"), gbc);
gbc.gridx = 1;
p.add(new JLabel("Vehicle Version:2017"), gbc);
gbc.gridx = 2;
p.add(new JLabel("Vehicle Companies:Honda"), gbc);
gbc.gridy = 2;
gbc.gridx = 0;
p.add(new JButton("Go"), gbc);
return p;
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel pList = new JPanel(new GridLayout(0, 1, 3, 3));
pList.setBorder(new TitledBorder("GridLayout"));
for (int ii = 1; ii < 21; ii++) {
pList.add(getShowRoomPanel(ii));
}
JScrollPane scrollPane = new JScrollPane(pList,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
ui.add(scrollPane);
}
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) {
}
ShowRoomLayout o = new ShowRoomLayout();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
Dimension d = f.getSize();
f.setSize(new Dimension(d.width, 400));
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
JScrollPane has its own layout: ScrollPaneLayout. If you want to use any other, you don't set it on the scroll pane itself, you put a JPanel inside it and set the layout on that panel.
Another way without the need to set any layout manager for the JScrollPane is the method
JScrollPane.setViewportView(Component);
This is my preferred way. No size or layout handling on the fly.
If you want to place several Components to the same JScrollPane, just put a JPanel in between. The JPanel can have your preferred Layout.
If your layout uses a null layout manager, you need to tell the scroll pane the size of your component
JPanel pane = new JPanel(){
Dimension d = new Dimension(400, 400);
#Override
public Dimension getMinimumSize(){
return d;
}
#Override
public Dimension getPreferredSize(){
return d;
}
#Override
public Dimension getMaximumSize(){
return d;
}
#Override
public void paintComponent(Graphics g){
g.setColor(Color.RED);
g.fill3DRect(25, 25, 350, 350, true);
}
};
pane.setLayout(null);
JFrame frame = new JFrame("check");
frame.setSize(200, 200);
frame.add(new JScrollPane(pane));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
For this, I set the size of the pane to be 400, 400. The scroll pane will respect this. If you comment out the overriden methods, you'll see the scroll doesn't work anymore.
For OP to apply this technique they would just have to change the line where they add the panel to the JFrame.
frame.add(new JScrollPane(new Page1311()));
Since Page1311 doesn't use a layout manager then they need to override, getMin/Max/Preferred. as I did in my example. That would wrap the custom JPanel with a scroll pane, and the content would be scrollable.

Add dynamically jpanels

I want to generate multiple panels (with title, desc and detail button), this is the general structure:
But when I put this code in a for loop it always adds the last item.
Panel panel_1 = new Panel();
panel_1.setBounds(23, 134, 378, 208);
JLabel lblNewLabel_2 = new JLabel("desc");
lblNewLabel_2.setBounds(0, 69, 189, 69);
JButton btnNewButton_2 = new JButton("Details");
btnNewButton_2.setBounds(104, 139, 189, 69);
panel_1.setLayout(null);
JLabel lblPrv = new JLabel("title");
lblPrv.setBounds(104, 0, 189, 69);
panel_1.add(lblPrv);
panel_1.add(lblNewLabel_2);
JLabel label_1 = new JLabel("");
label_1.setBounds(0, 69, 189, 69);
panel_1.add(label_1);
panel_1.add(btnNewButton_2);
Any suggestion?
Here is an example of how to place multiple panels next to each other:
public class Example extends JFrame {
Example() {
setLayout(new FlowLayout());
for (int i = 0; i < 4; i++)
add(new MyPanel());
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
class MyPanel extends JPanel {
MyPanel() {
setLayout(new BorderLayout());
add(new JLabel("title", SwingConstants.CENTER), BorderLayout.PAGE_START);
add(new JLabel("<html>WWWWWW WWWWWWW<p>WWWWWWWWW<p>RRRRRRR RRRRR RRRRRRR"));
add(new JButton("Details"), BorderLayout.PAGE_END);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Example());
}
}
You should pick the layout managers best suited for your situation.

JTable in JPanel Not Displaying

I don't understand where is the problem. The JTable is embedded in a JScrollPanel which is embedded in a JPanel. The table is not displaying. Any help appreciated. I probably missed to add some elements. Checked thoroughly but cannot find anything. This is just the constructor:
public TableIssues() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 894, 597);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel patientsPanel = new JPanel();
patientsPanel.setBounds(6, 152, 882, 417);
patientsPanel.setLayout(null);
String[] patientsColumns = {
"one",
"two",
"three"};
String[][] tableInput={{"first","second","third"},{"first","second","third"}};
patientsTable = new JTable(tableInput,patientsColumns);
JScrollPane scroll = new JScrollPane();
scroll.setBounds(0, 0, 882, 363);
scroll.setLayout(null);
scroll.setViewportView(patientsTable);
patientsPanel.add(scroll);
JButton addPatietsButton = new JButton("Add");
addPatietsButton.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
addPatietsButton.setBounds(356, 375, 211, 36);
patientsPanel.add(addPatietsButton);
contentPane.add(patientsPanel);
}
NEVER do this:
scroll.setLayout(null);
You ruin the JScrollPane's layout, and so it completely loses its functionality, thereby shooting yourself in the foot. Remove that line.
While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example, this GUI
is created by this code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableIssues2 extends JPanel {
private static final int GAP = 5;
private static final String[] COL_NAMES = {"One", "Two", "Three"};
private DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0);
private JTable patientsTable = new JTable(model);
public TableIssues2() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
buttonPanel.add(new JButton("Add"));
buttonPanel.add(new JButton("Remove"));
buttonPanel.add(new JButton("Exit"));
JPanel bottomPanel = new JPanel();
bottomPanel.add(buttonPanel);
for (int i = 0; i < 5; i++) {
model.addRow(new String[]{"First", "Second", "Third"});
}
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(new JScrollPane(patientsTable), BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
TableIssues2 mainPanel = new TableIssues2();
JFrame frame = new JFrame("TableIssues2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How to Center Jpanel in JFrame?

There is a class which extends JFrame. then Further JFrame have JPanel named contentPane and this Jpanel contains 2 more jpanel. as Tree shown in picture.
I Want to Center that contentPane in JFrame so that on changing size of JFrame JPanel (contentPane) will remain in center. I have tried with different Layouts but did not come up with right one. is there any way ?
Full page picture is here
Code is this.
public class Purchases extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Purchases frame = new Purchases();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 513, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 477, 193);
contentPane.add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(10, 214, 477, 174);
contentPane.add(panel_1);
panel_1.setLayout(null);
}
This code is Eclipse automatically generated. I did not find where the contentPane is added in JFrame.
Set the frame's layout to GridBagLayout. Wrap your existing content in another JPanel, add this panel to the frame
For example
Take a look at Laying Out Components Within a Container and How to Use GridBagLayout for more details
You really should avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
I have made a sample for you. Modify it as per your need. Just want to show you what you want, is working.
TestClass()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 513, 438);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
JButton b1 = new JButton("hello");
JPanel panel = new JPanel(new BorderLayout());
//panel.setBounds(10, 10, 477, 193);
panel.add(b1, BorderLayout.CENTER);
contentPane.add(panel, BorderLayout.EAST);
//panel.setLayout(null);
JButton b2 = new JButton("why");
JPanel panel_1 = new JPanel(new BorderLayout());
//panel_1.setBounds(10, 214, 477, 174);
panel_1.add(b2, BorderLayout.CENTER);
contentPane.add(panel_1, BorderLayout.WEST);
//panel_1.setLayout(null);
this.getContentPane().add(contentPane);
}
Hope this will help. :-)
I think you should set the maximum size of the element & set it to align center:
setAlignmentX(JComponent.CENTER_ALIGNMENT);
setMaximumSize(new Dimension(100, 100));
As explained here:
How can I properly center a JPanel ( FIXED SIZE ) inside a JFrame?

Adding components to JScrollPane dynamically

I am new to Java Swing I want to develop an POS application which is like this image:
To develop this application I am using Eclipse, I have created JPanel which is shown by numbers e.g(1, 2) in image. At no 3 I have added JscrollPan which contain JPanel, now I want to do here when I click a button from panel no 2 that should add new buttons in panel no 3 dynamically and at that time I want to show only three buttons at each line and scroll should be activate only vertically when needed. But I am not able to do that, because when I write scrollPanel.setPreferredSize(new Dimension(2, 3)); vertical scroll cannot work. My Code is here:
public class WelcomeUI extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WelcomeUI frame = new WelcomeUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public WelcomeUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setUndecorated(true);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
header = new JPanel();
header.setForeground(Color.BLUE);
FlowLayout fl_header = (FlowLayout) header.getLayout();
fl_header.setAlignment(FlowLayout.RIGHT);
fl_header.setVgap(40);
fl_header.setHgap(0);
header.setBackground(Color.BLUE);
contentPane.add(header, BorderLayout.NORTH);
footer = new JPanel();
FlowLayout flowLayout = (FlowLayout) footer.getLayout();
flowLayout.setVgap(10);
footer.setBackground(Color.BLUE);
contentPane.add(footer, BorderLayout.SOUTH);
panel_2 = new JPanel();
panel_2.setBackground(Color.BLUE);
contentPane.add(panel_2, BorderLayout.WEST);
JButton btnSelectRestaurant = new JButton("Select Restaurant");
btnSelectRestaurant.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createDynamicButton(e);
}
});
JButton btnNewButton = new JButton("Select Steward");
JButton btnNewButton_1 = new JButton("Select Table");
JButton btnNewButton_2 = new JButton("Misc keys");
GroupLayout gl_panel_2 = new GroupLayout(panel_2);
gl_panel_2.setHorizontalGroup(
gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addGap(19)
.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
.addComponent(btnNewButton, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addComponent(btnSelectRestaurant, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnNewButton_1, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addComponent(btnNewButton_2, Alignment.TRAILING, 0, 0, Short.MAX_VALUE))
.addContainerGap())
);
gl_panel_2.setVerticalGroup(
gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addGap(26)
.addComponent(btnSelectRestaurant, GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 47, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNewButton_1, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNewButton_2, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)
.addContainerGap(438, Short.MAX_VALUE))
);
gl_panel_2.setAutoCreateContainerGaps(true);
gl_panel_2.setAutoCreateGaps(true);
panel_2.setLayout(gl_panel_2);
panel_3 = new JPanel();
FlowLayout flowLayout_2 = (FlowLayout) panel_3.getLayout();
flowLayout_2.setHgap(250);
contentPane.add(panel_3, BorderLayout.EAST);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
scrollPanel = new JPanel();
scrollPanel.setPreferredSize(new Dimension(2, 3));
scrollPane.setViewportView(scrollPanel);
}
protected void createDynamicButton(ActionEvent e) {
JButton dynButton = new JButton("My Button");
dynButton.setPreferredSize(new Dimension(300, 200));
scrollPanel.add(dynButton);
scrollPanel.validate();
scrollPanel.revalidate();
}
private JPanel header;
private JPanel footer;
private JPanel panel_2;
private JPanel panel_3;
private JPanel scrollPanel;
private JScrollPane scrollPane;
}
So, please tell me where I am doing wrong. Thanks in advance.
Focusing on panel 3, consider the following:
Give the panel a GridLayout(0, 3), which specifies an arbitrary number rows in three columns.
Implement the Scrollable interface, and let getPreferredScrollableViewportSize() return a a Dimension that is a multiple of the button height.
As each button is added, give it a suitable Action.
When adding a button, revalidate() the panel and repaint() it.
I got the answer, actually the problem is, I have set maximum size for panel and all dynamically generated buttons placed at single line, that are added till max size not encountered, but functions cannot communicate other one hence we need to change size dynamically and that will happen by modifying FlowLayout interface.
you can use modified layout rather than FlowLayout.

Categories