public class Gridlayout extends JFrame {
public Gridlayout()
{
setTitle("xxx");
setSize(540,635);
this.setResizable(false);
this.setLocation(500,50);
initComponents();
setDefaultCloseOperation(3);
}
JLabel etykieta = new JLabel("Poziom trudności: ");
JPanel top = new JPanel(new GridLayout(2, 2));
JPanel mid = new JPanel(new GridLayout(0, 1));
JPanel bot = new JPanel(new GridLayout(1, 0));
JButton start= new JButton("Start");
JButton zakoncz = new JButton("Zakoncz");
JRadioButton latwy = new JRadioButton("Łatwy");
JRadioButton sredni = new JRadioButton("Średni");
JRadioButton trudny = new JRadioButton("Trudny");
ButtonGroup poziomTrudnosci= new ButtonGroup();
public void initComponents() {
this.getContentPane().add(top, BorderLayout.NORTH);
this.getContentPane().add(mid, BorderLayout.CENTER);
this.getContentPane().add(bot, BorderLayout.SOUTH);
start.setPreferredSize(new Dimension(1, 40));
zakoncz.setPreferredSize(new Dimension(1, 40));
mid.add(etykieta);
mid.add(latwy);
mid.add(sredni);
mid.add(trudny);
bot.add(start);
poziomTrudnosci.add(latwy);
poziomTrudnosci.add(sredni);
poziomTrudnosci.add(trudny);
}
public static void main(String[] args) {
new Gridlayout().setVisible(true);
}
}
How can I move this button from the left to the center of the window? They should stay close. I was trying everything but they still are on the left side.
If I understand your question correctly, you want to horizontally center the JRadioButtons in the JFrame, yes? Try the setHorizontalAlignment() method. Add the following lines to your initComponents() function:
latwy.setHorizontalAlignment(JRadioButton.CENTER);
sredni.setHorizontalAlignment(JRadioButton.CENTER);
trudny.setHorizontalAlignment(JRadioButton.CENTER);
Related
I'm currently building GUI with Java Swing.
My current code produces this.
The JTextArea of Product List makes the GUI looks awkward, how can I make the JTextArea looks like this, where it seems to have an extra row:
The GroupLayout code I'm using is:
gr.setVerticalGroup(gr.createSequentialGroup()
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(productName).addComponent(productText).addComponent(productList))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(amount).addComponent(amountText).addComponent(prodScroll))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(description).addComponent(desScroll))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(addButton).addComponent(remButton)));
gr.setHorizontalGroup(gr.createSequentialGroup()
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(productName).addComponent(amount).addComponent(description).addComponent(addButton))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.CENTER).addComponent(productText).addComponent(amountText).addComponent(desScroll).addComponent(remButton))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.CENTER).addComponent(productList).addComponent(prodScroll)));
I think the minority of people would choose to use GridBagLayout. However, I dislike it (among with GroupLayout) since it is "hard to use". I use nested panels instead with various Layout Managers. Using only BorderLayout and GridLayout you can achieve something like the following example, which is totally resizable, giving emphasis to "interaction" components (I mean, there is no reason to resize a constant-texted JLabel, right?)
I did not add any comments in purpose, so you can experiment with constants (and layout constraints) and see their reason of existence while having the documentations opened.
Code:
public class NestedLayoutManagersExample extends JFrame {
private static final long serialVersionUID = -7042997375941726246L;
private static final int labelsWidth = 80;
private static final int textFieldColumns = 15;
private static final int spaceBetweenAllComponents = 10;
public NestedLayoutManagersExample() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel contentPane = new JPanel(new GridLayout(1, 2, 50, 50));
contentPane.setBorder(BorderFactory.createEmptyBorder(spaceBetweenAllComponents, spaceBetweenAllComponents,
spaceBetweenAllComponents, spaceBetweenAllComponents));
setContentPane(contentPane);
add(createLeftPanel());
add(createRightPanel());
setLocationByPlatform(true);
pack();
}
private Component createRightPanel() {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel productListLabel = new JLabel("Product list");
mainPanel.add(productListLabel, BorderLayout.PAGE_START);
JList<String> productList = new JList<>();
DefaultListModel<String> listModel = new DefaultListModel<>();
Arrays.asList("Small Chair", "Big Chair", "Flying Chair").forEach(listModel::addElement);
productList.setModel(listModel);
JScrollPane listScrollPane = new JScrollPane(productList);
mainPanel.add(listScrollPane, BorderLayout.CENTER);
return mainPanel;
}
private Component createLeftPanel() {
JPanel mainPanel = new JPanel(new BorderLayout(spaceBetweenAllComponents, spaceBetweenAllComponents));
JPanel topPanel = new JPanel(new GridLayout(2, 1, spaceBetweenAllComponents, spaceBetweenAllComponents));
topPanel.add(createStraightPanel("Product Name"));
topPanel.add(createStraightPanel("Amount"));
mainPanel.add(topPanel, BorderLayout.PAGE_START);
JPanel centerPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("<html><p style='width:" + labelsWidth + "px';> Description");
label.setVerticalAlignment(JLabel.TOP);
centerPanel.add(label, BorderLayout.LINE_START);
centerPanel.add(createTextAreaPanel());
mainPanel.add(centerPanel, BorderLayout.CENTER);
return mainPanel;
}
private JPanel createTextAreaPanel() {
JPanel mainPanel = new JPanel(new BorderLayout(spaceBetweenAllComponents, spaceBetweenAllComponents));
JTextArea textArea = new JTextArea(1, textFieldColumns);
JScrollPane textAreaScrollPane = new JScrollPane(textArea);
mainPanel.add(textAreaScrollPane, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel(new BorderLayout());
JButton addButton = new JButton("Add");
buttonsPanel.add(addButton, BorderLayout.LINE_START);
JButton removeButton = new JButton("Remove");
buttonsPanel.add(removeButton, BorderLayout.LINE_END);
mainPanel.add(buttonsPanel, BorderLayout.PAGE_END);
return mainPanel;
}
private Component createStraightPanel(String labelText) {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("<html><p style='width:" + labelsWidth + "px';>" + labelText);
mainPanel.add(label, BorderLayout.LINE_START);
JTextField textField = new JTextField(textFieldColumns);
mainPanel.add(textField, BorderLayout.CENTER);
return mainPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new NestedLayoutManagersExample().setVisible(true));
}
}
Preview:
I have the GUI displaying properly for the most part, except for one thing. The TitledBorder("Numeric Type") does not display the entire title for the right JPanel. I believe it has something to do with the BorderLayout Manager. Instead of displaying "Numeric Type" within the border, just "Numeric..." displays. Any help will be greatly appreciated.
public class P3GUI extends JFrame {
private JLabel originalList;
private JTextField originalSort;
private JLabel sortedList;
private JTextField newSort;
private JPanel panel;
private JButton performSort;
private JRadioButton ascending;
private JRadioButton descending;
private ButtonGroup sort;
private JRadioButton integer;
private JRadioButton fraction;
private ButtonGroup numType;
private JPanel inputPanel, outputPanel, calculatePanel, radioPanel;
private JPanel left, right;
public P3GUI () {
super("Binary Search Tree Sort");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
originalList = new JLabel("Original List");
originalSort = new JTextField(20);
inputPanel = new JPanel();
inputPanel.add(originalList);
inputPanel.add(originalSort);
sortedList = new JLabel("Sorted List");
newSort = new JTextField(20);
newSort.setEditable(false);
outputPanel = new JPanel();
outputPanel.add(sortedList);
outputPanel.add(newSort);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(inputPanel);
panel.add(outputPanel);
add(panel, BorderLayout.NORTH);
performSort = new JButton("Perform Sort");
calculatePanel = new JPanel();
calculatePanel.add(performSort);
add(calculatePanel, BorderLayout.CENTER);
ascending = new JRadioButton("Ascending");
descending = new JRadioButton("Descending");
sort = new ButtonGroup();
sort.add(ascending);
sort.add(descending);
integer = new JRadioButton("Integer");
fraction = new JRadioButton("Fraction");
numType = new ButtonGroup();
numType.add(integer);
numType.add(fraction);
radioPanel = new JPanel();
radioPanel.setLayout(new FlowLayout());
left = new JPanel();
left.setLayout(new GridLayout(2,1));
left.setBorder(BorderFactory.createTitledBorder("Sort Order"));
left.add(ascending);
left.add(descending);
right = new JPanel();
right.setLayout(new GridLayout(2,1));
right.setBorder(BorderFactory.createTitledBorder("Numeric Type"));
right.add(integer);
right.add(fraction);
radioPanel.add(left);
radioPanel.add(right);
add(radioPanel, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new P3GUI().setVisible(true);
}
});
}
}
The problem is that the right JPanel is too small to display the entire title, and so it gets truncated. I'd suggest placing the bottom two JPanels into another that uses GridLayout, and then place them in such a way that they expand to fit the bottom of your GUI. When spread out, the title has a much greater chance of being fully displayed (but not a guarantee, mind you!).
For example, if you make the main GUI use a BorderLayout, and add this GridLayout using JPanel into the BorderLayout.CENTER position, it will fill it completely. Then the top components, the TextFields and JButton can be added to another JPanel, say one that uses a GridBagLayout, and add that to the main JPanel's BorderLayout.PAGE_START position.
For example, the following code produces this GUI:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class P3GUI2 extends JPanel {
private static final int COLS = 20;
private JTextField originalSort = new JTextField(COLS);
private JTextField newSort = new JTextField(COLS);
private JButton performSort = new JButton("Perform Sort");
private JRadioButton ascending = new JRadioButton("Ascending");
private JRadioButton descending = new JRadioButton("Descending");
private ButtonGroup sort = new ButtonGroup();
private JRadioButton integer = new JRadioButton("Integer");
private JRadioButton fraction = new JRadioButton("Fraction");
private ButtonGroup numType = new ButtonGroup();
public P3GUI2() {
JPanel topPanel = new JPanel(new GridBagLayout());
topPanel.add(new JLabel("Original List:"), createGbc(0, 0));
topPanel.add(originalSort, createGbc(1, 0));
topPanel.add(new JLabel("Sorted List:"), createGbc(0, 1));
topPanel.add(newSort, createGbc(1, 1));
performSort.setMnemonic(KeyEvent.VK_P);
JPanel btnPanel = new JPanel();
btnPanel.add(performSort);
JPanel sortOrderPanel = createTitlePanel("Sort Order");
JPanel numericPanel = createTitlePanel("Numeric Type");
sortOrderPanel.add(ascending);
sortOrderPanel.add(descending);
sort.add(ascending);
sort.add(descending);
numericPanel.add(integer);
numericPanel.add(fraction);
numType.add(integer);
numType.add(fraction);
JPanel radioPanels = new JPanel(new GridLayout(1, 0, 3, 3));
radioPanels.add(sortOrderPanel);
radioPanels.add(numericPanel);
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new BorderLayout(3, 3));
add(topPanel, BorderLayout.PAGE_START);
add(btnPanel, BorderLayout.CENTER);
add(radioPanels, BorderLayout.PAGE_END);
}
private JPanel createTitlePanel(String title) {
JPanel panel = new JPanel(new GridLayout(0, 1, 3, 3));
panel.setBorder(BorderFactory.createTitledBorder(title));
return panel;
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
return gbc;
}
private static void createAndShowGui() {
P3GUI2 mainPanel = new P3GUI2();
JFrame frame = new JFrame("Binary Search Tree Sort");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Or you could place the above btnPanel into the main one BorderLayout.CENTER and then place the radioPanels into the main one BorderLayout.PAGE_END. This will display a GUI of the same appearance but it will expand differently if re-sized.
The preferred size of the panel (as determined by the layout manager) does not consider the size of the text in the TitledBorder so the title can get truncated.
Here is a custom JPanel that can be used with a TitleBorder. The getPreferredSize() method has been customized to use the maximum width of:
the default getPreferredSize() calculation
the width of the text in the TitledBorder
Here is a simple example:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitledBorderPanel extends JPanel
{
/**
** The preferred width on the panel must consider the width of the text
** used on the TitledBorder
*/
#Override
public Dimension getPreferredSize()
{
Dimension preferredSize = super.getPreferredSize();
Border border = getBorder();
int borderWidth = 0;
if (border instanceof TitledBorder)
{
Insets insets = getInsets();
TitledBorder titledBorder = (TitledBorder)border;
borderWidth = titledBorder.getMinimumSize(this).width + insets.left + insets.right;
}
int preferredWidth = Math.max(preferredSize.width, borderWidth);
return new Dimension(preferredWidth, preferredSize.height);
}
private static void createAndShowGUI()
{
JPanel panel = new TitledBorderPanel();
panel.setBorder( BorderFactory.createTitledBorder("File Options Command List:") );
panel.setLayout( new BoxLayout(panel, BoxLayout.Y_AXIS) );
panel.add( new JLabel("Open") );
panel.add( new JLabel("Close") );
// panel.add( new JLabel("A really wierd file option longer than border title") );
JFrame frame = new JFrame("TitledBorderPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
Hello I am trying to add a border or a line break separating the north section from the rest of the JPanel. Basically using set border I have a border around the whole window but then want a line from one section of the border straight across horizontally to the other side. when i add a border to a JPanel that is added to BorderLayout.NORTH it puts a whole border inside the section. not the outline of the section. hope you know what i mean.
Attached I have a section of my code that is holding all my JPanel code in it so far. any help I would love, thanks.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class GamePanel extends JPanel {
private JTextPane playertext;
private JTextField wealthstring, currentwealth;
public GamePanel() {
super();
setLayout(new BorderLayout());
setBackground(Game.getBackgroundColor());
Border raised = BorderFactory.createRaisedBevelBorder();
Border lowered = BorderFactory.createLoweredBevelBorder();
setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(4, 4, 4, 4), (BorderFactory.createCompoundBorder(raised, lowered))));
add(northpanel(), BorderLayout.NORTH);
add(eastpanel(), BorderLayout.EAST);
}
private JPanel northpanel() {
Font northfont = new Font("Engravers MT", Font.BOLD, 12);
playertext = new JTextPane();
playertext.setFont(northfont);
playertext.setEditable(false);
playertext.setText("Player: \n" + Game.getName());
playertext.setBackground(Game.getBackgroundColor());
playertext.setBorder(new EmptyBorder(10,10,10,10));
wealthstring = new JTextField("Money: ");
wealthstring.setFont(northfont);
wealthstring.setEditable(false);
wealthstring.setHorizontalAlignment(wealthstring.RIGHT);
wealthstring.setBorder(null);
wealthstring.setBackground(Game.getBackgroundColor());
currentwealth = new JTextField();
currentwealth.setFont(northfont);
currentwealth.setEditable(false);
currentwealth.setHorizontalAlignment(wealthstring.RIGHT);
currentwealth.setBackground(Game.getBackgroundColor());
currentwealth.setBorder(null);
String wealthrounded = String.format("%.2f", Game.getMoney());
currentwealth.setText(wealthrounded);
JPanel wealthtext = new JPanel();
wealthtext.setLayout(new GridLayout(2, 1));
wealthtext.setBackground(Game.getBackgroundColor());
wealthtext.setBorder(new EmptyBorder(10,10,10,10));
wealthtext.add(wealthstring);
wealthtext.add(currentwealth);
JPanel northpanel = new JPanel();
northpanel.setLayout(new BorderLayout());
northpanel.setBackground(Game.getBackgroundColor());
northpanel.add(playertext, BorderLayout.WEST);
northpanel.add(wealthtext, BorderLayout.EAST);
return northpanel;
}
private JPanel eastpanel() {
JButton tab1 = new JButton("Tab 1");
JButton tab2 = new JButton("Tab 2");
JButton tab3 = new JButton("Tab 3");
JPanel easttabs = new JPanel();
easttabs.setLayout(new GridLayout(1, 3));
easttabs.add(tab1);
easttabs.add(tab2);
easttabs.add(tab3);
JPanel eastpanels = new JPanel();
eastpanels.setLayout(new BorderLayout());
eastpanels.add(easttabs, BorderLayout.NORTH);
return eastpanels;
}
}
Like this?
For that we would use a JSeparator.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class UnderlinePageStart {
private JComponent ui = null;
UnderlinePageStart() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel pageStart = new JPanel(new BorderLayout(2,2));
ui.add(pageStart, BorderLayout.PAGE_START);
pageStart.add(new JLabel("Page Start", SwingConstants.CENTER));
// add a 'horizontal line'
pageStart.add(new JSeparator(), BorderLayout.PAGE_END);
ui.add(new JScrollPane(new JTextArea(5, 25)));
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
UnderlinePageStart o = new UnderlinePageStart();
JFrame f = new JFrame("Underline Page Start");
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);
}
}
I wrote a program to compose a GUI using swing/awt framework for my assignment. So far, I am able to get the pieces working together, but when I put them all into a JFrame, they are not coming out as expected.
I have recently started working on Java GUI framework, and not sure what is missing in my code. How can I get this working properly?
I am also attaching the screen shots (see at the bottom) of the output I am getting.
public class MainFrame extends JFrame {
public MainFrame() {
addComponentsToPane(this.getContentPane());
}
private void addComponentsToPane(Container pane) {
// Set layout
GridBagConstraints gbc = new GridBagConstraints();
this.setTitle("Test tool");
this.setSize(600, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2, 1));
// Add video JComponent
mMainPanel = new MainPanel();
pane.add(mMainPanel, 0);
// Add conference screen panel
mFeedPanel = new FeedPanel();
pane.add(mFeedPanel, 1);
// Add a button panel
mButtonPanel = new ButtonPanel();
pane.add(mButtonPanel, 2);
this.setResizable(true);
this.setVisible(true);
this.pack();
}
}
// In actual output, there is 1 screen in this panel.
// mScreen1 is derived from JComponent object.
public class MainPanel() extends JPanel {
public MainPanel() {
addMainPanelComponents();
}
private void addMainPanelComponents() {
this.setSize(352, 240);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 2));
add(mScreen);
setVisible(true);
}
}
// In actual output, there are 3 screens in this panel. I have shown code for 1 screen only
// mScreen1 is derived from JComponent object.
public class FeedPanel extends JPanel {
public FeedPanel() {
addFeedPanelComponents();
}
private void addFeedPanelComponents() {
String img1 = "images/screen1.png";
setSize(352, 150);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 3));
Image image1 = ImageIO.read(new File(img1));
mScreen1.setImage(image1);
add(mScreen1);
setVisible(true);
}
}
public class ButtonPanel extends JPanel {
public ButtonPanel() {
addButtonPanelComponents();
}
private void addButtonPanelComponents() {
this.setSize(352, 150);
this.setBackground(Color.yellow);
this.setLayout(new GridLayout(1,
5));
// Add Button to panel
mStartButton = new JButton("Start");
this.add(mStartButton);
mStartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StartButtonActionListener(ae);
}
});
mStopButton = new JButton("Stop");
this.add(mStopButton);
mStopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StopButtonActionListener(ae);
}
});
setVisible(true);
}
}
This comes by default on running the code.
This comes after manually resizing the frame.
The combination of BorderLayout , GirdLayout and BoxLayout can do this for you(Actually it's not the only choice).
Here is the code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridLayoutTest {
public void createUI(){
JFrame frame = new JFrame();
JPanel topPanel = new TopPanel();
JPanel buttomPanel = new ButtomPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel,BorderLayout.CENTER);
mainPanel.add(buttomPanel,BorderLayout.SOUTH);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
GridLayoutTest test = new GridLayoutTest();
test.createUI();
}
#SuppressWarnings("serial")
class TopPanel extends JPanel{
public TopPanel(){
setLayout(new GridLayout(2, 3));
ImageIcon icon = new ImageIcon("capture.png");
JLabel label1 = new JLabel(icon);
label1.setVisible(false);
JLabel label2 = new JLabel(icon);
JLabel label3 = new JLabel(icon);
label3.setVisible(false);
JLabel label4 = new JLabel(icon);
JLabel label5 = new JLabel(icon);
JLabel label6 = new JLabel(icon);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);
add(label6);
}
}
#SuppressWarnings("serial")
class ButtomPanel extends JPanel{
public ButtomPanel(){
JButton startButton = new JButton("start");
JButton stopButton = new JButton("stop");
JButton recordButton = new JButton("record");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
}
}
}
BoxLayout is so good too provide white space and help you to center the component.
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
Add Glue before the first component and after the last component will help you too center the component and add strut can help you to provide white space you want. you can refer to https://stackoverflow.com/a/22525005/3378204 for more details.
Here is the effect:
The BoxLayout won't affect your component's size. Hope it can help you.
Try this :
public class Main{
private JFrame f;
private JLabel l1, l2, l3,l4;
private JPanel p1, p2, p3;
private JButton b1, b2, b3;
public Main(){
this.f = new JFrame();
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.f.setLayout(new GridLayout(3,1));
this.p1 = new JPanel();
this.p1.setLayout(null)
this.p1.setSize(yoursize);
this.l1 = new JLabel();
this.l1.setBounds(x,y,xspan,yspan);
this.p1.add(l1);
this.p2 = new JPanel();
this.p2.setLayout(new GridLayout(1,3));
this.l2 = new JLabel();
this.l3 = new JLabel();
this.l4 = new JLabel();
this.p2.add(l2);
this.p2.add(l3);
this.p2.add(l4);
this.p3 = new JPanel();
this.p3.setLayout(new GridLayout(1,3));
this.b1 = new JButton();
this.b2 = new JButton();
this.b3 = new JButton();
this.p3.add(b1);
this.p3.add(b2);
this.p3.add(b3);
this.f.add(p1);
this.f.add(p2);
this.f.add(p3);
this.f.pack();
this.f.setResizeable(false)
}}
Add your video components instead of labels and you can change the color of the components as you wish.
Also if you want more control over the size and position of the components, use null layout and place them individually using setBounds() function as once shown in the program above. It is surely time consuming but makes the layout perfect.
Here's what I actually want to put on a panel:
First logical block:
radio button 1 text field icon button
radio button 2 text field icon button
check box
Second logical block:
Label Spinner
Button
My first decision is to make Vertical Box Layout and put there two Horizontal Box Layouts - for each logical block. But the problem is with these blocks, what layouts to choose to describe this structure? I dislike GridBagLayout - it is very composite and difficult to understand, especially when code isn't yours. For the moment I see that Flow Layout and Grid Layout can be used. But Grid Layout, for example, stretches buttons to the width of a cell and if a button is with icon only it, it looks very strange then.
Hope you can advise me something.
For the first case you can use a simple GridLayout on the JPanel with 3 Rows each having a separate JPanel with FlowLayout having constraints, FLowLayout.LEFT. Have a look at this code example :
import java.awt.*;
import javax.swing.*;
public class ExampleLayout
{
private void displayGUI()
{
JFrame frame = new JFrame("Example Layout");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1, 5, 5));
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JRadioButton rbut1 = new JRadioButton("RadioButton 1", false);
JTextField tfield1 = new JTextField(10);
JButton button1 = new JButton("Button 1");
topPanel.add(rbut1);
topPanel.add(tfield1);
topPanel.add(button1);
JPanel middlePanel = new JPanel();
middlePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JRadioButton rbut2 = new JRadioButton("RadioButton 2", false);
JTextField tfield2 = new JTextField(10);
JButton button2 = new JButton("Button 2");
middlePanel.add(rbut2);
middlePanel.add(tfield2);
middlePanel.add(button2);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JCheckBox cbox = new JCheckBox("CheckBox 1", false);
bottomPanel.add(cbox);
contentPane.add(topPanel);
contentPane.add(middlePanel);
contentPane.add(bottomPanel);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ExampleLayout().displayGUI();
}
});
}
}
OUTPUT :
And for the Second case, simply add first two components to the JPanel having default Layout. And for the third components, simply add components on to a JPanel having GridBagLayout, with no constraints.
EDIT #1 :
Or you can use this approach, for your second block.
import java.awt.*;
import javax.swing.*;
public class ExampleLayout
{
private void displayGUI()
{
JFrame frame = new JFrame("Example Layout");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JPanel basePanel = new JPanel();
basePanel.setLayout(new GridLayout(0, 1, 5, 5));
JPanel topPanel = new JPanel();
//topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel label1 = new JLabel("Label 1", JLabel.CENTER);
JRadioButton rbut1 = new JRadioButton("RadioButton 1", false);
topPanel.add(label1);
topPanel.add(rbut1);
JPanel middlePanel = new JPanel();
middlePanel.setLayout(new GridBagLayout());
JButton button1 = new JButton("Button 1");
middlePanel.add(button1);
basePanel.add(topPanel);
basePanel.add(middlePanel);
contentPane.add(basePanel, BorderLayout.PAGE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ExampleLayout().displayGUI();
}
});
}
}