m trying to add a Jslider and a Jlabel to PAGE_END beside each other, i can add each of them on their on but adding .add("components name".PAGE_END) to both it on lets one exist there?
so basicly i want to create my slider and a jlabel beside it to the right, could someone please help in anyway, thanks.
package assignment;
//import java.awt.FlowLayout;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MyControlPanel extends javax.swing.JPanel {
JSlider slider;
JLabel sliderLabel;
JLabel blank;
public MyControlPanel() {
slider = new JSlider();
slider.setValue(50);
slider.addChangeListener(new MyChangeAction());
slider.setMajorTickSpacing(10);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setBounds(300, 50, 100, 50);
sliderLabel = new JLabel("50");
blank = new JLabel(" ");
JTextField boundary_length = new JTextField("Boundary Length");
JTextField area = new JTextField("Area");
setLayout(new BorderLayout());
this.add(slider, BorderLayout.PAGE_END);
this.add(sliderLabel, BorderLayout.LINE_END);
this.add(area);
this.add(boundary_length);
this.add(blank, BorderLayout.LINE_START);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
public class MyChangeAction implements ChangeListener{
//complete code here
public void stateChanged(ChangeEvent ce)
{
int value = slider.getValue();
String str = Integer.toString(value);
sliderLabel.setText(str);
}
} // end class
Instead of using BorderLayout to place both the slider and the label, create a panel containing both components, then use BorderLayout to place the panel.
Replace
this.add(slider, BorderLayout.PAGE_END);
this.add(sliderLabel, BorderLayout.LINE_END);
With
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout( new FlowLayout(FlowLayout.TRAILING));
sliderPanel.add(slider);
sliderPanel.add(sliderLabel);
this.add(sliderPanel, BorderLayout.PAGE_END);
This is based on code I used to place an OK and Cancel button at the bottom of a dialog. This might not compile - but you get the idea. Play around with the arguments to FlowLayout and change the order of adding to the slider panel until you get the look you want.
BTW - since you are doing the layout yourself - not using a GUI builder - you might as well get rid of the initComponents method and the surrounding comments. I'm guessing that you are using Netbeans and created a panel that was initially configured to use GroupLayout, and Netbeans injected that code. Now it's just getting in the way.
Related
I am trying to layout my JPanel such that:
The information label is at the top,
The text area is directly below, this and the info label go across (horizontally) the entire panel,
Below the text from left to right (equally spaced) are the config, save and then clear buttons,
Below those is the success/failure label (central, under the save button) and the home button (right, under the clear button).
I have tried many combinations and used other stack answers but cannot get it right, something about group layout I can't get my head around!
import javax.swing.*;
public class JFrameTest {
private static JFrame mainApp;
private static JPanel mainPanel;
public JFrameTest() {
mainApp = new JFrame("Application");
mainApp.setSize(640, 480);
mainApp.setLocationRelativeTo(null);
mainApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainApp.add(mainPanel());
mainApp.setVisible(true);
}
private JPanel mainPanel() {
JFrame.setDefaultLookAndFeelDecorated(true);
mainPanel= new JPanel();
mainPanel.setSize(600,450);
Container container = mainApp.getContentPane();
JLabel labelInfo = new JLabel("add necessary information here");
JLabel labelSOrF = new JLabel("Success/Failure");
// labelSOrF.setVisible(false);
JTextArea textArea = new JTextArea();
JButton configButton= new JButton("config");
JButton saveButton= new JButton("save");
JButton clearButton= new JButton("clear");
JButton homeButton= new JButton("Home");
GroupLayout layout = new GroupLayout(container);
container.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(configButton)
.addGroup(layout.createParallelGroup()
.addComponent(saveButton)
.addComponent(labelSOrF, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup()
.addComponent(clearButton)
.addComponent(homeButton)
.addComponent(labelInfo)
.addComponent(textArea, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
)))
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(labelInfo)
.addComponent(textArea, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addComponent(configButton)
.addComponent(saveButton)
.addComponent(buttonClear))
.addGroup(layout.createParallelGroup()
.addComponent(labelSOrF, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(homeButton)))
);
edit - added code
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
GroupLayout was designed for GUI builders. No human being will deliberately use a GroupLayout. It's too hard to understand and as you've discovered, maintain.
Here's a GUI that meets your requirements.
Swing was designed to be constructed from the inside out. You layout the Swing components and let the JPanels and the JFrame size themselves. You don't start with the JFrame and fit all the Swing components.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
I created a main JPanel with three subordinate JPanels. To construct a complex GUI, you nest simple JPanels.
I added the Swing components to each JPanel in column, row order. That helps me to organize the code and makes it easier for readers of your code to understand the code.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
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.JTextArea;
import javax.swing.SwingUtilities;
public class JFrameTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JFrameTest());
}
#Override
public void run() {
JFrame mainApp = new JFrame("Application");
mainApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainApp.add(createMainPanel(), BorderLayout.CENTER);
mainApp.pack();
mainApp.setLocationRelativeTo(null);
mainApp.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(createTitlePanel());
panel.add(createTextAreaPanel());
panel.add(createButtonPanel());
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JLabel labelInfo = new JLabel("add necessary information here");
panel.add(labelInfo);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JTextArea textArea = new JTextArea(5, 40);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scrollPane);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridLayout(0, 3, 20, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton configButton = new JButton("config");
panel.add(configButton);
JButton saveButton = new JButton("save");
panel.add(saveButton);
JButton clearButton = new JButton("clear");
panel.add(clearButton);
JLabel dummy = new JLabel(" ");
panel.add(dummy);
JLabel labelSOrF = new JLabel("Success/Failure");
panel.add(labelSOrF);
JButton homeButton = new JButton("Home");
panel.add(homeButton);
return panel;
}
}
Is setting preferred size of JFrame using setPreferredSize() considered bad?
If it is bad, what is good way to change JFrame window size to dimension I need.
I know laying components in way to reflect final JFrame dimension that I need. But if I use shortcut to change preferred size using call setPreferredSize() just before call to pack() to change final JFrame size is bad? If so why?
For example I have sample form:
This is displayed without setting preferred size.
Now I can resize form with call to setPreferredSize() before call to pack().
This is displayed with call: setPreferredSize(new Dimension(500, 300));
I can have similar effect with setting components size while laying it out. But what is disadvantage of setting frame size with just call to setPreferredSize().
I can think setting preferred size as resizing displayed window manually with mouse after it has been displayed. Isn't it?
Code:
import java.awt.Dimension;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField fullNameTextField = new JTextField();
private JTextField emailIDTextField = new JTextField();
private JTextArea addressTextArea = new JTextArea();
private JButton submitButton = new JButton("Submit");
private JButton cancelButton = new JButton("Cancel");
public MyFrame(){
super("MyFrame");
layoutComponents();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
setPreferredSize(new Dimension(500, 300));
pack();
}
private void layoutComponents(){
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
JLabel fullNameLabel = new JLabel("Full Name:");
JLabel emailIDLabel = new JLabel("Email ID:");
JLabel addressLabel = new JLabel("Address:");
JScrollPane addressScrollPane = new JScrollPane(addressTextArea);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(fullNameLabel)
.addComponent(emailIDLabel)
.addComponent(addressLabel)
)
.addGap(15)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(fullNameTextField, 10, 200, Short.MAX_VALUE)
.addComponent(emailIDTextField)
.addComponent(addressScrollPane)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(submitButton)
.addGap(10)
.addComponent(cancelButton)
)
)
)
)
.addGap(10)
)
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(fullNameLabel)
.addComponent(fullNameTextField)
)
.addGap(5)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(emailIDLabel)
.addComponent(emailIDTextField)
)
.addGap(5)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(addressLabel)
.addComponent(addressScrollPane, 20, 60, Short.MAX_VALUE)
)
.addGap(15)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(submitButton)
.addComponent(cancelButton)
)
.addGap(10)
)
);
layout.linkSize(submitButton, cancelButton);
getRootPane().setDefaultButton(submitButton);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyFrame().setVisible(true);
}
});
}
}
The main reason it would be considered bad (bad is probably too strong a word, unwise might be better) is the use of unknown (magic) numbers, rather than empirical values.
Every platform (and even similar OS running on different hardware and settings) has it's own means for rendering content which can change the amount of space that individual components require.
In regards to things like text fields and text-areas, you can make suggestions about the number of columns (and rows for text areas) which can be used to change a frames final size, using setColumns and setRows for example...
So, using the following code...
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout101 {
public static void main(String[] args) {
new TestLayout101();
}
public TestLayout101() {
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 JTextField fullNameTextField = new JTextField(10);
private JTextField emailIDTextField = new JTextField(10);
private JTextArea addressTextArea = new JTextArea(10, 20);
private JButton submitButton = new JButton("Submit");
private JButton cancelButton = new JButton("Cancel");
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JLabel("Full Name: "), gbc);
gbc.gridy++;
add(new JLabel("Email ID: "), gbc);
gbc.gridy++;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(new JLabel("Address: "), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(fullNameTextField, gbc);
gbc.gridy++;
add(emailIDTextField, gbc);
gbc.gridy++;
gbc.weighty = 1;
add(new JScrollPane(addressTextArea), gbc);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 4));
buttons.add(submitButton);
buttons.add(cancelButton);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 0;
add(buttons, gbc);
}
}
}
Which produces...
Now by changing only one line...
private JTextArea addressTextArea = new JTextArea(10, 20);
// Only this value ---^
It produces this...
And again...
private JTextArea addressTextArea = new JTextArea(10, 40);
// Only this value ---^
I could change the number of rows for the JTextArea and effect the height of the window as well.
The difference is, these values are used in combination with the systems font metrics to calculate the preferred size of the components when the program is run, so it will be different for different systems and platforms...
The main point to layouts is to spend your time focused on the intent and the work flow and not trying to get a pixel perfect solution, because there's simply no such thing...talk to web developers, they have the same issues, just much worse (multiple browsers on a single system, all rendering differently)
Personally, I think there is nothing wrong with using frame.setPreferredSize() to resize a JFrame window. In fact, I think it is the most appropriate solution for resizing it.
But this is a good time to make a distinction between what some of the most common resizing methods do:
frame.pack(), as explained here basically takes the prefered sizes for each of the individual elements.
frame.setSize() resizes the window as expected, but only if a component's parent has no layout manager expressly defined.
There is a discussion concerning the use of this method here.
That doesn't really leave any other methods to use to define the size of a window, which is why I think setting the preferred window size is the best way go about it. I would still make sure to define setMinimumSize() and setMaximumSize() to ensure the components are resized correctly in all cases.
Edit:
Other posts in this thread got me thinking about the use of 'magic constants' in setting a components. In web development, for instance, it is generally frowned upon to use pixels, for example, as this changes widely by system. I wanted to see if this was also true with dimensions. In short, my findings concluded it doesn't.
This was a JFrame with a prefered size of new Dimension(200, 300) taken on my MacBook Pro with Retina Display:
This was a JFrame with a prefered size of new Dimension(200, 300) taken on my Asus Windows Tablet (non-retina display):
These windows looked the exact same and, although I couldn't find this published, the Dimenion is really an already-scaled proportion, taking into consideration the height, width, and resolution of the display to produce a near accurate rendering across all devices. This, I guess you could say, makes sense because it is the Java way.
That being said, here's some things I think need to watched out for:
The difference between UIManager LookAndFeel across platforms as MadProgrammer pointed out
Honestly, I think the final decision is left up to the programmer. After this testing, I pretty much still conclude that using the frame.setPreferredSize() is one of the best things available if you don't intend to a implement a semi-complex window manager. Even then, I think there will always be some unaccounted variation.
I am programming a small application and have run into a big bump. I am stuck on why the JSlider won't allow me to add it to the JPanel.
When the last line of code reads:
"add.(slider);"
the JSlider covers the entire JPanel. Is this correct and I need to resize my JSlider somehow? Or, have I made a mistake with the code and are not making the Jslider visible within the Jpanel?
Here's my code:
package atmosfile;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JSlider;
import java.awt.*;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public Main() {
super("Package Choice");
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(1, 100, 500));
panel.add(new JButton("Package 1"));
panel.add(new JButton("Package 2"));
panel.add(new JButton("Package 3"));
add(panel);
JSlider slider = new JSlider();
slider.setLayout(new FlowLayout(1, 100, 200));
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
slider.setSize(200, 200);
slider.setVisible(true);
panel.add(slider);
}
}
Thanks in advance for any help its most appreciated!
The horizontal gap of your FlowLayout is so large that it "pushes" the JSlider component out of the drawable area of the frame. Reducing it brings it back in into view again. Also would recommend avoiding the use of magic numbers (1 = FlowLayout.CENTER):
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 50, 500));
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.
Why is the label not displaying?
package javaapplication4;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class settingPanel extends javax.swing.JPanel {
static JPanel con = new JPanel();
static JFrame frame = new JFrame();
JLabel jLabel1 = new JLabel();
public JEditorPane htmlvi = new JEditorPane();
/** Creates new form settingPanel */
public settingPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4",
"Item 5" };
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addGroup(
jPanel1Layout
.createSequentialGroup()
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE, 70,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(325, Short.MAX_VALUE)));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addComponent(
jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 272,
Short.MAX_VALUE));
jTabbedPane1.addTab("tab1", jPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addComponent(
jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400,
Short.MAX_VALUE));
layout.setVerticalGroup(layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addComponent(
jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300,
Short.MAX_VALUE));
}// </editor-fold>
private void addpanel() {
JPanel pnl = new JPanel();
pnl.setOpaque(false);
pnl.setLayout(new GridBagLayout());
pnl.add(new JButton());
pnl.setVisible(true);
jPanel1.setLocation(10, 30);
jPanel1.add(pnl);
}
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
JLabel write = new JLabel();
// if(evt.getValueIsAdjusting()){
String read = "<html><h2>" + jList1.getSelectedValue().toString()
+ "<UL>USB";
addpanel();
jPanel1.add(write);
}
// Variables declaration - do not modify
private javax.swing.JList jList1;
public static javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
public static void main(String args[]) {
frame.add(new settingPanel());
// jPanel2.setLayout(new GridBagLayout());
// jPanel2.add(new JButton());
// jPanel2.setVisible(false);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}
}
You add your JLabel to jPanel1, which uses a GroupLayout to display its components. The GroupLayout needs to know where each component must be placed in its vertical and horizontal group, and it doesn't know where to put your new label, since you didn't tell.
I very much doubt that your end goal is to add a new label to your GUI each time the selection changes. You should probably add a unique label with a default text when the GUI is initialized, and change the text of this label when the selection changes.