Multiple JPanels - All buttons same size - java

I have a a main panel that contains multiple panels inside. Each 'children' panel contains one (or more) JButtons. Since I am displaying all the panels at the same time, I would like to make all the buttons the same size (to have consistency).
This code illustrates my problem:
public class Test
{
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(new Dimension(200, 200));
// 1st Panel
JPanel panel1 = new JPanel(new MigLayout());
panel1.add(new JButton("button in panel 1"));
// 2nd Panel
JPanel panel2 = new JPanel(new MigLayout());
panel2.add(new JButton("2nd button"));
JPanel parent = new JPanel(new MigLayout("wrap"));
parent.add(panel1, "pushx, growx");
parent.add(new JSeparator(), "pushx, growx");
parent.add(panel2, "pushx, growx");
f.add(parent);
f.setVisible(true);
}
}
The size of the "button in panel 1" is different from the button in the other panel. Is there an 'easy' way to set their size using the layout? (Hardcoding the size is NOT an option).

I think you didn't read the document carefully, to demonstrate the use I have written a code. You should not copy the same snippet showed in that link. They have specified that the component you have updating must be passed into updateComponentTreeUI() method. You can replace the size by replacing the "large" with "small" or "mini".
import javax.swing.*;
import java.awt.*;
public class Demo {
/**
* #param args
*/
JFrame frame ;
JButton btn;
public Demo()
{
frame = new JFrame("Example");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLayout(new FlowLayout());
btn = new JButton("Example");
btn.putClientProperty("JComponent.sizeVariant", "large");
SwingUtilities.updateComponentTreeUI(btn);
frame.add(btn);
frame.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception e)
{
e.printStackTrace();
}
Demo d = new Demo();
}
}

Related

How do I add other swing components in a specific swing tabbed pane?

I have just started learning Java Swing and I am making a application form sort of project and I want to add more components like buttons,text areas and other in specific tab but I am not able to.
The code is given below:
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame("Hotel Appication Form");
JTextArea ta=new JTextArea(400,400);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(39,20,500,500);
tp.add("form",p1);
tp.add("preferences",p2);
tp.add("FaQ's",p3);
f.add(tp);
f.setSize(600,600);
f.setVisible(true);
//JButton
JButton b = new JButton("Submit");
b.setBounds(50,50,30,20);
f.add(b);
//JLabel
}
public static void main(String[] args) {
new TabbedPaneExample();
}
}
The screenshot of the output is attached here
In this code example simple frame with tabbed panel and simple components in each tab.
Your problem was incorrect adding components to JPanel.
Hope that helps you!
output1 output2
import java.awt.GridLayout;
import javax.swing.*;
public class test {
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Split Pane Example");
// Display the window.
frame.setSize(500, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set grid layout for the frame
frame.getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JButton button = new JButton("Button");
JLabel label = new JLabel("Label");
JTextField textField = new JTextField("TextField");
panel.add(button);
panel.add(label);
panel2.add(textField);
tabbedPane.addTab("Tab1", panel);
tabbedPane.addTab("Tab2", panel2);
frame.getContentPane().add(tabbedPane);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Java Swing 13 GridLayout does not exist?

I can't seem to get a swing GridLayout to work in java 13. The error is that GridLayout cannot be resolved to a type in the following code:
import javax.swing.*;
public class GameFrame extends JFrame {
public static final void NewFrame() {
new GameFrame();
}
public GameFrame() {
this.setSize(1600, 800);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("The Game");
this.setVisible(true);
this.setResizable(false);
JPanel MainPanel = new JPanel();
MainPanel.setLayout(new GridLayout());
}
}
The issue is caused by the class not being imported.
import java.awt.GridLayout;
Since it is not in the swing package it doesn't get imported with the star import.
Also it is better to use explicit imports.
This might be related to the fact that panel is empty. Try running this code and it should work.
public class GridLayoutTest {
private static JButton[] arrayBtn;
public static void main(String[] args) {
// the frame that contains the components
JFrame frame = new JFrame("GridLayoutTest from JCG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the size of the frame
frame.setSize(350, 350);
// set the rows and cols of the grid, as well the distances between them
GridLayout grid = new GridLayout(5, 3, 10, 10);
// what layout we want to use for our frame
frame.setLayout(grid);
// add a text field with a specified text to the frame
JTextArea text = new JTextArea();
text.setText("Result");
text.setEditable(false);
frame.add(text);
// add buttons to the frame
frame.add(new JButton("+"));
frame.add(new JButton("="));
arrayBtn = new JButton[10];
// add JButtons dynamically
for(int i=0; i < arrayBtn.length; i++) {
arrayBtn[i] = new JButton(Integer.toString(i));
frame.add(arrayBtn[i]);
}
frame.setVisible(true);
}
}

Splitting Frame in Three

I have coded a GUI that looks like shown below. It is coded as such:
There is a main Frame managed with BorderLayout.
In the west part of it is a panel with a grid layout of 3 x 2 buttons.
In the center part is a panel.
I'd like to add a third panel as shown. How can I do this?
In the center part is a Panel
That panel might also have a BorderLayout, put the two combo boxes in a panel in the PAGE_START of it, and the 3rd panel in the CENTER.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
public class ThreePanelLayout {
private JComponent ui = null;
private String[] buttonNames = {"Time", "Price", "Route", "Sort", "Admin", "End"};
private String[][] comboFirstNames = {{"Departing Stop"}, {"Final Stop"}};
ThreePanelLayout() {
initUI();
}
public void initUI() {
if (ui!=null) return;
// I always use this 'ui' panel as a content pane that contains
// everything else..
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
// now to create the 3 panels of the '3 panel layout'.
JPanel panel1 = new JPanel(new BorderLayout());
panel1.setBackground(Color.RED);
panel1.setBorder(new TitledBorder("Choose Option"));
JPanel panel2 = new JPanel(new BorderLayout());
panel2.setBackground(Color.GREEN);
panel2.setBorder(new TitledBorder("Choose Two Stops"));
JPanel panel3 = new JPanel(new BorderLayout());
panel3.setBackground(Color.ORANGE);
panel3.setBorder(new TitledBorder("Third Panel Here"));
// add the buttons to 1st panel
panel1.add(addButtonsToPanel(buttonNames), BorderLayout.LINE_START);
// add the combos to the top of 2nd panel
panel2.add(addCombosToPanel(comboFirstNames), BorderLayout.PAGE_START);
// give the 3rd panel some size
panel3.add(new JLabel(new ImageIcon(new BufferedImage(400,200,BufferedImage.TYPE_INT_ARGB))));
// now assemble them all together
panel2.add(panel3, BorderLayout.CENTER);
panel1.add(panel2, BorderLayout.CENTER);
ui.add(panel1, BorderLayout.CENTER);
}
private JPanel addButtonsToPanel(String[] ids) {
JPanel p = new JPanel(new GridLayout(0, 2));
for (String id : ids) {
p.add(new JButton(id));
}
return p;
}
private JPanel addCombosToPanel(String[][] ids) {
JPanel p = new JPanel(new FlowLayout());
for (String[] id : ids) {
p.add(new JComboBox<String>(id));
}
return p;
}
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) {
}
ThreePanelLayout o = new ThreePanelLayout();
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);
}
}

JButtons in JPanel in another JPanel

Is it possible to add a JPanel with JButtons to a Split JPanel? Right now, I have the JPanel with JButtons added to a JFrame, but I want it on a JPanel with other JPanels. When I attempt to do this, I get a completely blank JPanel with dividers.
______________________________________________________________________________
public class Panel extends JPanel implements Runnable, ActionListener {
public Panel(){
JFrame frame = new JFrame();
ctsMenu = new JPanel(new GridLayout(2,2));
ctsMenu.setPreferredSize(new Dimension(500,500));
for (int iRows = 0; iRows < 2 ; iRows++){
for (int iColumns = 0; iColumns < 2; iColumns++){
sGrid[iRows][iColumns] = new JButton ("("+iRows+","+iColumns+")");
ctsMenu.add(sGrid[iRows][iColumns]);
sGrid[iRows][iColumns].addActionListener(this);
panel.add(ctsMenu);
}
}
sGrid[0][0].setText("A");
sGrid[0][1].setText("B");
sGrid[1][0].setText("C");
sGrid[1][1].setText("D");
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}}
____________________________________________________________________
public MainFrame()
{
setTitle( "Split Pane Application" );
setBackground( Color.GREEN );
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
createPanel1();
createPanel2();
createPanel3();
createPanel4();
splitPaneV = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
topPanel.add( splitPaneV, BorderLayout.CENTER );
splitPaneV.setDividerLocation(300);
splitPaneV.setLeftComponent( gamePanel);
// gamePanel.addKeyListener(new KeyListener());
gamePanel.setFocusable(true);
gamePanel.requestFocusInWindow();
splitPaneV.setRightComponent( panel3 );
}
}
public void createPanel1(){
// deleted to take up less space
}
public void createPanel2(){
// deleted to take up less space
}
public void createPanel3(){
panel3 = new Panel();
}
public void createPanel4(){
//deleted to take up less space
}
}
You ask:
Is it possible to add a JPanel with JButtons to a Split JPanel?
Yes, it is most definitely possible to do this. It's something similar to what we do all the time:
import javax.swing.*;
public class SplitPaneEg {
private static void createAndShowGui() {
JPanel panel1 = new JPanel();
panel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
panel1.add(new JButton("Button 1"));
panel1.add(new JButton("Button 2"));
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
panel2.add(new JButton("Button 1"));
panel2.add(new JButton("Button 2"));
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1,
panel2);
JFrame frame = new JFrame("Split Pane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(splitPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You state:
Right now, I have the JPanel with JButtons added to a JFrame, but I want it on a JPanel with other JPanels. When I attempt to do this, I get a completely blank JPanel with dividers.
Then you have an error in your code, but unfortunately based on code you've posted I doubt that any of us can do more than just guess. If you need more specific help, then you will want to post a small runnable example that demonstrates your problem, an sscce.

Jframe. adding 2 Jpanel components in one frame. Doesnt work

Problem : i'm trying to add a 2nd Jpanel in my frame but when i add this latter, it overwrites the previous one. The purpose is to have 2 components (Jpanels) in the same frame but it seem to accept only one but not both. The order of appearence should be in one column and two rows:
1: Enter name:
2: TextField
import javax.swing.*;
import java.awt.*;
public class Money2 extends JFrame {
public Money2() {
// setLayout(new GridLayout(2,2));
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.CENTER));
p1.add(new JLabel("Enter name:"));
// -------------------------------------------------------------------------
// p2.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel p2 = new JPanel(new FlowLayout());
p2.add(new JTextField(8));
add(p1); // add to Jframe
add(p2);
}
/** Main method */
public static void main(String[] args) {
Money2 frame = new Money2();
frame.setTitle("Money Converter App");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 400);
frame.setVisible(true);
}
}
Both panels cannot occupy the same location in a BorderLayout. You could place panel p1 at a different location:
add(p1, BorderLayout.PAGE_START);

Categories