I am trying to get familiar with CardLayout so I am making a mock game menu. This menu should have three buttons, but that layout part is easy.
So, what I want to do is start it with a menu with three buttons. The single player button should change what the user sees to a single button, which can change it back to the original menu.
I followed an example online and then applied the same methods to this. However, the menu itself is a card and it's where the command to change cards will come from, not a separate container.
Whenever I run this i get an error:
public class GameMenuCards extends JFrame{
private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
private GridBagConstraints gbc;
public GameMenuCards(){
initUI();
}
public void initUI(){
//set the properties for the window
setTitle("Game Menu With Cards");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
cardPanel = new JPanel();
cl = new CardLayout();
JPanel game = new JPanel();
game.setBackground(Color.BLACK);
//the menu panel
JPanel menu = new JPanel();
menu.setLayout(new GridBagLayout());
menu.setBackground(Color.BLACK);
cardPanel.add(menu, "1");
cardPanel.add(game, "2");
//set up the buttons for the menu
JButton single = new JButton("Single Player");
single.setPreferredSize(new Dimension(300, 30));
single.setBackground(Color.GRAY);
single.setForeground(Color.CYAN);
single.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
JButton multi = new JButton("Multi Player");
multi.setPreferredSize(new Dimension(300, 30));
multi.setBackground(Color.GRAY);
multi.setForeground(Color.CYAN);
multi.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
JButton score = new JButton("High Scores");
score.setPreferredSize(new Dimension(300, 30));
score.setBackground(Color.GRAY);
score.setForeground(Color.CYAN);
score.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
gbc = new GridBagContraints();
//add everything to the menu
gbc.insets = new Insets(35, 50, 0, 50);
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = 1;
menu.add(single, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
label(menu);
gbc.gridx = 1;
gbc.gridy = 3;
menu.add(multi, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
label(menu);
gbc.gridx = 1;
gbc.gridy = 5;
gbc.insets = new Insets(35, 50, 35, 50);
menu.add(score, gbc);
single.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
currentCard = 2;
cl.show(cardPanel, "" + (currentCard));
}
});
JButton returnBut = new JButton("Back To Menu");
returnBut.setPreferredSize(new Dimension(300, 30));
returnBut.setBackground(Color.GRAY);
returnBut.setForeground(Color.CYAN);
returnBut.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
returnBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
currentCard = 1;
cl.show(cardPanel, "" + (currentCard));
}
});
game.add(returnBut);
getContentPane().add(cardPanel);
}
public void label(Container c){
JLabel j1 = new JLabel();
j1.setPreferredSize(new Dimension(300, 40));
j1.setBackground(Color.BLACK);
c.add(j1, gbc);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
GameMenuCards gm = new GameMenuCards();
gm.setVisible(true);
}
});
}
}
I know that i could have done a similar thing with the buttons to the labels but i only had the thought two buttons in, so at that stage it would have taken longer.
Am I going about this the right way? Can you correct any mistakes I've made in the code?
Whenever I run this i get an error
Your application is throwing an NPE here
gbc.insets = new Insets(35, 50, 0, 50);
as you haven't initialized your GridBagConstraints gbc.
Also, the reason that you see both panels side-by-side is that, even though you created a CardLayout, you neglect to use it for your cardPanel. Therefore you are still using the default FlowLayout of the JPanel. You could do:
cardPanel = new JPanel(cl);
Related
I have an actionlistener on a button that is to change a boolean called flood to true when clicked, this is then used in an if statement to call a method that will change a frame. My problem is nothing is happening when the button is clicked. I am using a debug log to check for the problem but I'm stumped.
public class Stop_The_Flood extends JFrame implements ActionListener{
final Button StopTheFlood = new Button("Stop The Flood!");
boolean flood = false;
public Stop_The_Flood(char[][] array) {
setTitle("Stop The Flood!");
setSize(1024,768);
//Container panel
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
//map panel
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(700, 900));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = array[0].length;
gbc.gridheight = array.length;
gbc.fill = GridBagConstraints.BOTH;
//Button Panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
g.gridwidth = 1;
g.gridheight = 1;
g.gridx = 8;
g.gridy = 15;
g.fill = GridBagConstraints.BOTH;
buttonPanel.setSize(350,350);
//Add to everything to frame
getContentPane().add(container);
container.add(panel, gbc);
container.add(buttonPanel, g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 100, 100);
StopTheFlood.setBackground(Color.cyan);
StopTheFlood.addActionListener(this);
JLabel[][] labelArray = new JLabel[array.length][array[0].length];
//Initialize JLabel array with the array that contains the data
labels(panel, labelArray, array);
buttonPanel.add(StopTheFlood);
setVisible(true);
if(flood == true) {
final Logger logger = Logger.getLogger("Stop_The_Flood");
logger.warning("found water");
}
}
public void actionPerformed(ActionEvent event) {
flood = true;
}
Nothing is being performed in your actionPerformed method, so you could try to create a new ClickListener class:
private class Clicklistener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == StopTheFlood)
{
flood = true;
}
}
}
Then on your "Stop_The_Flood" class create an object of ClickListener and add it to .addActionLister():
Clicklistener click= new Clicklistener();
StopTheFlood.addActionListener(click);
P.S don't forget to pass StopTheFlood to the ClickListener since I did not add that to the code.
I am new to swing, am trying to make a form in which you can navigate to different panels by the click of buttons on the left-hand side, to fill out forms(panels) appearing on the right-hand side, and I am using the GridBagLayout for the purpose. I am trying to remove the current panel on the click of the JButton and then add the corresponding panels I created by extending JPanel to classes. For ex., if I click on the accountDetailsButton, I wish to open up the accountDetails Panel, somewhat like switching tabs. I want to replace whichever panel is open on that position with the accountDetails Panel, and since any tab may be open, I need to exchange the panel on the basis of coordinates instead of the component name. I don't know how to go about it as I want to remove and add components on the basis of coordinates on the frame, and the name of the components may not be known. Here's the code.
Thanks a lot in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FormWindow {
private CustomerProfile customerProfile;
private AccountDetails accountDetails;
private LoanDetails loanDetails;
private DocumentUpload documentUpload;
private JPanel mainPanel;
private JLabel logo;
private JButton customerProfileButton;
private JButton accountDetailsButton;
private JButton loanDetailsButton;
private JButton documentUploadButton;
private JPanel bufferPanel;
public static void main(String[] args) {
JFrame frame = new JFrame("FormWindow");
frame.setContentPane(new FormWindow().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
FormWindow() {
mainPanel = new JPanel();
bufferPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
customerProfile = new CustomerProfile();
accountDetails = new AccountDetails();
loanDetails = new LoanDetails();
documentUpload = new DocumentUpload();
// fieldForm.setLayout(new GridBagLayout());
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridheight = 5;
gbc.fill = GridBagConstraints.BOTH;
bufferPanel.add(customerProfile);
mainPanel.add(bufferPanel, gbc);
final GridBagConstraints gbcForms = gbc;
logo = new JLabel();
logo.setText("LOGO");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(5, 5, 10, 5);
mainPanel.add(logo, gbc);
customerProfileButton = new JButton();
customerProfileButton.setText("Customer Profile");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
mainPanel.add(customerProfileButton, gbc);
accountDetailsButton = new JButton();
accountDetailsButton.setText("Account Details");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
mainPanel.add(accountDetailsButton, gbc);
loanDetailsButton = new JButton();
loanDetailsButton.setText("Loan Details");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
mainPanel.add(loanDetailsButton, gbc);
documentUploadButton = new JButton();
documentUploadButton.setText("Document Upload");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
mainPanel.add(documentUploadButton, gbc);
//adding action listeners to buttons
customerProfileButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
accountDetailsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
loanDetailsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
documentUploadButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
}
}
I wish to display the corresponding panel on the right-hand side of the frame when the corresponding button is clicked. For ex., if I click the accountDetailsButton, I want to replace the previously visible panel with the accountDetails panel (the code for accountDetails has the accountDetails class extending JPanel). This is done to get the feel of switching between tabs in a way.
just a disclaimer: I already checked most of Stack Overflow and couldn't find an answer on the website. I also asked some nice people on Reddit, but only fixed it halfway through.
So, I am trying the create a GUI application and I am new to the Java language (very, very new - so there is a big chance I am making a rookie mistake). I already designed my interface for my 'StartScreen' and I wanted to make button1 to open my second class ('NewUsers').
I was using the GUI Editor and I think this is probably the cause of my problems, as an answer to my question online I just saw people add
this.dispose();
new JFrame().setVisible(true);
This doesn't work on me however. I managed to fix it until a certain point and now I am able to close the frame on a click, but I still can't figure out how to open another frame from the button :(. Here is my code for Frame1('StartScreen'). Frame2 is just an empty window for now, but it's for testing purposes.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class StartScreen {
private final JFrame frame;
private JButton newUserButton;
private JButton existingUserButton;
private JButton nonUserBookingButton;
private JPanel panell;
public StartScreen() {
this.frame = new JFrame("StartScreen");
frame.setContentPane(panell);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
newUserButton.addActionListener(this::onNewUserClicked);
}
public static void newuserscall
() {
NewUsers newuserscall = new NewUsers();
}
private void onNewUserClicked(ActionEvent event) {
frame.setVisible(false);
}
public static void main(String[] args) {
new StartScreen();
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
panell = new JPanel();
panell.setLayout(new GridBagLayout());
panell.setPreferredSize(new Dimension(600, 400));
final JPanel spacer1 = new JPanel();
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(30, 0, 0, 0);
panell.add(spacer1, gbc);
newUserButton = new JButton();
newUserButton.setText("Button");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.BOTH;
panell.add(newUserButton, gbc);
existingUserButton = new JButton();
existingUserButton.setText("Button");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.BOTH;
panell.add(existingUserButton, gbc);
nonUserBookingButton = new JButton();
nonUserBookingButton.setText("Button");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 6;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.BOTH;
panell.add(nonUserBookingButton, gbc);
final JPanel spacer2 = new JPanel();
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 3;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.VERTICAL;
panell.add(spacer2, gbc);
final JPanel spacer3 = new JPanel();
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 5;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(0, 250, 0, 0);
panell.add(spacer3, gbc);
final JPanel spacer4 = new JPanel();
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 5;
gbc.fill = GridBagConstraints.VERTICAL;
panell.add(spacer4, gbc);
final JPanel spacer5 = new JPanel();
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(25, 0, 0, 0);
panell.add(spacer5, gbc);
final JLabel label1 = new JLabel();
label1.setText("Label");
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 0;
panell.add(label1, gbc);
final JPanel spacer6 = new JPanel();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 6;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(30, 0, 0, 0);
panell.add(spacer6, gbc);
final JPanel spacer7 = new JPanel();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(30, 0, 0, 0);
panell.add(spacer7, gbc);
}
/**
* #noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return panell;
}
}
Thanks in advance! I hope some of you can figure out a way I can fix my code :(
Regards
Well what I'll start out saying is that you are correct: never use a GUI Builder. I don't even mean when you're trying to learn, I mean never use it. It's mainly there for prototyping a concept and not meant for you to use it for learning or production code. Below is a cleaned up more precise example for you, but in your particular example, you need to add your
new JFrame().setVisible(true);
inside of your onNewUserClicked function. Also, note that when you do that, you're creating an empty frame, that will be the absolute minimum amount of size that it takes for your OS to create it because there's nothing in it, you never packed the frame, and never manually and explicitly set the size, so check around your top left area of your monitor - it's there.
Here is probably closer to what you want in terms of cleanliness.
public class Foo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final JFrame jf = new JFrame();
JPanel jp = new JPanel();
JButton jb = new JButton("New Frame");
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jf.setVisible(false);
new JFrame().setVisible(true);
}
});
jp.setLayout(new FlowLayout());
jp.add(jb);
jf.setContentPane(jp);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.pack();
}
}
}
}
The reason why I say cleaner at all, is because of the control of a LayoutManager. GUI builders like the one you use always tend to use GridBagLayout because it's easier for it to dynamically (from your user input) place things precisely. But the code it generates is unmanageable. And things get worse when you consider that if you expand or contract your GUI, that the GridBagLayout is not flexible with this so now your Components are stuck exactly where you placed them when dragging them from the GUI Builder. Proper use of the correct LayoutManager will give you a flexible and manageable GUI. Check out this Oracle guide for more info and help: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
That is because you are disposing the parent frame before showing the new one.
In this scenario your parent frame, from which you are calling
new JavaFrame2().SetVisibility(true);
contains the handle to the new JavaFrame. By disposing the parent frame you technically delete the parent -> you cant do something with it any more.
Try hiding the startscreen by calling .SetVisibility(false) instead of this.dispose();.
Why are the JLabel, JTextField and JButton components on the FieldBox panel not displaying?
Please let me know if I can add anything to this question to make it more answerable!
The field box (one of which is created for each of several instance fields):
public class FieldBox extends javax.swing.JPanel {
JLabel label;
JTextField textField;
public FieldBox() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
label = new JLabel();
gbc.gridx = 0;
gbc.gridy = 0;
add(label,gbc);
textField = new JTextField();
gbc.gridx = 1;
gbc.gridy = 0;
add(textField, gbc);
JButton editBtn = new JButton("edit");
gbc.gridx = 2;
gbc.gridy = 0;
add(editBtn, gbc);
JButton saveBtn = new JButton ("save");
gbc.gridx = 3;
gbc.gridy = 0;
add(saveBtn, gbc);
label.setVisible(true);
label.setBackground(Color.yellow);
setVisible(true);
initComponents();
}
The panel onto which the boxes are added: (the panel appears. I know this panel loads because I can see its background. I can also see the "tit" JLabel, which I'm using for testing. Also, when I load the boxes onto it using a gridLayout (as shown below), I see the background of one of the boxes, but none of its contents are displayed, and also there should be three boxes shown but I only see one. Using a GridBagLayout
public class ShowBook extends javax.swing.JPanel {
public ShowBook(Book b) {
setLayout(new GridLayout(1,6));
setBackground(Color.GREEN);
String[] fieldTitles = {"title", "catalog", "publisher" };
JLabel tit = new JLabel("tit");
add(tit);
for (String s : fieldTitles){
FieldBox fb = new FieldBox();
fb.label.setText(s + ": ");
fb.textField.setText(getField(b, s));
System.out.println("in text field" + fb.textField.getText());
fb.revalidate();
fb.setVisible(true);
add (fb);
}
revalidate();
setVisible(true);
}
The panel onto which the ShowBook panel (above) is added. This panel also contains a listbox, which lists books in the collection, and a button to launch a ShowBook panel with the selected book as parameter.
public class ShowLib extends javax.swing.JPanel {
/**
* Creates new form ShowLib
*/
public ShowLib(Library l) {
setLayout(new BorderLayout()) ;
setBackground(Color.WHITE);
JPanel listPanel = new JPanel();
listPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
final JList bookList = new JList();
bookList.setVisible(true);
bookList.setPreferredSize(new Dimension(150, 600));
bookList.setBackground(Color.yellow);
DefaultListModel dlm = new DefaultListModel();
for (Book b : l.libList){
dlm.addElement(b);
}
bookList.setModel(dlm);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = gbc.BOTH;
listPanel.add(bookList, gbc);
JButton showBtn = new JButton("show");
gbc.gridy = gbc.RELATIVE;
listPanel.add(showBtn, gbc);
showBtn.addActionListener(new ActionListener () {
#Override
public void actionPerformed(ActionEvent e){
Book b = (Book) bookList.getSelectedValue();
ShowBook db = new ShowBook (b);
System.out.println("Clicked");
add (db, BorderLayout.CENTER);
revalidate();
}
});
revalidate();
setVisible(true);
add(listPanel, BorderLayout.WEST);
}
Where the ShowLib panel is added to the main JFrame. I know this works because that panel displays properly
void showLib() {
ShowLib sl = new ShowLib(l);
sl.setVisible(true);
setContentPane(sl);
revalidate();
// this.revalidate();
// this.pack();
System.out.println("showlibClicked");
}
The problem was the line initComponents(); at the bottom of the FieldBox class.
Lesson learned: If you're not using NetBeans visual GUI editor, GET RID OF THIS LINE!
Is it possible i can have a top panel for a login. Then a middle and bottom panel underneath.
I'm using gridbaglayout and i have assigned 2 panels. One panel has components linked to it for login details and the other panel has other components linked to it. However, it's not going occurring to plan.
Ive tried using Box/Borderlayout to do this, but then i'm not able to create the spacing i want.
Here is a sketch of what i want.
public class GUI extends JFrame{
private JPanel myTopPL, myTopPL2;
private JTextField myUsernameTF;
private JTextField myPasswordTF;
private JTextField myMessageTF;
private JLabel myUsernameLBL;
private JLabel myPasswordLBL;
private JLabel myItemsLBL;
private JTextArea myMainTA;
private JButton myLoginBN;
private JButton myConnectBN;
private JButton mySendBN;
private JComboBox myItemsCB;
public GUI () {
super("GUI ");
setLayout(new GridBagLayout());
myTopPL = new JPanel();
myTopPL2 = new JPanel();
myTopPL.setLayout(new GridBagLayout());
myTopPL2.setLayout(new GridBagLayout());
GridBagConstraints myTopPLGBC = new GridBagConstraints();
myTopPLGBC.weightx = 1;
myTopPLGBC.weighty = 1;
GridBagConstraints myTopPLGBC2 = new GridBagConstraints();
myTopPLGBC.weightx = 2;
myTopPLGBC.weighty = 2;
myUsernameLBL = new JLabel("Username: ");
myUsernameLBL.setFont(new Font("Arial", Font.BOLD, 13));
myTopPLGBC.gridx = 1;
myTopPLGBC.gridy = 1;
myTopPLGBC.insets = new Insets(5,5,5,5);
myTopPL.add(myUsernameLBL, myTopPLGBC);
myUsernameTF = new JTextField(10);
myTopPLGBC.gridx = 2;
myTopPLGBC.gridy = 1;
myTopPLGBC.insets = new Insets(5,5,5,5);
myTopPL.add(myUsernameTF,myTopPLGBC);
myPasswordLBL = new JLabel("Password: ");
myPasswordLBL.setFont(new Font("Arial", Font.BOLD, 13));
myTopPLGBC.gridx = 3;
myTopPLGBC.gridy = 1;
myTopPLGBC.insets = new Insets(5,5,5,5);
myTopPL.add(myPasswordLBL, myTopPLGBC);
myPasswordTF = new JTextField(10);
myTopPLGBC.gridx = 4;
myTopPLGBC.gridy = 1;
myTopPLGBC.insets = new Insets(5,5,5,5);
myTopPL.add(myPasswordTF,myTopPLGBC);
myLoginBN = new JButton("Login");
myTopPLGBC.gridx = 5;
myTopPLGBC.gridy = 1;
myTopPLGBC.insets = new Insets(5,5,5,5);
myTopPL.add(myLoginBN,myTopPLGBC);
myItemsLBL = new JLabel("Items: ");
myItemsLBL.setFont(new Font("Arial", Font.BOLD, 13));
myTopPLGBC2.gridx = 1;
myTopPLGBC2.gridy = 3;
myTopPLGBC2.insets = new Insets(5,5,5,5);
myTopPL2.add(myItemsLBL, myTopPLGBC2);
myItemsCB = new JComboBox();
myItemsCB.addItem(" Select an Item ");
myTopPLGBC2.gridx = 1;
myTopPLGBC2.gridy = 4;
myTopPLGBC2.insets = new Insets(5,5,5,5);
myTopPL2.add(myItemsCB, myTopPLGBC2);
myConnectBN = new JButton("Connect");
myTopPLGBC2.gridx = 2;
myTopPLGBC2.gridy = 4;
myTopPLGBC2.insets = new Insets (5,5,5,5);
myTopPL2.add(myConnectBN, myTopPLGBC2);
GridBagConstraints GBC = new GridBagConstraints();
GBC.anchor = GridBagConstraints.NORTHWEST;
GBC.weightx = 1;
GBC.weighty = 1;
this.add(myTopPL,GBC);
GridBagConstraints GBC2 = new GridBagConstraints();
GBC2.anchor = GridBagConstraints.NORTHWEST;
GBC2.weightx = 2;
GBC2.weighty = 2;
this.add(myTopPL2,GBC2);
}
public static void main(String[] args) {
GUI GUI = new GUI ();
GUI .setDefaultCloseOperation(RMIAuctionHouse.EXIT_ON_CLOSE);
GUI .setSize(750,500);
GUI .setVisible(true);
}
}
I'd break down the application into it's individual areas of responsibilities and focus on creating the UI elements to support it. This will allow you to focus on the needs of each section of your application, it also allows you the opportunity to change around the layout as you need
public class TestLayout15 {
public static void main(String[] args) {
new TestLayout15();
}
public TestLayout15() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
private JTextField messageField;
private JButton sendButton;
public MainPane() {
setBorder(new EmptyBorder(4, 4, 4, 4));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new LoginPane(), gbc);
gbc.gridy++;
add(new ConnectPane(), gbc);
gbc.gridy++;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new JScrollPane(new JTextArea(5, 20)), gbc);
gbc.gridwidth = 1;
messageField = new JTextField(10);
sendButton = new JButton("Send");
gbc.gridy++;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(messageField, gbc);
gbc.gridx++;
gbc.weightx = 0;
add(sendButton, gbc);
}
}
public class ConnectPane extends JPanel {
private JComboBox comboBox;
private JButton connectButton;
public ConnectPane() {
comboBox = new JComboBox();
connectButton = new JButton("Connect");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
add(comboBox, gbc);
gbc.gridx++;
gbc.weightx = 1;
add(connectButton, gbc);
}
}
public class LoginPane extends JPanel {
private JTextField userNameField;
private JPasswordField passwordField;
private JButton loginButton;
public LoginPane() {
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
loginButton = new JButton("Login");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
add(new JLabel("User name:"), gbc);
gbc.gridx++;
add(userNameField, gbc);
gbc.gridx++;
add(new JLabel("Password:"), gbc);
gbc.gridx++;
add(passwordField, gbc);
gbc.gridx++;
gbc.weightx = 1;
add(loginButton, gbc);
}
}
}
To start with, replace the call to GUI.setSize(750,500) with GUI.pack(). That will size the window to fit your content. After doing that you'll see the second panel is appearing to the right of the first. This is because you did not set gridx/gridy on GBC2 so it defaults to putting myTopPL2 to the right of myTopPL1, not below it.
I rarely explicitly set the gridx/gridy when using GridBagLayout. For your first row of the display, I would use default values for all but myLoginBN where I would set gridwidth to GridBagConstraints.REMAINDER. That tells GridBagLayout that nothing else goes on this row. The next item added with a default gbc will be placed at the start of the second row.
Minor nits:
Use standard Java capitalization:
Class name are camelcase with a leading uppercase character. So, "Gui", not "GUI".
Instance names are camelcase with a leading lowercase character. So, "gbc1" not "GBC1"
Use SwingUtilities.InvokeLater to start the Gui on the EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUI GUI = new GUI ();
GUI .setDefaultCloseOperation(RMIAuctionHouse.EXIT_ON_CLOSE);
GUI .setSize(750,500);
GUI .setVisible(true);
}});
Seems you are not familiar with Java layouts, so i recomend you to try null(absolute) Layout:
setLayout(null);
...
component.setBounds( x, y, width, heigh );
add(component);
Here example
package gui;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JFrame{
private JTextField myUsernameTF;
private JLabel myUsernameLBL;
public GUI() {
super("GUI ");
setLayout(null);
myUsernameLBL = new JLabel("Username: ");
myUsernameLBL.setFont(new Font("Arial", Font.BOLD, 13));
myUsernameLBL.setBounds(50,30,80,20);
add(myUsernameLBL);
myUsernameTF = new JTextField(10);
myUsernameTF.setBounds(190,30,80,20);
add(myUsernameTF);
// and so on ...
}
public static void main(String[] args) {
GUI frame = new GUI();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(750,500);
frame.setVisible(true);
}
}
Good luck on thorny way to handle java swing =)