Increasing distance from top of JPanel - java

I'm trying to increase the distance of my JButtons from the top of my Panel to make it more visually appealing, i've tried using an invisible button but have had no luck.
public class SimpleBorder {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Border etched = (Border) BorderFactory.createEtchedBorder();
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
JTextArea text = new JTextArea(10, 40);
JScrollPane scrol = new JScrollPane(text);
JScrollPane scrol2 = new JScrollPane(list);
JPanel panel= new JPanel();
panel.add(scrol2,BorderLayout.WEST);
panel.add(scrol, BorderLayout.EAST);
panel.setBorder(etched);
frame.add(panel);
frame.setVisible(true);
}
}
Any ideas ?

The key basically lies, in the fact, that the component doesn't knows it's actual size, till frame.pack() won't be called. Hence after this I am performing this calculation, to determine how much empty space to put for Border and again calling frame.pack() to repack() everything after putting the Border.
Please do have a look at this example, and see if this suite your needs :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private GridBagConstraints gbc;
public MainMenu() {
gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
}
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout());
menuPanel = new JPanel(new GridBagLayout());
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
addComp(menuPanel, playButton, 0, 0, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, instructionButton, 0, 1, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, scoreboardButton, 0, 2, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, exitButton, 0, 3, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() - (contentPane.getHeight() / 4),
20, 5, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp,
int gridx, int gridy,
int gridwidth, int gridheight,
double weightx, double weighty,
int fill) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.fill = fill;
panel.add(comp, gbc);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
Here is the output :
EDIT 1 :
Moreover, if you will use GridLayout instead of using GridBagLayout for the MainMenu, then I guess the results will be more promising. Please have a look at this example for that change :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new GridBagLayout());
menuPanel = new JPanel(new GridLayout(0, 1, 5, 5));
menuPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
menuPanel.add(playButton);
menuPanel.add(instructionButton);
menuPanel.add(scoreboardButton);
menuPanel.add(exitButton);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() -
(contentPane.getHeight() -
(3 * menuPanel.getHeight())),
20, 0, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
EDIT 2 :
Another variant is looking much better, though, this time, the base JPanel is using GridLayout and the MenuPanel is using GridBagLayout. Please have a look at this example :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private GridBagConstraints gbc;
public MainMenu() {
gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.anchor = GridBagConstraints.CENTER;
}
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new GridLayout(1, 1, 5, 2));
menuPanel = new JPanel(new GridBagLayout());
menuPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
addComp(menuPanel, playButton, 0, 0, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, instructionButton, 0, 1, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, scoreboardButton, 0, 2, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, exitButton, 0, 3, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() -
(contentPane.getHeight() -
(2 * menuPanel.getHeight()) + 100),
20, 2, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp,
int gridx, int gridy,
int gridwidth, int gridheight,
double weightx, double weighty,
int fill) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.fill = fill;
panel.add(comp, gbc);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

Related

How to position components in a JFrame?

jframe = new JFrame("Admin");
jpanel = new JPanel();
jpanel.setLayout(new FlowLayout());
jframe.add(jpanel);
userLabel = new JLabel("Username:");
jpanel.add(userLabel);
userLabel.setBounds(100, 100, 30, 30);
userTxtfield = new JTextField(15);
jpanel.add(userTxtfield);
passwordTxtfield = new JTextField(15);
jpanel.add(userTxtfield);
jpanel.add(passwordTxtfield);
passwordLabel = new JLabel("Password:");
jpanel.add(passwordLabel);
userLabel.setBounds(100, 100, 30, 30);
loginButton= new JButton("Login");
jpanel.add(loginButton);
jframe.pack();
jframe.setLocationRelativeTo(null);
jframe.setSize(350,350);
jframe.setVisible(true);
I am trying to make a neat login area for my program but I can't seem to get the two labels and text fields to line up with the button underneath. Is there a better way of doing this positioning of the components within this JFrame?
Use a JOptionPane to display a log-in dialog. One way to layout the components is to use a GridBagLayout.
The code that produces that is:
public void login() {
JPanel loginPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(
0, 0, 1, 1, 0, 0,
GridBagConstraints.BASELINE_TRAILING,
GridBagConstraints.NONE,
new Insets(5, 5, 5, 5), 4, 6);
loginPanel.add(new JLabel("ID"), gbc);
gbc.gridy = 1;
loginPanel.add(new JLabel("Password"), gbc);
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.gridx = 1;
gbc.gridy = 0;
loginPanel.add(new JTextField("enter ID", 10), gbc);
gbc.gridy = 1;
loginPanel.add(new JPasswordField(6), gbc);
int result = JOptionPane.showConfirmDialog(
ui, loginPanel, "LogIn", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
// here a real app would check the results of the ID/password
cardLayout.show(ui, "loggedin");
}
}
Here is the complete example (an MCVE, as mentioned above).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BlockTheFrame {
private JComponent ui = null;
private CardLayout cardLayout;
BlockTheFrame() {
initUI();
}
public final void initUI() {
if (ui != null) {
return;
}
cardLayout = new CardLayout();
ui = new JPanel(cardLayout);
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JLabel login = new JLabel("Log in");
login.setFont(login.getFont().deriveFont(200f));
ui.add(login, "login");
ui.add(new JLabel("logged in"), "loggedin");
}
public void login() {
JPanel loginPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(
0, 0, 1, 1, 0, 0,
GridBagConstraints.BASELINE_TRAILING,
GridBagConstraints.NONE,
new Insets(5, 5, 5, 5), 4, 6);
loginPanel.add(new JLabel("ID"), gbc);
gbc.gridy = 1;
loginPanel.add(new JLabel("Password"), gbc);
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.gridx = 1;
gbc.gridy = 0;
loginPanel.add(new JTextField("enter ID", 10), gbc);
gbc.gridy = 1;
loginPanel.add(new JPasswordField(6), gbc);
int result = JOptionPane.showConfirmDialog(
ui, loginPanel, "LogIn", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
// here a real app would check the results of the ID/password
cardLayout.show(ui, "loggedin");
}
}
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) {
}
BlockTheFrame o = new BlockTheFrame();
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);
o.login();
}
};
SwingUtilities.invokeLater(r);
}
}

GridBag Layout acting as a flow layout , within a card layout. What am I doing wrong?

This code uses the card layout, as I want to change the window display rather than have multiple windows (or frames). Therefore I want multiple panels, which seems to work.
However within the panels I want to use the gridbag layout for positioning components. But it's not working! It acts as a flow layout. Can anyone help me get over this hurdle? Please.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class another
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
panel2 = new MyPanel2();
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new another().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField How;
private JLabel jcomp2;
private JLabel jcomp3;
private JButton jcomp4;
private JPanel contentPane;
private JPanel myPanel1;
public MyPanel(JPanel panel)
{
contentPane = panel;
//construct components
How = new JTextField (1);
jcomp2 = new JLabel ("Label2");
jcomp3 = new JLabel ("Label3");
jcomp4 = new JButton ("openNewWindow");
myPanel1 = new JPanel();
//adjust size and set layout
setPreferredSize (new Dimension (600, 600));
setLayout (new GridBagLayout());
//set component bounds (only needed by Absolute Positioning)
/*
How.setBounds (245, 50, 60, 25);
jcomp2.setBounds (35, 30, 185, 50);
jcomp3.setBounds (250, 30, 60, 20);
jcomp4.setLocation(0, 0);
jcomp4.setSize(315, 25);
*/
insert(jcomp2, 0, 0, 1, 1);
insert(jcomp3, 0, 1, 1, 1);
insert(jcomp4, 1, 0, 1, 1);
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
//add components
//add (How);
add (jcomp2);
add (jcomp3);
add (jcomp4);
}
public void insert(Component c, int gridX, int gridY, int gridW, int gridH)
{
GridBagConstraints constraint = new GridBagConstraints();
constraint.gridx = gridX;
constraint.gridy = gridY;
constraint.gridwidth = gridW;
constraint.gridheight = gridH;
constraint.anchor = GridBagConstraints.LINE_START;
myPanel1.add(c, constraint);
}
}
class MyPanel2 extends JPanel {
private JButton jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JTextField jcomp4;
public MyPanel2() {
//construct components
jcomp1 = new JButton ("test1");
jcomp2 = new JButton ("test2");
jcomp3 = new JButton ("test3");
jcomp4 = new JTextField (5);
//adjust size and set layout
setPreferredSize (new Dimension (395, 156));
setLayout (null);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (20, 45, 100, 25);
jcomp2.setBounds (135, 60, 100, 25);
jcomp3.setBounds (260, 35, 100, 25);
jcomp4.setBounds (105, 115, 100, 25);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
add (jcomp4);
}
}
You look to be unnecessarily over-complicating things. You create a JPanel called contentPane and give it a CardLayout, all well and good, but then for some reason you pass that contentPane JPanel into the MyPanel constructor,
JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
panel2 = new MyPanel2();
and then within the constructor you assign components to this same contentPane JPanel -- but why? You assign GridBagLayout to the MyPanel this instance, but then add components to the myPanel1 variable within it in a GridBag way when this JPanel has the JPanel default FlowLayout:
class MyPanel extends JPanel {
// ....
private JPanel contentPane;
private JPanel myPanel1;
public MyPanel(JPanel panel) {
contentPane = panel;
// ....
myPanel1 = new JPanel();
setLayout (new GridBagLayout()); // you set *** this *** to GridBagLayout
insert(jcomp2, 0, 0, 1, 1);
insert(jcomp3, 0, 1, 1, 1);
insert(jcomp4, 1, 0, 1, 1);
add (jcomp2); // and then you add components to this without GridBagConstraints ?
add (jcomp3);
add (jcomp4);
}
public void insert(Component c, int gridX, int gridY, int gridW, int gridH) {
// ....
// but then add components in a GridBagLayout way into the myPanel1 JPanel???
myPanel1.add(c, constraint);
}
}
Better to set myPanel to use GridBagLayout:
// adjust size and set layout
setPreferredSize(new Dimension(600, 600));
// setLayout(new GridBagLayout());
myPanel1.setLayout(new GridBagLayout());
Rather than this
Again it seems that you're over-complicating what should be a simple endeavor.
For example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class SimpleCardExample extends JPanel {
private static final int EB_GAP = 8;
private CardLayout cardLayout = new CardLayout();
public SimpleCardExample() {
setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
setLayout(cardLayout);
add(new GridBagPanel(this), GridBagPanel.class.getSimpleName());
add(new NextPanel(this), NextPanel.class.getSimpleName());
}
public void nextCard() {
cardLayout.next(this);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SimpleCardExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SimpleCardExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class GridBagPanel extends JPanel {
private static final int GAP = 6;
private static final Insets GBC_INSETS = new Insets(GAP, GAP, GAP, GAP);
public GridBagPanel(SimpleCardExample scExample) {
setLayout(new GridBagLayout());
add(new JLabel("Title Goes Here", SwingConstants.CENTER), createGbc(0, 0, 2, 1));
add(new JLabel("Name:"), createGbc(0, 1, 1, 1));
add(new JTextField(15), createGbc(1, 1, 1, 1));
add(new JLabel("Phone:"), createGbc(0, 2, 1, 1));
add(new JTextField(15), createGbc(1, 2, 1, 1));
add(new JLabel("Address:"), createGbc(0, 3, 1, 1));
add(new JTextField(15), createGbc(1, 3, 1, 1));
add(new JButton(new NextAction("Next", scExample)), createGbc(0, 4, 2, 1));
}
private GridBagConstraints createGbc(int x, int y, int w, int h) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
gbc.insets = GBC_INSETS;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
return gbc;
}
}
class NextPanel extends JPanel {
public NextPanel(SimpleCardExample scExample) {
add(new JButton(new NextAction("Next", scExample)));
}
}
class NextAction extends AbstractAction {
private SimpleCardExample scExample;
public NextAction(String name, SimpleCardExample scExample) {
super(name);
this.scExample = scExample;
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
scExample.nextCard();
}
}

How to align the elements to the top in a GridBagLayout?

I want to put a text element in a GridBagLayout after clicking on a button.
But the elements are vertically centered. So how can I force the grid bag layout to position the elements to the top?
Here is an example code:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class RefreshPanel {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JTextPane [] textPane;// = new JTextPane[1];
private JScrollPane scrollbar;
private ArrayList arrayList = new ArrayList();
private JButton newItem = new JButton("new");
private GridBagLayout gbl = new GridBagLayout();
private JMenu menuStart= new JMenu("Start");
private JMenu menuEdit= new JMenu("Edit");
private JMenu menuWindow= new JMenu("Window");
private JMenu menuHelp= new JMenu("help");
private JMenuBar menuBar = new JMenuBar();
RefreshPanel() {
menuBar.add(menuStart);
menuBar.add(menuEdit);
menuBar.add(menuWindow);
menuBar.add(menuHelp);
scrollbar = new JScrollPane(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(gbl);
addButtonListener();
createFrame();
} //constructor
public void addButtonListener() {
newItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
arrayList.add("data");
textPane = generateTextPane(arrayList.size(), arrayList);
System.out.println("Länge: "+textPane.length);
for(int i=0;i<textPane.length;i++) {
System.out.println(textPane[i].getText());
addComponent(panel, gbl, textPane[i], 0, i, 1, 1, 1, 0);
panel.revalidate();
}
frame.revalidate();
}
});
}
private JTextPane[] generateTextPane(int arraySize, ArrayList arrayList) {
JTextPane [] textPane = new JTextPane[arraySize];
for(int i=0;i<textPane.length;i++) {
textPane[i]=new JTextPane();
textPane[i].setText((String) arrayList.get(i));
System.out.println("length >> "+textPane.length);
}
return textPane;
}
public void addComponent(Container cont,
GridBagLayout gbl,
Component c,
int x, int y,
int width, int height,
double weightx, double weighty) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = width; gbc.gridheight = height;
gbc.weightx = weightx; gbc.weighty = weighty;
gbc.anchor = GridBagConstraints.SOUTH;
gbl.setConstraints( c, gbc );
cont.add( c );
}
public void createFrame() {
frame.add(menuBar, BorderLayout.NORTH);
frame.add(scrollbar, BorderLayout.CENTER);
frame.add(newItem, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300,300));
frame.setVisible(true);
}
public static void main(String [] args) {
new RefreshPanel();
}
}
I know that the grids are dynamically changing their size when I put a new element.
Any ideas how can I solve my problem?
I have changed your GridBagLayout properties. Check this:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class RefreshPanel {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JTextPane [] textPane;// = new JTextPane[1];
private JScrollPane scrollbar;
private ArrayList arrayList = new ArrayList();
private JButton newItem = new JButton("new");
private GridBagLayout gbl = new GridBagLayout();
private JMenu menuStart= new JMenu("Start");
private JMenu menuEdit= new JMenu("Edit");
private JMenu menuWindow= new JMenu("Window");
private JMenu menuHelp= new JMenu("help");
private JMenuBar menuBar = new JMenuBar();
RefreshPanel() {
menuBar.add(menuStart);
menuBar.add(menuEdit);
menuBar.add(menuWindow);
menuBar.add(menuHelp);
scrollbar = new JScrollPane(panel);
panel.setBackground(Color.WHITE);
gbl.columnWidths = new int[]{0, 0, 0, 0};
gbl.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl);
addButtonListener();
createFrame();
} //constructor
public void addButtonListener() {
newItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
arrayList.add("data");
textPane = generateTextPane(arrayList.size(), arrayList);
System.out.println("Länge: "+textPane.length);
for(int i=0;i<textPane.length;i++) {
System.out.println(textPane[i].getText());
panel.add(textPane[i],new GridBagConstraints( 0, i, 1, 1,
1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
panel.revalidate();
}
frame.revalidate();
}
});
}
private JTextPane[] generateTextPane(int arraySize, ArrayList arrayList) {
JTextPane [] textPane = new JTextPane[arraySize];
for(int i=0;i<textPane.length;i++) {
textPane[i]=new JTextPane();
textPane[i].setText((String) arrayList.get(i));
System.out.println("length >> "+textPane.length);
}
return textPane;
}
public void addComponent(Container cont,
GridBagLayout gbl,
Component c,
int x, int y,
int width, int height,
double weightx, double weighty) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = width; gbc.gridheight = height;
gbc.weightx = weightx; gbc.weighty = weighty;
gbc.anchor = GridBagConstraints.SOUTH;
gbl.setConstraints( c, gbc );
cont.add( c );
}
public void createFrame() {
frame.add(menuBar, BorderLayout.NORTH);
frame.add(scrollbar, BorderLayout.CENTER);
frame.add(newItem, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300,300));
frame.setVisible(true);
}
public static void main(String [] args) {
new RefreshPanel();
}
}

GridBagLayout 2 JPanels - One less width than other

I would like to find out how exactly would I go about to having two JPanels on one JPanel, all using GridBagLayout.
Basically you have your Top Most JPanel and then with 2 JPanels on their as below requirement:
--------------------------------------
| | |
| | |
| | |
| JPanel 1 | JPanel |
| | 2 |
| | |
| | |
--------------------------------------
Basically I would need JPanel 1 to be bigger than JPanel 2. But also JPanel 2 must NOT resize, JPanel 1 should only resize if the main panel gets resized.
Any idea's?
Have a look at this code example and see if this is what you wanted :
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class GridBagExample {
private JPanel leftPanel;
private JPanel rightPanel;
private GridBagConstraints gbc;
private Random random;
public GridBagExample() {
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.insets = new Insets(5, 5, 5, 5);
random = new Random();
}
private void displayGUI() {
JFrame frame = new JFrame("Swing Worker Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = getPanel();
contentPane.setLayout(new GridBagLayout());
leftPanel = getPanel();
rightPanel = getPanel();
addComp(contentPane, leftPanel, 0, 0, 1, 1,
GridBagConstraints.BOTH, 0.7, 1.0);
addComp(contentPane, rightPanel, 1, 0, 1, 1,
GridBagConstraints.BOTH, 0.3, 1.0);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp, int gridx,
int gridy, int gridwidth, int gridheight,
int fill, double weightx, double weighty) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.fill = fill;
gbc.weightx = weightx;
gbc.weighty = weighty;
panel.add(comp, gbc);
}
private JPanel getPanel() {
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(new Color(random.nextInt(256),
random.nextInt(256), random.nextInt(256)));
return panel;
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new GridBagExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
Though if you want your right JPanel not to change size, you can pass GridBagConstraints.NONE to the function instead of GridBagConstraints.BOTH as done by me. Since without the actual contents known for this JPanel which will become its part, its hard to present its true size.
OUTPUT :
EDIT :
Updating my code, to better explain, as to what I am saying, though I used user2699405's (OP) ideas too from the comments.
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class GridBagExample {
private JPanel leftPanel;
private JPanel rightPanel;
private GridBagConstraints gbc;
private Random random;
public GridBagExample() {
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.insets = new Insets(5, 5, 5, 5);
random = new Random();
}
private void displayGUI() {
JFrame frame = new JFrame("Swing Worker Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = getPanel();
contentPane.setLayout(new GridBagLayout());
leftPanel = getPanel();
rightPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return (new Dimension(100, 100));
}
};
addComp(contentPane, leftPanel, 0, 0, 1, 1,
GridBagConstraints.BOTH, 1.0, 1.0);
addComp(contentPane, rightPanel, 1, 0, 1, 1,
GridBagConstraints.NONE, 0.0, 1.0);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp, int gridx,
int gridy, int gridwidth, int gridheight,
int fill, double weightx, double weighty) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.fill = fill;
gbc.weightx = weightx;
gbc.weighty = weighty;
panel.add(comp, gbc);
}
private JPanel getPanel() {
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(new Color(random.nextInt(256),
random.nextInt(256), random.nextInt(256)));
return panel;
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new GridBagExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

Component size in SpringLayout

I use SpringLayout on my form, But as you see, its look isn't good (large and bad size)!
public class t8 extends JFrame {
JButton okButton, cancellButton;
JTextField idTF, nameTf;
JLabel idlbl, namelbl;
public t8() {
add(createPanel(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setLocation(400, 100);
setVisible(true);
}
public static void main(String[] args) {
new t8();
}
public JPanel createPanel() {
JPanel panel = new JPanel();
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
panel.add(idlbl);
panel.add(idTF);
panel.add(namelbl);
panel.add(nameTf);
panel.add(okButton);
panel.add(cancellButton);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 3, 2, 20, 50, 50, 100);
return panel;
}
}
I change makeCompactGrid numbers, But was not success!
(The width of JTextFields are large, and my button's size are different)
If you don't care about the layout manager, but only care about the layout, then you should use a GridLayout, or if you don't want all component to be the same size, a GridBagLayout. Here's how with a grid layout (only the modified method is shown):
public JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
panel.add(idlbl);
panel.add(idTF);
panel.add(namelbl);
panel.add(nameTf);
panel.add(okButton);
panel.add(cancellButton);
return panel;
}
And with a GridBagLayout:
public JPanel createPanel() {
JPanel panel = new JPanel();
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
panel.setLayout(gb);
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
add(panel, idlbl, 0, 0, 1, 1, gb, gbc, false);
add(panel, idTF, 0, 1, 1, 1, gb, gbc, true);
add(panel, namelbl, 1, 0, 1, 1, gb, gbc, false);
add(panel, nameTf, 1, 1, 1, 1, gb, gbc, true);
add(panel, okButton, 2, 0, 1, 1, gb, gbc, false);
add(panel, cancellButton, 2, 1, 1, 1, gb, gbc, true);
return panel;
}
private void add(Container outer, Component c, int x, int y, int w, int h, GridBagLayout gb, GridBagConstraints gbc, boolean wide) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
if (wide) {
gbc.weightx = 100;
} else {
gbc.weightx = 0;
}
gb.setConstraints(c, gbc);
outer.add(c);
}
I believe that the extra GridBagLayout complexity just might be worth it.
I would suggest you to use Netbeans drag and drop tool which will allow you to set the components physically and will also give you the preview.
If you want to do it with code just use the free layout and set the location and size of every component manually By setSize() and setLocation() methods, although this will require more lines of code but will ensure you that all the components are in their correct position.

Categories