Why is GridBagConstraints gathering the objects in the centre of the JPanel? - java

In the following code I am creating a JFrame with a JMenuBar and JPanel, the later having three JTextFields and three JLabels. However, all the components of the JPanel are gathering in the center. I've set the layout before adding components so I don't think its this issue (which I've had before). If anyone has anybody ideas how to sort this out I would be much obliged.
public class InterfaceWindow {
private static final Logger LOGGER = Logger.getLogger(DownloadWindow.class.getName());
private JButton helpJButton;
private JButton copyToClipBoardJButton;
private JButton enterJButton;
private JButton selectFileJButton;
private JLabel pathJLabel;
private JLabel jobNameJLabel;
private JLabel emailJLabel;
private JTextField pathJTextField;
private JTextField jobNameJTextField;
private JTextField emailJTextField;
private JTextArea transcriptionJTextArea;
private JMenu accountJMenu;
private JMenu jobsJMenu;
private JMenu helpJMenu;
private JMenuBar toolBarJMenuBar = new JMenuBar();
private JMenuItem uploadYouTubeJMenuItem;
private JMenuItem uploadFileJMenuItem;
private JMenuItem downloadJMenuItem;
private JMenuItem helpJMenuItem;
private GridBagConstraints panelGbc = new GridBagConstraints();
private GridBagConstraints frameGbc = new GridBagConstraints();
private JPanel interfaceJPanel = new JPanel();
private String emptyField = "default";
private String filePath = "default";
public JButton getHelpJButton() {
return helpJButton;
}
public JButton getCopyToClipBoardJButton() {
return copyToClipBoardJButton;
}
public JButton getEnterJButton() {
return enterJButton;
}
public JButton getSelectFileJButton() {
return selectFileJButton;
}
public JFrame setInterfaceWindow() {
JFrame interfaceJFrame = new JFrame();
frameGbc.fill = GridBagConstraints.HORIZONTAL;
interfaceJPanel = setInterfaceJPanel();
interfaceJFrame.getContentPane().setLayout(new GridBagLayout());
interfaceJFrame.setLayout(new GridBagLayout());
interfaceJFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
interfaceJFrame.setTitle("Audio Transcribe");
interfaceJFrame.setSize(800, 800);
interfaceJFrame.setLocationRelativeTo(null);
interfaceJFrame.setJMenuBar(setToolBar(toolBarJMenuBar));
interfaceJFrame.add(interfaceJPanel, frameGbc);
interfaceJFrame.setVisible(true);
return interfaceJFrame;
}
private JPanel setInterfaceJPanel() {
panelGbc.fill = GridBagConstraints.HORIZONTAL;
panelGbc.insets.bottom = 1;
panelGbc.insets.top = 2;
panelGbc.insets.right = 1;
panelGbc.insets.left = 1;
panelGbc.weightx = 1;
panelGbc.weighty = 1;
interfaceJPanel.setLayout(new GridBagLayout());
interfaceJPanel.setSize(800, 700);
setJobName(interfaceJPanel);
setPath(interfaceJPanel);
setEmail(interfaceJPanel);
setButtons(interfaceJPanel);
setTextArea(interfaceJPanel);
setAction();
return interfaceJPanel;
}
public JMenuBar setToolBar(JMenuBar toolBarJMenuBar) {
accountJMenu = new JMenu("Accounts");
jobsJMenu = new JMenu("Jobs");
helpJMenu = new JMenu("Help");
toolBarJMenuBar.add(accountJMenu);
toolBarJMenuBar.add(jobsJMenu);
toolBarJMenuBar.add(helpJMenu);
downloadJMenuItem = new JMenuItem("Download");
uploadFileJMenuItem = new JMenuItem("Upload file");
uploadYouTubeJMenuItem = new JMenuItem("Upload from YouTube");
helpJMenuItem = new JMenuItem("Help");
jobsJMenu.add(downloadJMenuItem);
jobsJMenu.addSeparator();
jobsJMenu.add(uploadFileJMenuItem);
jobsJMenu.addSeparator();
jobsJMenu.add(uploadYouTubeJMenuItem);
helpJMenu.add(helpJMenuItem);
return toolBarJMenuBar;
}
private void setEmail(JPanel interfaceJPanel) {
JLabel emailLabel = new JLabel("Email:");
panelGbc.gridx = 1;
panelGbc.gridy = 3;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(emailLabel, panelGbc);
emailJTextField = new JTextField();
emailJTextField.setText(emptyField);
panelGbc.gridx = 2;
panelGbc.gridy = 3;
panelGbc.gridwidth = 3;
panelGbc.gridheight = 1;
interfaceJPanel.add(emailJTextField, panelGbc);
}
private void setPath(JPanel interfaceJPanel) {
JLabel filePathLabel = new JLabel("File path:");
panelGbc.gridx = 1;
panelGbc.gridy = 0;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(filePathLabel, panelGbc);
pathJTextField = new JTextField();
pathJTextField.setText(filePath);
panelGbc.gridx = 2;
panelGbc.gridy = 0;
panelGbc.gridwidth = 2;
panelGbc.gridheight = 1;
interfaceJPanel.add(pathJTextField, panelGbc);
}
private void setJobName(JPanel interfaceJPanel) {
JLabel jobNameLabel = new JLabel("Job name:");
panelGbc.gridx = 1;
panelGbc.gridy = 2;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(jobNameLabel, panelGbc);
jobNameJTextField = new JTextField();
jobNameJTextField.setText(emptyField);
panelGbc.gridx = 2;
panelGbc.gridy = 2;
panelGbc.gridwidth = 2;
panelGbc.gridheight = 1;
interfaceJPanel.add(jobNameJTextField, panelGbc);
}
private void setAction() {
}
private void setTextArea(JPanel interfaceJPanel) {
}
private void setButtons(JPanel interfaceJPanel) {
}
}

It's because you're nesting two JPanels with GridBagLayout, and when adding the inner JPanel to the outer panel your frameGbc constraint does not have weightx or weighty set, centering the inner JPanel. The inner JPanel will size to its preferredSize, meaning, size as small as allowed, and will be centered.
Best not to do this. Instead let the JFrame continue to use BorderLayout, and add the GridBagLayout using JPanel BorderLayout.CENTER, or don't nest JPanels unnecessarily and just give the contentPane a GridBagLayout.

Related

Adding ImageIcon to JPanel

I'm working with a chat app and trying to integrate profile pictures into the code. For now, I'm just trying to get a simple static "smiley.png" to display in my gui. doing this:
final ImageIcon profilePicture = new ImageIcon(getClass().getResource("smiley.png"));
final JLabel profileLabel = new JLabel(profilePicture);
currentPanel.add(profileLabel);
results in a ERROR: Exception in ChatSimpleGui.run. Check log for details. (Log is nonexistent as I run this from terminal)
Please help?
Here is full code for this particular class:
package codeu.chat.client.simplegui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import codeu.chat.client.ClientContext;
import codeu.chat.common.User;
// NOTE: JPanel is serializable, but there is no need to serialize UserPanel
// without the #SuppressWarnings, the compiler will complain of no override for serialVersionUID
#SuppressWarnings("serial")
public final class UserPanel extends JPanel {
private final ClientContext clientContext;
public UserPanel(ClientContext clientContext) {
super(new GridBagLayout());
this.clientContext = clientContext;
initialize();
}
private void initialize() {
// This panel contains from top to bottom; a title bar, a list of users,
// information about the current (selected) user, and a button bar.
// Title bar - also includes name of currently signed-in user.
final JPanel titlePanel = new JPanel(new GridBagLayout());
final GridBagConstraints titlePanelC = new GridBagConstraints();
final JLabel titleLabel = new JLabel("Users", JLabel.LEFT);
final GridBagConstraints titleLabelC = new GridBagConstraints();
titleLabelC.gridx = 0;
titleLabelC.gridy = 0;
titleLabelC.anchor = GridBagConstraints.PAGE_START;
final GridBagConstraints titleGapC = new GridBagConstraints();
titleGapC.gridx = 1;
titleGapC.gridy = 0;
titleGapC.fill = GridBagConstraints.HORIZONTAL;
titleGapC.weightx = 0.9;
final JLabel userSignedInLabel = new JLabel("not signed in", JLabel.RIGHT);
final GridBagConstraints titleUserC = new GridBagConstraints();
titleUserC.gridx = 2;
titleUserC.gridy = 0;
titleUserC.anchor = GridBagConstraints.LINE_END;
titlePanel.add(titleLabel, titleLabelC);
titlePanel.add(Box.createHorizontalGlue(), titleGapC);
titlePanel.add(userSignedInLabel, titleUserC);
titlePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
// User List panel.
final JPanel listShowPanel = new JPanel();
final GridBagConstraints listPanelC = new GridBagConstraints();
final DefaultListModel<String> listModel = new DefaultListModel<>();
final JList<String> userList = new JList<>(listModel);
userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
userList.setVisibleRowCount(10);
userList.setSelectedIndex(-1);
final JScrollPane userListScrollPane = new JScrollPane(userList);
listShowPanel.add(userListScrollPane);
userListScrollPane.setPreferredSize(new Dimension(150, 150));
//PASSWORD FIELD
final JTextField passwordField = new JTextField();
listShowPanel.add(passwordField);
passwordField.setPreferredSize(new Dimension(100, 20));
//STATUS FIELD to be implemented shortly
//final JTextField statusField = new JTextField();
//listShowPanel.add(statusField);
//statusField.setPreferredSize(new Dimension(100, 20));
// Current User panel
final JPanel currentPanel = new JPanel();
final GridBagConstraints currentPanelC = new GridBagConstraints();
final JTextArea userInfoPanel = new JTextArea();
final JScrollPane userInfoScrollPane = new JScrollPane(userInfoPanel);
currentPanel.add(userInfoScrollPane);
userInfoScrollPane.setPreferredSize(new Dimension(245, 85));
final ImageIcon profilePicture = new ImageIcon(getClass().getResource("smiley.png"));
final JLabel profileLabel = new JLabel(profilePicture);
currentPanel.add(profileLabel);
// Button bar
final JPanel buttonPanel = new JPanel();
final GridBagConstraints buttonPanelC = new GridBagConstraints();
final JButton userUpdateButton = new JButton("Update");
final JButton userSignInButton = new JButton("Sign In");
final JButton userAddButton = new JButton("Add");
buttonPanel.add(userUpdateButton);
buttonPanel.add(userSignInButton);
buttonPanel.add(userAddButton);
// Placement of title, list panel, buttons, and current user panel.
titlePanelC.gridx = 0;
titlePanelC.gridy = 0;
titlePanelC.gridwidth = 10;
titlePanelC.gridheight = 1;
titlePanelC.fill = GridBagConstraints.HORIZONTAL;
titlePanelC.anchor = GridBagConstraints.FIRST_LINE_START;
listPanelC.gridx = 0;
listPanelC.gridy = 1;
listPanelC.gridwidth = 10;
listPanelC.gridheight = 8;
listPanelC.fill = GridBagConstraints.BOTH;
listPanelC.anchor = GridBagConstraints.FIRST_LINE_START;
listPanelC.weighty = 0.8;
currentPanelC.gridx = 0;
currentPanelC.gridy = 9;
currentPanelC.gridwidth = 10;
currentPanelC.gridheight = 3;
currentPanelC.fill = GridBagConstraints.HORIZONTAL;
currentPanelC.anchor = GridBagConstraints.FIRST_LINE_START;
buttonPanelC.gridx = 0;
buttonPanelC.gridy = 12;
buttonPanelC.gridwidth = 10;
buttonPanelC.gridheight = 1;
buttonPanelC.fill = GridBagConstraints.HORIZONTAL;
buttonPanelC.anchor = GridBagConstraints.FIRST_LINE_START;
this.add(titlePanel, titlePanelC);
this.add(listShowPanel, listPanelC);
this.add(buttonPanel, buttonPanelC);
this.add(currentPanel, currentPanelC);
userUpdateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
UserPanel.this.getAllUsers(listModel);
}
});
userSignInButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (userList.getSelectedIndex() != -1) {
final String name = userList.getSelectedValue();
final String password = passwordField.getText();
if (clientContext.user.signInUser(name, password)){
userSignedInLabel.setText("Hello " + name);
} else{
userSignedInLabel.setText("User Not Found");
}
}
}
});
userAddButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final String s = (String) JOptionPane.showInputDialog(
UserPanel.this, "Enter user name:", "Add User", JOptionPane.PLAIN_MESSAGE,
null, null, "");
//CHECK VALID UNIQUE USERNAME: either here or ClientUser.java
final String password = (String) JOptionPane.showInputDialog(
UserPanel.this, "Set password:", "Add password", JOptionPane.PLAIN_MESSAGE,
null, null, "");
final String status = (String) JOptionPane.showInputDialog(
UserPanel.this, "Set status:", "Post!", JOptionPane.PLAIN_MESSAGE,
null, null, "");
if (s != null && s.length() > 0) {
clientContext.user.addUser(s, password, status);
UserPanel.this.getAllUsers(listModel);
}
}
});
userList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (userList.getSelectedIndex() != -1) {
final String data = userList.getSelectedValue();
userInfoPanel.setText(clientContext.user.showUserInfo(data));
}
}
});
getAllUsers(listModel);
}
// Swing UI: populate ListModel object - updates display objects.
private void getAllUsers(DefaultListModel<String> usersList) {
clientContext.user.updateUsers();
usersList.clear();
for (final User u : clientContext.user.getUsers()) {
usersList.addElement(u.name);
}
}
}
Try this:
Jlabel imageLogo = new JLabel();
imageLogo.setIcon(new ImageIcon("path/to/your/image"));
Hope you saved your image in your project folder

GridLayout throws illegal component position

By default GridLayout(5,3) would add the components in this way:
A B C
D E F
G H I
J K L
M N O
To have the components disposed in the following positions:
A F K
B G L
C H M
D I N
E J O
I have this code:
//imports...
public class GridLayoutProblem {
private static final int NUM_ROWS = 5, NUM_COLMS=3;
private JPanel mainPanel = new JPanel();
private JPanel buttonPannel = new JPanel(new GridLayout(NUM_ROWS, NUM_COLMS));
private JButton btnA = new JButton("A");
private JButton btnB = new JButton("B");
//same with C, D...
private JButton btnO = new JButton("O");
private JComponent[] buttons = {
btnA, btnB, btnC, btnD, btnE,
btnF, btnG, btnH, btnI, btnJ,
btnK, btnL, btnM, btnN, btnO
};
public GridLayoutProblem(){
int i=0;
for (JComponent button : buttons){
int index = i%NUM_ROWS*NUM_COLMS+i/NUM_ROWS;
buttonPannel.add(button,index);
i++;
}
mainPanel.add(buttonPannel);
}
//...
But it results in:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: illegal component position.
I did a quick test and it seems you cannot skip indexes and add elements to higher index.
So your option is to do something like this,
for (int i = 0; i < NUM_ROWS*NUM_COLMS; i++){
int index = i%NUM_COLMS*NUM_ROWS+i/NUM_COLMS; // Note the change in calculation. Just interchange rows and colms from your algo.
buttonPannel.add(button[index],i);
}
Change buttonPannel.add(button,index); to buttonPannel.add(buttons[index]);. (You don't need a foreach-loop) GridLayout always adds the components like you showed in the first example, but if you can make your calculation for index right (see other answer), so it adds it like "A,F,K,B...", you can achieve what you want.
Run the code below to see how the buttons are being added:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
//imports...
public class GridLayoutProblem {
private static final int NUM_ROWS = 5, NUM_COLMS=3;
private static JPanel mainPanel = new JPanel();
private JPanel buttonPannel = new JPanel(new GridLayout(NUM_ROWS, NUM_COLMS));
private JButton btnA = new JButton("A");
private JButton btnB = new JButton("B");
private JButton btnC = new JButton("C");
private JButton btnD = new JButton("D");
private JButton btnE = new JButton("E");
private JButton btnF = new JButton("F");
private JButton btnG = new JButton("G");
private JButton btnH = new JButton("H");
private JButton btnI = new JButton("I");
private JButton btnJ = new JButton("J");
private JButton btnK = new JButton("K");
private JButton btnL = new JButton("L");
private JButton btnM = new JButton("M");
private JButton btnN = new JButton("N");
private JButton btnO = new JButton("O");
private JComponent[] buttons = {
btnA, btnB, btnC, btnD, btnE,
btnF, btnG, btnH, btnI, btnJ,
btnK, btnL, btnM, btnN, btnO
};
public static void main(String[] args) {
new GridLayoutProblem();
}
public GridLayoutProblem(){
JFrame frame = new JFrame();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < NUM_ROWS * NUM_COLMS; i++) {
int index = i%NUM_COLMS*NUM_ROWS+i/NUM_COLMS;
buttonPannel.add(buttons[index]);
frame.revalidate();
frame.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
mainPanel.add(buttonPannel);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}

Swing: how to get value from JTextfield in every JPanel?

My school project is to create a purchasing system for that I create a JPanel array to list out all the products information and also allow user to input something for every item. And I dont know how to get all the values from jtextfields by clicking one button. The actionPerformed() method always requires a final variable which is quite troublesome for me.
private JButton payBtn;
public void shoppingCartTab(Customer userIn){
contentPanel.removeAll();
bottomPanel.removeAll();
final Customer USER = userIn;
ArrayList<Product> pArray = new ArrayList<Product>();
pArray = loadCartFile.loadCartFile(userIn);
JLabel tabLabel = new JLabel("Shopping Cart");
JPanel cartItems = new JPanel();
cartItems.setLayout(new BoxLayout(cartItems, BoxLayout.Y_AXIS));
final JPanel CONSTANT_CART = cartItems;
JScrollPane scroller = new JScrollPane(cartItems);
if(pArray != null){
JPanel item[] = new JPanel[pArray.size()];
for(int i = 0; i< pArray.size(); i++){
item[i] = new JPanel();
final JPanel JPANEL_TO_DEL = item[i];
item[i].setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.weightx = 0.3;
item[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel icon_small = new JLabel(new ImageIcon("Icons\\" + pArray.get(i).getID() + "_small.jpg"));
JLabel itemID = new JLabel(pArray.get(i).getID());
final String CONSTANT_ID = pArray.get(i).getID();
JLabel itemName = new JLabel(pArray.get(i).getName());
JLabel itemPrice = new JLabel("$" + pArray.get(i).getPrice());
JPanel setQuantity = new JPanel();
JButton plusBtn = new JButton("+");plusBtn.setPreferredSize(new Dimension(45,30));
final JTextField QUANTITY = new JTextField("0");QUANTITY.setColumns(3);
QUANTITY.setPreferredSize(new Dimension(45,30));QUANTITY.setHorizontalAlignment(JTextField.CENTER);
JButton minusBtn = new JButton("-");minusBtn.setPreferredSize(new Dimension(45,30));
plusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())<100)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())+1));
}
});
minusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())>0)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())-1));
}
});
setQuantity.add(plusBtn);
setQuantity.add(QUANTITY);
setQuantity.add(minusBtn);
JButton delBtn = new JButton("Delete");
delBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure to remove this item from your cart?", "Confirm", JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
CONSTANT_CART.remove(JPANEL_TO_DEL);
revalidate();
repaint();
ShoppingCart.removeItem(USER, CONSTANT_ID);
}
}
});
gBC.gridx = 0;
gBC.gridy = 0;
item[i].add(icon_small,gBC);
gBC.gridx = 1;
gBC.gridy = 0;
item[i].add(itemID,gBC);
gBC.gridx = 2;
gBC.gridy = 0;
item[i].add(itemName,gBC);
gBC.gridx = 3;
gBC.gridy = 0;
item[i].add(itemPrice,gBC);
gBC.gridx = 4;
gBC.gridy = 0;
item[i].add(setQuantity,gBC);
gBC.gridx = 5;
gBC.gridy = 0;
item[i].add(delBtn,gBC);
cartItems.add(item[i]);
}
contentPanel.add(tabLabel);
contentPanel.add(scroller);
payBtn = new JButton("Pay");
bottomPanel.add(payBtn); payBtn.addActionListener(this);
}else{
JLabel emptyMsg = new JLabel("Your cart is empty!");
contentPanel.add(emptyMsg);
}
revalidate();
repaint();
}
One solution would be to create a type which extends JPanel, and exposes a public property, which when called returns the value stored in the JTextField. Something like:
public class TextFieldPanel extends JPanel {
private JTextField myTextField;
public TextFieldPanel()
{
//layout init code here
}
public String getText()
{
return myTextField.getText();
}
}
Then just use this class instead of a regular JPanel. Then when your button is clicked, iterate over each of the objects in your collection, and call getText() on them to get your values.

Vertical alignment of checkboxes

Could you help me understand how to set left vertical alignment to the checkboxes. I mean each checkbox on its own row.
Tried everything I could imagine and have come to the end of my wit.
public class DisplayFrame extends JFrame {
public DisplayFrame(ArrayList<String> contents){
DisplayPanel panel = new DisplayPanel(contents, whiteList);
add(panel);
}
private void displayAll(){
DisplayFrame frame = new DisplayFrame(contents, whiteList);
GridBagLayout gbl = new GridBagLayout();
frame.setLayout(gbl);
frame.setVisible(true);
...
}
public class DisplayPanel extends JPanel {
ArrayList<JCheckBox> cbArrayList = new ArrayList<JCheckBox>();
ArrayList<String> contents;
...
public DisplayPanel(ArrayList<String> contents){
...
createListOfCheckBoxes();
}
private void createListOfCheckBoxes() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = contents.size() + 1;
gbc.gridheight = contents.size() + 1;
for (int i = 0; i < contents.size(); i++){
gbc.gridx = 0;
gbc.gridy = i;
String configuration = contents.get(i);
JCheckBox currentCheckBox = new JCheckBox(configuration);
if (whiteList.contains(configuration)){
currentCheckBox.setSelected(true);
}
currentCheckBox.setVisible(true);
add(currentCheckBox, gbc);
}
}
"If I were able to proceed without GridBagLayout, that would suit me"
You can just use a BoxLayout. Box is a convenience class for BoxLayout. You can just do
Box box = Box.createVerticalBox();
for (int i = 0; i < contents.size(); i++){
String configuration = contents.get(i);
JCheckBox currentCheckBox = new JCheckBox(configuration);
if (whiteList.contains(configuration)){
currentCheckBox.setSelected(true);
}
box.add(currentCheckBox);
}
Since Box is a JComponent, you can just add the box to a container.
You can see more at How to Use BoxLayout
Simple Example
import javax.swing.*;
public class BoxDemo {
public static void main(String[] args) {
Box box = Box.createVerticalBox();
JCheckBox cbox1 = new JCheckBox("Check me once");
JCheckBox cbox2 = new JCheckBox("Check me twice");
JCheckBox cbox3 = new JCheckBox("Check me thrice");
box.add(cbox1);
box.add(cbox2);
box.add(cbox3);
JOptionPane.showMessageDialog(null, box);
}
}

Positioning with GridBagLayout

I've a positioning problem with the GridBagLayout :
I try to place in center (at the top) a label but with my code (for a reason which I didn't see), I've this :
I want that the label Test are at the top of my window and in center. Someone can explain me the reason of this bad positionnement ?
My program :
public class Accueil extends JFrame {
private JPanel home = new JPanel();
private GridBagConstraints grille = new GridBagConstraints();
private JLabel title = new JLabel("Test");
public Accueil() {
home.setLayout(new GridLayout());
init_grille();
init_title();
this.add(home);
this.setSize(600,600);
this.setTitle("Test One");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private void init_grille() {
grille.fill = GridBagConstraints.BOTH;
grille.weightx = 2;
grille.weighty = 5;
grille.ipady=grille.anchor=GridBagConstraints.CENTER;;
}
private void init_title() {
grille.fill = GridBagConstraints.HORIZONTAL;
grille.gridx = 0;
grille.gridy = 0;
home.add(title,grille);
}
public static void main(String [] args) {
new Accueil();
}
}
This won't help:
home.setLayout(new GridLayout());
You probably want:
home.setLayout(new GridBagLayout());
Also, these changes should work:
private void init_title() {
grille.fill = GridBagConstraints.NONE;
grille.gridx = 0;
grille.gridy = 0;
grille.anchor = GridBagConstraints.NORTH;
home.add(title,grille);
}

Categories