How to Separate Panels in a JFrame to Separate Classes - java

I have this JFrame named MainFrame and I'm trying to separate each panel into it's own class. I tried and failed with some errors.
Please see the code that I tried. What failed and what did I get wrong?
public class MainFrame extends JFrame {
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private StartScreenPlayerPanel startScreenPlayerPanel;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
System.out.println(screenSize);
frame.setMinimumSize(new Dimension(screenSize.width/2, screenSize.height/2));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
startScreenPlayerPanel = new StartScreenPlayerPanel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, (screenSize.width * 2 / 3), (screenSize.height * 2 / 3));
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{1200, 0};
gbl_contentPane.rowHeights = new int[]{74, 0, 446, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblTitle = new JLabel("The Coin Game",SwingConstants.CENTER);
lblTitle.setFont(new Font("Arial", Font.PLAIN, (int)screenSize.width/30));
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.gridwidth = 2;
gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
gbc_lblTitle.anchor = GridBagConstraints.NORTH;
gbc_lblTitle.fill = GridBagConstraints.HORIZONTAL;
gbc_lblTitle.gridx = 0;
gbc_lblTitle.gridy = 0;
contentPane.add(lblTitle, gbc_lblTitle);
JPanel StartScreenBtnPanel = new JPanel();
GridBagConstraints gbc_StartScreenBtnPanel = new GridBagConstraints();
gbc_StartScreenBtnPanel.gridwidth = 0;
gbc_StartScreenBtnPanel.insets = new Insets(0, 0, 5, 0);
gbc_StartScreenBtnPanel.fill = GridBagConstraints.BOTH;
gbc_StartScreenBtnPanel.gridx = 0;
gbc_StartScreenBtnPanel.gridy = 1;
contentPane.add(StartScreenBtnPanel, gbc_StartScreenBtnPanel);
StartScreenBtnPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnAddPlayer = new JButton("Add Player");
btnAddPlayer.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnAddPlayer);
JButton btnStartGame = new JButton("Start Game");
btnStartGame.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnStartGame);
The code I'm trying to separate to a different Class
// JPanel tblPanel = new JPanel();
// GridBagConstraints gbc_tblPanel = new GridBagConstraints();
// gbc_tblPanel.gridwidth = 2;
// gbc_tblPanel.insets = new Insets(0, 0, 5, 0);
// gbc_tblPanel.fill = GridBagConstraints.BOTH;
// gbc_tblPanel.gridx = 0;
// gbc_tblPanel.gridy = 2;
// contentPane.add(tblPanel, gbc_tblPanel);
// tblPanel.setLayout(new BorderLayout(0, 0));
// table = new JTable();
// tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
// table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 16));
// table.setModel(new DefaultTableModel(
// new Object[][] {
// },
// new String[] {
// "New Player", "Initial Points"
// }
// ) {
// Class[] columnTypes = new Class[] {
// String.class, Integer.class
// };
// public Class getColumnClass(int columnIndex) {
// return columnTypes[columnIndex];
// }
// });
// table.getColumnModel().getColumn(0).setResizable(false);
// table.getColumnModel().getColumn(0).setMinWidth(14);
// tblPanel.add(table, BorderLayout.CENTER);
What I tried
At the end of MainFrame Class
contentPane.add(startScreenPlayerPanel, startScreenPlayerPanel.getSSPPConstraints());
}
public StartScreenPlayerPanel getStartScreenPlayerPanel() {
return startScreenPlayerPanel;
}
New Class - StartScreenPlayerPanel
public class StartScreenPlayerPanel extends JFrame {
MainFrame mainframe;
private JTable table;
private GridBagConstraints gbc_tblPanel = new GridBagConstraints();
public StartScreenPlayerPanel() {
JPanel tblPanel = new JPanel();
gbc_tblPanel.gridwidth = 2;
gbc_tblPanel.insets = new Insets(0, 0, 5, 0);
gbc_tblPanel.fill = GridBagConstraints.BOTH;
gbc_tblPanel.gridx = 0;
gbc_tblPanel.gridy = 2;
tblPanel.setLayout(new BorderLayout(0, 0));
table = new JTable();
tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 16));
table.setModel(new DefaultTableModel(new Object[][] {}, new String[] { "New Player", "Initial Points" }) {
Class[] columnTypes = new Class[] { String.class, Integer.class };
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
});
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(0).setMinWidth(14);
tblPanel.add(table, BorderLayout.CENTER);
}
public GridBagConstraints getSSPPConstraints(){
return gbc_tblPanel;
}
}

I'm trying to seperate each panel to it's own class
public class StartScreenPlayerPanel extends JFrame {
Ok, so why are you extending JFrame?
If you want to add a panel to the main frame then you extend JPanel:
public class StartScreenPlayerPanel extends JPanel {
Now because your class "is a" JPanel, you just set the layout manager of the panel and add components to it.
public StartScreenPlayerPanel()
{
setLayout(new BorderLayout());
table = new JTable();
table.setModel( ... );
add(table.getTableHeader(), BorderLayout.NORTH);
add(table, BorderLayout.CENTER);
}
There is no need for the getSSPPConstraints() method in this class. The "StartScreenPlayerPanel" doesn't know or care how the panel is used. It only worries about the layout of the components in its own class.
The result is a JPanel with a JTable added to the JPanel.
Note: typically when using a JTable you would use:
//add(table.getTableHeader(), BorderLayout.NORTH);
//add(table, BorderLayout.CENTER);
add(new JScrollPane(table), BorderLayout.CENTER);
The scrollpane will automatically add the table header to itself.
Now in your main class you add the panel to the content pane:
//contentPane.add(startScreenPlayerPanel, startScreenPlayerPanel.getSSPPConstraints());
GridBagConstraints gbc_playerPanel = new GridBagConstraints();
gbc_playerPanel.gridwidth = 2;
gbc_playerPanel.insets = new Insets(0, 0, 5, 0);
gbc_playerPanel.fill = GridBagConstraints.BOTH;
gbc_playerPanel.gridx = 0;
gbc_playerPanel.gridy = 2;
contentPane.add(startScreenPlayeerPanel, gbc_playerPanel).
That is the constraints are the property of the class that adds the panel to the content panel.

Related

JPanel with CardLayout is blank when it changed

I've a problem with a JPanel.
It's a CardLayout and two sub-panel that change.
I need to do a button which switch from subpanel 1 to 2 and display selected Product.
ISSUE:
When I select a product card, JPanel changes but it's blank.
If I step over the window with the mouse , the buttons appear, but not the JLabels.
And If I resize the windows, it's empty again.
What is the problem?
EDIT:
Here the code that return same error.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private static final long serialVersionUID = 1L;
// private String title;
// private Dimension d;
public MainFrame(String title, Dimension d) {
// LoginPanel template = new LoginPanel(this);
// RegisterPanel template = new RegisterPanel(this);
CustomerPanel template = new CustomerPanel(this);
this.setTitle(title);
this.setSize(d);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.getContentPane().add(template);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new MainFrame("Fubars", new Dimension(800, 650));
});
}
}
#SuppressWarnings("serial")
class CustomerPanel extends JPanel {
MainFrame mf;
JPanel one, two;
JPanel panel;
public CustomerPanel(MainFrame mf) {
this.mf = mf;
mf.getContentPane().setLayout(new CardLayout(0, 0));
JPanel container = new JPanel();
mf.getContentPane().add(container, "name_36743208542992");
container.setLayout(new BorderLayout(0, 0));
JPanel back = new JPanel();
container.add(back, BorderLayout.NORTH);
back.setLayout(new FlowLayout(FlowLayout.LEFT));
JButton btnControl = new JButton("<");
back.add(btnControl);
panel = new JPanel();
container.add(panel, BorderLayout.CENTER);
CardLayout cl = new CardLayout(0, 0);
panel.setLayout(cl);
one = new OnePanel(this.mf);
two = new JPanel();
panel.add(one, "1");
panel.add(two, "2");
btnControl.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
two = new LoginPanel(mf);
cl.next(panel);
}
});
}
}
#SuppressWarnings("serial")
class LoginPanel extends JPanel {
// private MainFrame mf;
private JTextField textField;
private JPasswordField passwordField;
public LoginPanel(MainFrame mf) {
// this.mf = mf;
mf.getContentPane().setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
mf.getContentPane().add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 100, 55, 72, 171, 0 };
gbl_panel.rowHeights = new int[] { 69, 22, 22, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
JLabel lblNewLabel = new JLabel("Email");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.fill = GridBagConstraints.HORIZONTAL;
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 1;
panel.add(lblNewLabel, gbc_lblNewLabel);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.anchor = GridBagConstraints.NORTH;
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.gridx = 3;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(15);
JLabel lblNewLabel_1 = new JLabel("Password");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.anchor = GridBagConstraints.WEST;
gbc_lblNewLabel_1.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_1.gridx = 1;
gbc_lblNewLabel_1.gridy = 2;
panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
passwordField = new JPasswordField();
passwordField.setColumns(15);
GridBagConstraints gbc_passwordField = new GridBagConstraints();
gbc_passwordField.anchor = GridBagConstraints.NORTH;
gbc_passwordField.gridx = 3;
gbc_passwordField.gridy = 2;
panel.add(passwordField, gbc_passwordField);
JPanel panel_1 = new JPanel();
mf.getContentPane().add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 30));
JButton btnNewButton = new JButton("LOGIN");
panel_1.add(btnNewButton);
btnNewButton.setActionCommand("login");
JButton btnRegistration = new JButton("REGISTER");
panel_1.add(btnRegistration);
btnRegistration.setActionCommand("registration");
}
}
#SuppressWarnings("serial")
class OnePanel extends JPanel {
// private MainFrame mf;
public OnePanel(MainFrame mf) {
// this.mf = mf;
mf.getContentPane().setLayout(new CardLayout(0, 0));
JPanel container = new JPanel();
mf.getContentPane().add(container, "name_36743208542992");
container.setLayout(new BorderLayout(0, 0));
JPanel image = new JPanel();
container.add(image, BorderLayout.CENTER);
JButton btnImageBack = new JButton("<");
image.add(btnImageBack);
JLabel imageContainer = new JLabel("Images");
image.add(imageContainer);
imageContainer.setBounds(new Rectangle(100, 100, 100, 100));
imageContainer.setHorizontalTextPosition(SwingConstants.CENTER);
imageContainer.setHorizontalAlignment(SwingConstants.CENTER);
imageContainer.setAlignmentX(Component.CENTER_ALIGNMENT);
imageContainer.setIconTextGap(3);
imageContainer.setIcon(null);
JButton btnImageForward = new JButton(">");
image.add(btnImageForward);
btnImageForward.setAlignmentY(Component.BOTTOM_ALIGNMENT);
btnImageForward.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel info = new JPanel();
container.add(info, BorderLayout.EAST);
GridBagLayout gbl_info = new GridBagLayout();
gbl_info.columnWidths = new int[] { 0, 0, 63, 0, 0, 0 };
gbl_info.rowHeights = new int[] { 0, 0, 25, 0, 0, 0, 0 };
gbl_info.columnWeights = new double[] { 1.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE };
gbl_info.rowWeights = new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE };
info.setLayout(gbl_info);
JLabel lblTitle = new JLabel("Title");
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.anchor = GridBagConstraints.NORTHWEST;
gbc_lblTitle.insets = new Insets(0, 0, 5, 5);
gbc_lblTitle.gridx = 2;
gbc_lblTitle.gridy = 1;
info.add(lblTitle, gbc_lblTitle);
JLabel lblDescription = new JLabel("Description");
GridBagConstraints gbc_lblDescription = new GridBagConstraints();
gbc_lblDescription.anchor = GridBagConstraints.WEST;
gbc_lblDescription.insets = new Insets(0, 0, 5, 5);
gbc_lblDescription.gridx = 2;
gbc_lblDescription.gridy = 2;
info.add(lblDescription, gbc_lblDescription);
JLabel lblPrice = new JLabel("Price");
GridBagConstraints gbc_lblPrice = new GridBagConstraints();
gbc_lblPrice.anchor = GridBagConstraints.WEST;
gbc_lblPrice.insets = new Insets(0, 0, 5, 5);
gbc_lblPrice.gridx = 2;
gbc_lblPrice.gridy = 3;
info.add(lblPrice, gbc_lblPrice);
lblPrice.setToolTipText("Price");
JButton btnAddCart = new JButton("Add to Cart");
GridBagConstraints gbc_btnAddCart = new GridBagConstraints();
gbc_btnAddCart.insets = new Insets(0, 0, 5, 5);
gbc_btnAddCart.anchor = GridBagConstraints.WEST;
gbc_btnAddCart.gridx = 2;
gbc_btnAddCart.gridy = 4;
info.add(btnAddCart, gbc_btnAddCart);
}
}

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);
}
}

Adding Listeners to various UI elements in MVC

While trying to implement an MVC architecture into a small little school project (and mostly failing) I am having a hard time with the data flow from UI -> controller -> model.
My UI is generally just a single JFrame with a JTabbedPane three tabs holding a JTable and a JPanel (for buttons) respectively.
One of those buttons is supposed to open a Dialog (Custom class extended from JFrame, not registered in UI class)
The user puts info into some fields in this dialog and the info should be communicated to the controller.
How do I properly register Listeners on UI elements that return input with the controller?
In the UI class, I can do it directly but the Dialog object is unknown to the controller.
My expected behavior:
Controller defines an inner class Some_Listener
registers Some_Listener with UI element X via public methods
firing the ActionPerformed() collects the form input and returns it to the Collector
My example code below:
public class Controller {
private UI view;
private DataManager model;
public Controller() {
this.view = new UI();
this.model = new DataManager(this);
addListener();
}
public void showView() {
this.view.setVisible(true);
}
public UI get_view() {
return view;
}
private void addListener() {
view.setNewElement1Listener(new NewElement1Listener());
view.setNewElement2Listener(new NewElement2Listener());
view.setDeleteElementListener(new DeleteElementListener());
}
class NewElement1Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new AddNewElementDialog("key1", view);
}
}
class NewElement2Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new AddNewElementDialog("key2", view);
}
}
class DeleteElementListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Implement listener
}
}
class DialogApproveListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
switch (key) {
case key1:
//use DialogInfo here
break;
case key2:
//use DialogIngfo here too
default:
break;
}
}
}
}
public class AddNewElementDialog extends JFrame {
private static final long serialVersionUID = 6744571L;
private JPanel contentPane = new JPanel();
private JTextField tfNewElementName;
private JFormattedTextField tfNewElementAdress;
private JPanel btnPanel;
private JButton btnOk;
private JButton btnCancel;
private String key;
public AddNewElementDialog(String key, Component mainWindow) {
super();
setTitle("New " + key);
setContentPane(contentPane);
setBounds(100, 100, 250, 100);
setResizable(false);
this.key = key;
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{10, 0, 0, 0, 30, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0};
gbl_contentPane.columnWeights =
new double[]{0.0, 1.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights =
new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
//ignore these; just for margins
JSeparator separator = new JSeparator();
GridBagConstraints gbc_separator = new GridBagConstraints();
gbc_separator.insets = new Insets(0, 0, 5, 5);
gbc_separator.gridx = 0;
gbc_separator.gridy = 0;
contentPane.add(separator, gbc_separator);
JLabel lblName = new JLabel("Name:");
GridBagConstraints gbc_lblName = new GridBagConstraints();
gbc_lblName.insets = new Insets(0, 0, 5, 5);
gbc_lblName.anchor = GridBagConstraints.SOUTHWEST;
gbc_lblName.gridx = 1;
gbc_lblName.gridy = 0;
contentPane.add(lblName, gbc_lblName);
JLabel lblAdress = new JLabel("Adress:");
GridBagConstraints gbc_lblAdress = new GridBagConstraints();
gbc_lblAdress.insets = new Insets(0, 0, 5, 5);
gbc_lblAdress.anchor = GridBagConstraints.SOUTHWEST;
gbc_lblAdress.gridx = 2;
gbc_lblAdress.gridy = 0;
contentPane.add(lblAdress, gbc_lblAdress);
JSeparator separator_1 = new JSeparator();
GridBagConstraints gbc_separator_1 = new GridBagConstraints();
gbc_separator_1.insets = new Insets(0, 0, 5, 0);
gbc_separator_1.gridx = 5;
gbc_separator_1.gridy = 0;
contentPane.add(separator_1, gbc_separator_1);
fNewElementName = new JTextField();
GridBagConstraints gbc_tfNewElementName = new GridBagConstraints();
gbc_tfNewElementName.insets = new Insets(0, 0, 5, 5);
gbc_tfNewElementName.fill = GridBagConstraints.HORIZONTAL;
gbc_tfNewElementName.gridx = 1;
gbc_tfNewElementName.gridy = 1;
contentPane.add(tfNewElementName, gbc_tfNewElementName);
tfNewElementName.setColumns(10);
tfNewElementAdress = new JTextField();
GridBagConstraints gbc_tfNewElementAdress = new GridBagConstraints();
gbc_tfNewElementAdress.fill = GridBagConstraints.HORIZONTAL;
gbc_tfNewElementAdress.insets = new Insets(0, 0, 5, 5);
gbc_tfNewElementAdress.gridwidth = 1;
gbc_tfNewElementAdress.gridx = 2;
gbc_tfNewElementAdress.gridy = 1;
tfNewElementAdress.setColumns(10);
contentPane.add(tfNewElementAdress, gbc_tfNewElementAdress);
btnPanel = new JPanel();
btnPanel.setLayout(new BorderLayout(0, 0));
btnOk = new JButton("OK");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(e -> closeDialog());
btnPanel.add(btnOk, BorderLayout.CENTER);
btnPanel.add(btnCancel, BorderLayout.EAST);
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.insets = new Insets(0, 0, 0, 5);
gbc_panel.gridwidth = 3;
gbc_panel.anchor = GridBagConstraints.SOUTHEAST;
gbc_panel.gridx = 2;
gbc_panel.gridy = 2;
contentPane.add(btnPanel, gbc_panel);
setLocationRelativeTo(mainWindow);
setVisible(true);
}
private void closeDialog(){
this.dispose();
}
public String getNewElementName() {
return tfNewElementName.getText();
}
public String getNewElementAddress() {
return tfNewElementAdress.getText();
}
public String getKey() {
return this.key;
}
public void setDialogApproveListener(ActionListener l) {
this.btnOk.addActionListener(l);
}
}

Increasing distance from top of JPanel

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);
}
}

CardLayout panel display error in existing frame

I have designed a frame containing a few controls using the design view in Netbeans 6.9.1. Further, I have added an empty panel in which I am trying to toggle display of a couple of swing components on button click. The problem is that on button click, the panel displays nothing. The code is as follows:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JPanel txtPanel = new JPanel();
JPanel listPanel = new JPanel();
JTextField txtfield = new JTextField("ABCDEFGHIJ", 20);
txtPanel.add(txtfield);
JList<String> list = new JList<String>();
DefaultListModel<String> model = new DefaultListModel<String>();
for (int i = 0; i < userCommands.size(); i++){
model.addElement(userCommands.get(i));
}
list.setModel(model);
listPanel.add(list);
jPanel2.add(listPanel, "list");
jPanel2.add(txtPanel, "text");
//MainUI.getFrames()[0].add(jPanel2, BorderLayout.CENTER);
itemStateChanged("text");
}
Code for itemStateChanged is as follows:
public void itemStateChanged(String disp) {
CardLayout cl = (CardLayout)(jPanel2.getLayout());
cl.show(jPanel2, disp);
}
In the first piece of code, jPanel2 is dragged and dropped onto the frame containing other components, what i am trying to achieve here is that on button click, the jPanel2 should toggle between text field and list. But currently, the panel is not displaying anything on button click.
Before even considering if jPanel2 can switch between the different panels (the different cards), is jPanel2 on display at all anywhere? The only code I can see that displayes the jPanel2 is adding it to the MainUI but it is commented out?! So how do you know that the display inside jPanel2 isn't switching?
I did a quick example code for you .Have a look.You need to define the Card layout as global and try.
import javax.swing.AbstractAction;
public class TestPanel extends JPanel {
/**
* Create the panel.
*/
JPanel panel;
CardLayout cl = new CardLayout();
public TestPanel() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 155, 0, 0};
gridBagLayout.rowHeights = new int[]{94, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JButton btnNewButton = new JButton("New button");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 0;
add(btnNewButton, gbc_btnNewButton);
btnNewButton.setAction(new AbstractAction("New button") {
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel txtPanel = new JPanel();
JPanel listPanel = new JPanel();
JTextField txtfield = new JTextField("ABCDEFGHIJ", 20);
txtPanel.add(txtfield);
JList<String> list = new JList<String>();
DefaultListModel<String> model = new DefaultListModel<String>();
for (int i = 0; i < 3; i++){
model.addElement("Sanjaya");
}
list.setModel(model);
listPanel.add(list);
panel.add(listPanel, "list");
panel.add(txtPanel, "text");
//MainUI.getFrames()[0].add(jPanel2, BorderLayout.CENTER);
itemStateChanged("list");
}
});
JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
GridBagConstraints gbc_textArea = new GridBagConstraints();
gbc_textArea.insets = new Insets(0, 0, 5, 5);
gbc_textArea.fill = GridBagConstraints.BOTH;
gbc_textArea.gridx = 1;
gbc_textArea.gridy = 0;
add(textArea, gbc_textArea);
panel = new JPanel(cl);
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.insets = new Insets(0, 0, 5, 0);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 2;
gbc_panel.gridy = 0;
add(panel, gbc_panel);
}
public void itemStateChanged(String disp) {
cl.show(panel, disp);
}
}

Categories