I'm using GridLayout class in Java to layout some UI components. Image is here:
I would like to get the Create Shopping Cart picture and the associated text to be aligned center in their respective cells in the panel. For details - the shopping cart picture would have to be in the center of the gray cell of the panel. And the text in the JTextArea have to be center aligned as well. Can you please help. My code is attached.
import javax.swing.*;
import java.awt.*;
class ImageDemo extends JFrame
{
ImageDemo()
{
Container pane = getContentPane();
pane.setLayout(new GridLayout(2,2));
setSize(800,400);
setLayout(new GridLayout(2,2));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel cartpane = new JPanel();
cartpane.setLayout(new GridLayout(1,2));
/*
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.SOUTH;
c.fill=GridBagConstraints.BOTH;
cartpane.add(imglabelcart,c);
c.gridx=1;
c.gridy=0;
c.fill=GridBagConstraints.BOTH ;
c.anchor = GridBagConstraints.WEST;
cartpane.add(cartta,c);
*/
ImageIcon iconcart = new ImageIcon("cart.jpg");
JLabel imglabelcart = new JLabel("Create Shopping Cart");
imglabelcart.setIcon(iconcart);
imglabelcart.setVerticalTextPosition(SwingConstants.BOTTOM);
imglabelcart.setHorizontalTextPosition(SwingConstants.CENTER);
JTextArea cartta = new JTextArea();
cartta.setLineWrap(true);
cartta.append("Use the Create Shopping Cart transaction to create a
new shopping cart for your purchases.\n");
cartta.append("You can view the products available in the catalog and select
them to be part of your shopping cart.");
cartpane.add(imglabelcart);
cartpane.add(cartta);
ImageIcon iconapprove = new ImageIcon("approve.jpg");
ImageIcon iconviewpo = new ImageIcon("viewpo.jpg");
ImageIcon iconlogout = new ImageIcon("viewpo.jpg");
JLabel imglabelapprove = new JLabel("Approve Shopping Cart");
JLabel imglabelviewpo = new JLabel("View Purchase Order");
JLabel imglabellogout = new JLabel("Logout");
imglabelapprove.setIcon(iconapprove);
imglabelapprove.setVerticalTextPosition(SwingConstants.BOTTOM);
imglabelapprove.setHorizontalTextPosition(SwingConstants.CENTER);
imglabelviewpo.setIcon(iconviewpo);
imglabelviewpo.setVerticalTextPosition(SwingConstants.BOTTOM);
imglabelviewpo.setHorizontalTextPosition(SwingConstants.CENTER);
imglabellogout.setIcon(iconlogout);
imglabellogout.setVerticalTextPosition(SwingConstants.BOTTOM);
imglabellogout.setHorizontalTextPosition(SwingConstants.CENTER);
pane.setBackground(new Color(156,195,252));
pane.add(cartpane);
pane.add(imglabelapprove);
pane.add(imglabelviewpo);
pane.add(imglabellogout);
setVisible(true);
}
public static void main(String[] args)
{
ImageDemo demoi = new ImageDemo();
}
}
Use setHorizontalAlignment() method of JLabel like next:
imglabelapprove.setHorizontalAlignment(JLabel.CENTER);
For centring text in JTextArea read that answer.
Related
this has seriously been the biggest issue in my code. I just want to create a simple pizza order taker using multiple panels. I want to be able to dictate the specific area each panel is located. Can someone please just pretend I'm a complete idiot and help me point this out?
I've attached my code as well as an image of how it looks so far. I want to be able to place individual segments like getting the user's information, choosing pizza size, then toppings, then a section where I will display the receipt with all of the order total.
I can do the calculations and take in values, I just need to figure out the appearance.
import javax.swing.*;
import java.awt.*;
public class PIZZA extends JFrame {
Container window = getContentPane();
ButtonGroup ordertype;
JRadioButton delivery, takeout;
JRadioButton small, medium, large;
JLabel fname, phonenum, zipcode;
JTextField ufname, uphonenum, uzipcode;
JPanel userinfoinput;
JPanel delivery_type;
JPanel userinfolabel;
JButton start;
BoxLayout userbox, labelbox, deliverybox;
ImageIcon starticon = new ImageIcon("start.png");
public PIZZA() {
}
public static void main(String[] args){
PIZZA frame = new PIZZA();
new PIZZA();
frame.setSize(new Dimension(600,600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("KRUSTY KRAB PIZZA");
frame.deliverymethod();
frame.getuserinfo();
frame.userinfolabels();
frame.getpizzasize();
frame.toppings_meat();
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
private void deliverymethod(){
delivery_type = new JPanel();
ordertype = new ButtonGroup();
delivery = new JRadioButton("Delivery (Currently Unavailable)");
delivery.setEnabled(false);
takeout = new JRadioButton("Take Out");
ordertype.add(takeout);
ordertype.add(delivery);
delivery_type.add(takeout);
delivery_type.add(delivery);
delivery_type.setSize(100,100);
window.add(delivery_type,BorderLayout.NORTH);
}
private void getuserinfo(){
userinfoinput = new JPanel();
//start = new JButton("Start", starticon);
//start.setLayout(null);
ufname = new JTextField(12);
uphonenum = new JTextField(12);
uzipcode = new JTextField(12);
userinfoinput.add(ufname);
userinfoinput.add(uphonenum);
userinfoinput.add(uzipcode);
//userinfoinput.add(start);
GridLayout lay = new GridLayout(3,1);
userinfoinput.setLayout(lay);
window.add(userinfoinput, BorderLayout.CENTER);
}
private void userinfolabels(){
userinfolabel = new JPanel();
fname = new JLabel("First Name");
phonenum = new JLabel("Phone Number");
zipcode = new JLabel("Zip Code");
userinfolabel.add(fname);
userinfolabel.add(zipcode);
userinfolabel.add(phonenum);
labelbox = new BoxLayout(userinfolabel, BoxLayout.Y_AXIS);
GridLayout label = new GridLayout(3,1);
userinfolabel.setLayout(label);
window.add(userinfolabel, BorderLayout.CENTER);
}
private void getpizzasize(){
JPanel pizzasize = new JPanel();
ButtonGroup size = new ButtonGroup();
small = new JRadioButton("Small");
medium = new JRadioButton("Medium");
large = new JRadioButton("Large");
size.add(small);
size.add(medium);
size.add(large);
pizzasize.add(small);
pizzasize.add(medium);
pizzasize.add(large);
pizzasize.setLayout(new FlowLayout());
pizzasize.setSize(100,100);
window.add(pizzasize, BorderLayout.SOUTH);
}
private void toppings_meat(){
JPanel meat = new JPanel();
meat.setLayout(new BoxLayout(meat, BoxLayout.Y_AXIS));
JCheckBox pepperoni = new JCheckBox("Pepperoni");
JCheckBox meatball = new JCheckBox("Meatball");
JCheckBox chicken = new JCheckBox("Grilled Chicken");
JCheckBox sausage = new JCheckBox("Italian Sausage");
JCheckBox bacon = new JCheckBox("Bacon");
meat.add(pepperoni);
meat.add(meatball);
meat.add(chicken);
meat.add(sausage);
meat.add(bacon);
window.add(meat);
}
}
This pizza GUI uses several Swing layout managers in different JPanels.
The main layout managers that I want to talk about are the JFrame BorderLayout and the input form GridBagLayout.
A BorderLayout is rather flexible in that you can put Swing components in various locations. The JPanels I created for this GUI are in the BEFORE_FIRST_LINE, CENTER, AFTER_LAST_LINE, and AFTER_LINE_ENDS positions of the BorderLayout.
The input form uses a GridBagLayout to position the JLabels and the input JTextFields in a column. The GridBagLayout is more flexible than a GridLayout because the grid cells don't have to be the same size in a GridBagLayout.
The Oracle Swing tutorial A Visual Guide to Layout Managers shows the different Swin layout managers, and how to use them.
Here's the code I used to create the pizza GUI. I created each subordinate JPanel in a separate method. All of the JFrame code is in the run method. Separating different parts of the GUI allows me to focus on one part of the GUI at a time. I can test each JPanel method separately.
I create the Swing components from left to right, top to bottom within a JPanel. This allows me to visually verify that I've included all the appropriate methods for a component. This also allows me to zero in on any component that isn't correct.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PizzaOrdering implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PizzaOrdering());
}
#Override
public void run() {
JFrame frame = new JFrame("KRUSTY KRAB PIZZA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getDeliveryMethodPanel(),
BorderLayout.BEFORE_FIRST_LINE);
frame.add(getUserInformationPanel(),
BorderLayout.CENTER);
frame.add(getPizzaSizePanel(),
BorderLayout.AFTER_LAST_LINE);
frame.add(getMeatToppingsPanel(),
BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getDeliveryMethodPanel() {
JPanel deliveryMethodPanel = new JPanel(new FlowLayout());
ButtonGroup orderTypeGroup = new ButtonGroup();
JRadioButton takeoutRadioButton =
new JRadioButton("Take Out");
orderTypeGroup.add(takeoutRadioButton);
deliveryMethodPanel.add(takeoutRadioButton);
JRadioButton deliveryRadioButton =
new JRadioButton("Delivery (Currently Unavailable)");
deliveryRadioButton.setEnabled(false);
orderTypeGroup.add(deliveryRadioButton);
deliveryMethodPanel.add(deliveryRadioButton);
return deliveryMethodPanel;
}
private JPanel getUserInformationPanel() {
JPanel userInformationPanel = new JPanel(new GridBagLayout());
userInformationPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.weightx = 1d;
JLabel nameLabel = new JLabel("First Name:");
userInformationPanel.add(nameLabel, gbc);
gbc.gridx++;
JTextField userNameField = new JTextField(20);
userInformationPanel.add(userNameField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel phoneNumberLabel = new JLabel("Phone Number:");
userInformationPanel.add(phoneNumberLabel, gbc);
gbc.gridx++;
JTextField userPhoneNumberField = new JTextField(20);
userInformationPanel.add(userPhoneNumberField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel zipCodeLabel = new JLabel("Zip Code:");
userInformationPanel.add(zipCodeLabel, gbc);
gbc.gridx++;
JTextField userZipCodeField = new JTextField(20);
userInformationPanel.add(userZipCodeField, gbc);
return userInformationPanel;
}
private JPanel getPizzaSizePanel() {
JPanel pizzaSizePanel = new JPanel(new FlowLayout());
ButtonGroup sizeGroup = new ButtonGroup();
JRadioButton smallRadioButton = new JRadioButton("Small");
sizeGroup.add(smallRadioButton);
pizzaSizePanel.add(smallRadioButton);
JRadioButton mediumRadioButton = new JRadioButton("Medium");
sizeGroup.add(mediumRadioButton);
pizzaSizePanel.add(mediumRadioButton);
JRadioButton largeRadioButton = new JRadioButton("Large");
sizeGroup.add(largeRadioButton);
pizzaSizePanel.add(largeRadioButton);
return pizzaSizePanel;
}
private JPanel getMeatToppingsPanel() {
JPanel meatToppingsPanel = new JPanel();
meatToppingsPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
meatToppingsPanel.setLayout(new BoxLayout(
meatToppingsPanel, BoxLayout.Y_AXIS));
JCheckBox pepperoniCheckBox = new JCheckBox("Pepperoni");
meatToppingsPanel.add(pepperoniCheckBox);
JCheckBox meatballCheckBox = new JCheckBox("Meatball");
meatToppingsPanel.add(meatballCheckBox);
JCheckBox chickenCheckBox = new JCheckBox("Grilled Chicken");
meatToppingsPanel.add(chickenCheckBox);
JCheckBox sausageCheckBox = new JCheckBox("Italian Sausage");
meatToppingsPanel.add(sausageCheckBox);
JCheckBox baconCheckBox = new JCheckBox("Bacon");
meatToppingsPanel.add(baconCheckBox);
return meatToppingsPanel;
}
}
I am having issue where my JPanel is not setting up the size. I am not sure if is something to do with my JTab or JFrame. I am using GridBagLayout layout management. And for some reason are not able to set the size.
Here is a dummy code, following the same logic to my original source code:
FirstPanel.java
import javax.swing.*;
import java.awt.*;
public class FirstPanel extends JPanel {
private JLabel label1 = new JLabel("Label 1");
private JTextField textField1 = new JTextField();
private GridBagConstraints c = new GridBagConstraints();
public FirstPanel() {
//Size is not overriding
Dimension size = getPreferredSize();
size.width = 100;
setPreferredSize(size);
setBorder(BorderFactory.createTitleBorder("Border Title");
setLayout(new GridBagLayout());
addComponents();
}
private void addComponents() {
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(5, 0, 0, 0);
add(label1, c);
c.gridx = 1;
add(textField1, c);
c.weightx = 1;
c.weighty = 1;
add(new JLabel(""), c);
}
}
MainPanel.java
import javax.swing.*;
import java.awt.*;
public class MainPanel {
private JFrame frame = new JFrame("App");
private JPanel panel1 = new JPanel(new GridBagLayout());
private GridBagConstraints c = new GridBagConstraints();
private JTabbedPane tabPane = new JTabbedPane();
public MainPanel() {
addComponents();
frame.add(tabPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 350);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
private void addComponents() {
tabPane.addTab("Tab 1", new FirstPanel());
}
}
Main.java
public class Main {
public static void main(String[] args) {
new MainPanel();
}
}
Or at least have two JPanels,
Exactly.
Frist you create a main panel using a BorderLayout that you add to the tabbed pane.
Then you have a second panel for your labels and text fields (using whatever layout manager you want). Then you add this panel to the BorderLayout.LINE_START.
Then you add your scrollpane containing the JTable to the BorderLayout.CENTER of the main panel.
Read the tutorial on Layout Manager. Nest panels with different layout managers as required.
want to have JTable taking 50% of the other side.
Picking a random number like 50% is not the way to design a GUI. What happens if the frame is made smaller/larger. What happens to the space? Design the layout with flexibility in mind, just like your browser window is designed. There are always fixed areas where the size is determined by the components added and there is a flexible area that grows/shrinks as desired.
The above frame contains gridlayout with two rows. First row is text area,second is a panel with two checkboxes. I want to increase height of first row so that first row should be 75% of Total height and second row should be 25%. How can I do that? Here is my code snippet:
setLayout(new GridLayout(2, 0, 0, 0));
Panel text_panel = new Panel();
add(text_panel);
text_panel.setLayout(new GridLayout(1, 0, 0, 0));
JTextArea textArea = new JTextArea();
textArea.setText("text to be displayed");
JScrollPane scroll = new JScrollPane (textArea);
text_panel.add(scroll);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
Border border = BorderFactory.createLineBorder(Color.GRAY);
textArea.setBorder(border);
textArea.setFont(new Font("Arial",Font.PLAIN,12));
textArea.setCaretPosition(0);
textArea.requestFocus();
Panel checebox_panel = new Panel();
checebox_panel.setBackground(Color.WHITE);
add(checebox_panel);
checebox_panel.setLayout(new GridLayout(1, 0, 0, 0));
androidCheckBox = new JCheckBox("Open start page");
androidCheckBox.setBackground(Color.WHITE);
androidCheckBox.addItemListener(itemListener);
androidCheckBox.setSelected(true);
checebox_panel.add(androidCheckBox);
eclipseCheckBox = new JCheckBox("register for updates");
eclipseCheckBox.setBackground(Color.WHITE);
eclipseCheckBox.addItemListener(itemListener);
eclipseCheckBox.setSelected(true);
checebox_panel.add(eclipseCheckBox);
This is not possible with GridLayout. GridLayout will always use even spacing. Look into another layout manager.
Here is a good reference:
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
With GridLayout you can't have two rows that are different sizes. Look into BoxLayout. Something like this:
JPanel content = new JPanel();
frame.getContentPane().add(content);
LayoutManager layout = new BoxLayout(content, BoxLayout.Y_AXIS);
Box boxes[] = new Box[2];
boxes[0] = Box.createHorizontalBox();
boxes[1] = Box.createHorizontalBox();
boxes[0].createGlue();
boxes[1].createGlue();
content.add(boxes[0]);
content.add(boxes[1]);
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
panel.setPreferredSize(new Dimension(500,300));
panel2.setPreferredSize(new Dimension(500,200));
boxes[0].add(panel);
boxes[1].add(panel2);
Using setPreferredSize is never optimal, but it works. This is just an example of how you could do it, I'm sure there is better ways though! ;)
"Increase a row size in Gridlayout" I came across this requirement and by trying to device a solution I got one, tried border instead grid layout. it might be helpful :)
here is the code:
import ComponentMeta.RequiredComp;
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PromptPopup extends JDialog {
private final JScrollPane scrollPane = new JScrollPane();
private int rows;
private int cols;
private int vGap;
private int hGap;
private Map<String, Component> componentRepo;
public PromptPopup(JFrame parent) {
super(parent);
componentRepo = new HashMap<>();
this.setModalityType(ModalityType.APPLICATION_MODAL);
}
public void setComponentsDisplayStyle(int rows, int cols, int vGap, int hGap) {
this.rows = rows;
this.cols = cols;
this.vGap = vGap;
this.hGap = hGap;
}
public void setComponentReop() {
JTextField dynamicParamTextField = new JTextField();
this.componentRepo.put("COMPANY_CODE", dynamicParamTextField);
JTextField dynamicParamTextField2 = new JTextField();
this.componentRepo.put("DIST_CODE", dynamicParamTextField2);
JTextField dynamicParamTextField3 = new JTextField();
this.componentRepo.put("LOCA_CODE", dynamicParamTextField3);
JTextField dynamicParamTextField4 = new JTextField();
this.componentRepo.put("TOKEN_EXEC", dynamicParamTextField4);
}
public void initPopupUI() {
//Setting content panes layout
getContentPane().setLayout(new BorderLayout(0, 0));
//Creating a root panel(root container) to hold the child components
JPanel rootContainer = new JPanel();
rootContainer.setLayout(new BorderLayout());
//Creating header panel(header container) to hold the header components
JPanel header = new JPanel();
header.setLayout(new FlowLayout());
JLabel headerText = new JLabel("Source query parameters required ");
headerText.setForeground(Color.WHITE);
header.add(headerText);
header.setBackground(Color.BLUE);
//Creating footer panel(footer container ) to hold the footer components
JPanel footer = new JPanel();
footer.setLayout(new FlowLayout());
JButton executeWithParamsButton = new JButton("Execute with params");
executeWithParamsButton.setBackground(Color.BLACK);
executeWithParamsButton.setForeground(Color.WHITE);
JButton cancelButton = new JButton("Cancel");
cancelButton.setBackground(Color.RED);
cancelButton.setForeground(Color.WHITE);
footer.add(executeWithParamsButton);
footer.add(cancelButton);
footer.setBackground(Color.BLUE);
//Creating content panel(content container) to hold the all dynamically generated components
JPanel contentContainer = new JPanel();
GridLayout gridLayout = new GridLayout(this.rows, this.cols, this.hGap, this.vGap);
contentContainer.setLayout(gridLayout);
for (Map.Entry entry : componentRepo.entrySet()) {
JLabel dynamicParamLabel = new JLabel(entry.getKey().toString());
contentContainer.add(dynamicParamLabel);
contentContainer.add((Component) entry.getValue());
}
// Adding all the created containers to the root container one by one
rootContainer.add(header, BorderLayout.NORTH);
rootContainer.add(contentContainer, BorderLayout.CENTER);
rootContainer.add(footer, BorderLayout.SOUTH);
//Adding the root container to the scroll pane in order the view to be scrollable nno matter how many components are there.
scrollPane.setViewportView(rootContainer);
getContentPane().add(scrollPane);
}
}
And Here is output I wanted i.e The Header to be on top consuming space only based on it's components and same for the Center panel and The footer containing button controls.
output
I'm in the middle of working on a program. It's GUI has two main parts, the left of the JFrame and the right of the JFrame. (Currently the right half is blank because I havn't started working on it yet).
The left part doesn't look good. All the buttons and textfields are stretched. I want them to have the height of standard buttons, similiar to the ones on this site. (You know, standard windows buttons).
How do I do that?
(I wouldn't want to simply pack() the whole thing, since the right half of the window is going to have a big square JPanel, and so pack()ing would mean that the window will still be square and the buttons on the left half would still be streched up and down).
Here's a picture:
And here's the code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
rightPanel = new JPanel();
optionsPanel = new JPanel();
pointsPanel = new JPanel();
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
optionsPanel.add(rect);
optionsPanel.add(oval);
optionsPanel.add(tri);
optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Try this
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
JPnel p=new JPanel();
p.add(rect);
p.add(oval);
p.add(tri);
p.add(free);
p.add(addPoint);
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
rightPanel = new JPanel();
optionsPanel = new JPanel();
pointsPanel = new JPanel();
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
optionsPanel.add(p);
//optionsPanel.add(oval);
//optionsPanel.add(tri);
//optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Like this for JLabels and JTextFields
Please go through following link for more information about Grid layout
How to Use GridLayout
Also try with different layouts in java swing
A Visual Guide to Layout Managers
Please try FlowLayout it is suitable for your requirement.
Just change setLayout(new FlowLayout());
Output :
You have that effect, because you use GridLayout, which resize component to whole cell(vertically/horizontally). You need to use another LayoutManager, or combinations of layouts.
For example I've changed your code with GridBagLayout:
private void initUI(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setLayout(new GridBagLayout());
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
leftPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
rightPanel = new JPanel();
rightPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
optionsPanel = new JPanel(new GridBagLayout());
pointsPanel = new JPanel(new GridBagLayout());
GridBagConstraints cMain = new GridBagConstraints();
cMain.insets = new Insets(5, 5, 5, 5);
cMain.gridx = 0;
cMain.gridy = 0;
cMain.anchor = GridBagConstraints.NORTHWEST;
add(leftPanel,cMain);
cMain.fill = GridBagConstraints.BOTH;
cMain.gridx++;
cMain.weighty = 1;
cMain.weightx = 1;
add(rightPanel,cMain);
leftPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
leftPanel.add(optionsPanel,c);
c.gridy++;
leftPanel.add(pointsPanel,c);
c.gridy = 0;
optionsPanel.add(rect,c);
c.gridx++;
optionsPanel.add(oval,c);
c.gridx++;
optionsPanel.add(tri,c);
c.gridx++;
optionsPanel.add(free,c);
c.gridx = 0;
c.gridy = 1;
pointsPanel.add(xLabel,c);
c.gridx++;
pointsPanel.add(xTextField,c);
c.gridx++;
pointsPanel.add(yLabel,c);
c.gridx++;
pointsPanel.add(yTextField,c);
c.gridx++;
pointsPanel.add(addPoint,c);
setSize(500,500);
setVisible(true);
}
I have been working on a main menu screen. I use a card layout because I have a splash screen that shows up before the main menu screen. Once the user clicks the "Continue" button on the splash screen, they are brought to the main menu screen.
I can't add a screenshot because I don't have a high enough reputation but as of now the buttons are pushed off to the side, I assume because of the card layout.
Is there any way that I can place the button on top of the main menu screen image?
Here is my code for the window:
package edu.ycp.cs.Main;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Window {
JPanel cards; // a panel that uses CardLayout
final static String SPLASHSCREEN = "SplashScreen";
final static String MAINMENU = "MainMenu";
public void addComponentToWindow(Container pane) {
// Put the JComboBox in a JPanel to get a nicer look.
JPanel gameWindow = new JPanel(); // use FlowLayout
// Create the "cards".
JPanel card1 = new JPanel();
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, MAINMENU);
}
});
card1.add(new SplashScreen());
card1.add(continueButton);
JPanel card2 = new JPanel();
JButton menuButton1 = new JButton("PLAY!");
JButton menuButton2 = new JButton("HIGH SCORES");
card2.add(new MainMenuScreen());
card2.add(menuButton1);
card2.add(menuButton2);
cards = new JPanel(new CardLayout());
cards.add(card1, SPLASHSCREEN);
cards.add(card2, MAINMENU);
pane.add(gameWindow, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
}
}
Any suggestions on how to get the button on top of the image?
JPanel card1 = new JPanel();
card1.add(new SplashScreen());
card1.add(continueButton);
A JPanel use a FlowLayout. So when you add two components to it they are just painted beside each other.
You want the component to be painted on top of each other so you need to do something like:
JPanel card1 = new JPanel();
SplashScreen splash = new SplashScreen();
splash.setLayout( new FlowLayout() );
card1. add(splash);
splash.add( continueButton );
Your JPanel that contains your 2 menuButton and MenuScreen doesn't have a layout. Use one like GridBagLayout and set the buttons on top. You could use another layout, that's up to you.
I used buttons only to show you a simple example for GridBagLayout and suggest you check Oracle's page on that layout if you wish to use it.
JPanel card2 = new JPanel();
card2.setLayout(new GridBagLayout());
JButton menuButton1 = new JButton("PLAY!");
JButton menuButton2 = new JButton("HIGH SCORES");
JButton menuButton3 = new JButton("UNDER THE 2 OTHERS");
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 0;
gbc2.gridy = 1;
gbc2.weightx = 1;
gbc2.weighty = 1;
gbc2.gridwidth = 2;
gbc2.fill = GridBagConstraints.HORIZONTAL;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.gridx = 1;
gbc3.gridy = 0;
gbc3.weightx = 1;
gbc3.weighty = 1;
gbc3.fill = GridBagConstraints.HORIZONTAL;
card2.add(menuButton1, gbc);
card2.add(menuButton2, gbc3);
card2.add(menuButton3, gbc2);
If your splash screen only has that one button, you could try making your entire splash image a button, as in this example: Java: using an image as a button
You could edit your existing splash screen image to add a Continue Button inside the image itself. Of course the user would be able to click anywhere (as it would be one huge image button).
Sounds cheesy, I know. But it might be a quick-and-dirty way to get close enough to what you want.