I can't move the buttons to the bottom - JFrame - java

I tried using GridLayout and BorderLayout but could not make my Buttons go below the mouth of the dog (picture). After making the button below the dog mouth, how do I add function to the buttons? For Settings, how do I make it open another window after I clicked on it and I can close the settings window instead of the whole thing. Thank you!
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Codegi extends JFrame {
public Codegi() {
JFrame frame = new JFrame();
try {
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("enter image description here[1]")))));
} catch (IOException e) {
e.printStackTrace();
}
frame.pack();
frame.setLayout(new FlowLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
p1.setOpaque(false);
p2.setOpaque(false);
p1.setLayout(new BorderLayout(0, 20));
//JButton b1 = new JButton("START");
//JButton b2 = new JButton("SETTINGS");
p2.add(p1);
p1.add(new JButton("SETTINGS"), BorderLayout.SOUTH);
p1.add(new JButton("START"), BorderLayout.CENTER);
//p1.add(b1);
//p1.add(b2);
frame.add(p2);
//design of button
//Font largefont = new Font("TimesRoman", Font.BOLD, 20);
//b1.setBackground(Color.ORANGE);
//b2.setBackground(Color.ORANGE);
//b1.setForeground(Color.BLACK);
//b2.setForeground(Color.BLACK);
//b1.setFont(largefont);
//b2.setFont(largefont);
frame.setTitle("Codegi:Programming made fun");
frame.setSize(498, 687);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(467, 627);
}
public static void main(String args[]) {
new Codegi();
}
}
Screenshot

Set the layout to null
view.setLayout(null);
and then set the position of buttons like below
btn.setBounds(starting x-coordinate,starting y-coordinate,btn width,btn height);
remove panels by setVisible(false);
and show new ones with setVisible(true); on btn click event

Related

No error shown but JButton and Label can't be seen

I'm new to coding and I am facing this problem where it doesn't show the JButton and JLabel that i added in the GUI. What have i done wrong and how do i fix it?
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class MainMenu {
public static void main (String []args) {
JFrame frame = new JFrame ("Main Menu");
frame.setSize(480,720);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2,5,5));
JButton meals = new JButton ("Meals");
JLabel label = new JLabel ("Welcome back!");
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(meals);
panel.add(label);
frame.add(panel);
}
}
That happens because you frame.setVisible(true); before adding any components to it. You should add the components to the frame first, and then, use the setVisible method.
panel.add(meals);
panel.add(label);
frame.add(panel);
frame.setVisible(true); //visible after components added
Fixed version of your code below. Hopefully it works. I tested it in my IDE.
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class MainMenu {
public static void main(String[] args) {
JFrame frame = new JFrame("Main Menu");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 5, 5));
JButton meals = new JButton("Meals");
JLabel label = new JLabel("Welcome back!");
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(meals);
panel.add(label);
frame.add(panel);
frame.setSize(480, 720);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

JFrame loading glitch

Can someone help me with my code, please. I am expiriencing strange behaviour in Eclipse.
Sometimes my application loads correctly and most of times I don't get North and South JPanels loaded properly or not loaded at all.
After loading GUI displays correctly only when I resize JFrame borders, but I would like to load every time correctly. I guess I have some trouble in my code but I can't find it. And btw, I am running Linux Mint 19.1 Tarra with java-11-openjdk-amd64.
Here is code for Main class:
package gui;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
new Dakijevstina();
}
}
And here is GUI class code:
package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
#SuppressWarnings("serial")
public class Dakijevstina extends JFrame{
Font font = new Font("TimesNew Roman", Font.PLAIN, 12);
public Dakijevstina() {
initComponents();
}
public void initComponents() {
//setting up JFrame
setTitle("Market garden financial software");
setFont(font);
setLayout(new BorderLayout());
setSize(640, 480);
setDefaultCloseOperation(Dakijevstina.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setVisible(true);
//setting up North JPanel
JPanel pnlNorth = new JPanel(new FlowLayout(FlowLayout.LEFT));
pnlNorth.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(pnlNorth, BorderLayout.NORTH);
//setting up StatusBar
JPanel pnlSouth = new JPanel(new FlowLayout(FlowLayout.LEFT));
pnlSouth.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(pnlSouth, BorderLayout.SOUTH);
//adding buttons to north JPanel
//About
JButton btnAbout = new JButton();
JButton btnExit = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("/images/about.png"));
Image img2 = ImageIO.read(getClass().getResource("/images/exit.png"));
btnAbout.setIcon(new ImageIcon(img));
btnExit.setIcon(new ImageIcon(img2));
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex);
}
btnAbout.setPreferredSize(new Dimension(40, 40));
btnAbout.setMinimumSize(new Dimension(40, 40));
btnAbout.setToolTipText("Information about author");
btnExit.setPreferredSize(new Dimension(40, 40));
btnExit.setMinimumSize(new Dimension(40, 40));
btnExit.setToolTipText("Exit application");
btnExit.addActionListener(e -> exitApp());
pnlNorth.add(btnAbout);
pnlNorth.add(btnExit);
//adding StatusBar to south JPanel
JLabel status = new JLabel("Welcome to Dakijevstina software");
status.setFont(font);
pnlSouth.add(status);
}
//event handlers
public void exitApp() {
this.dispose();
}
This is what I get most of time:
unwanted behaviour
And this is how it supose to be:
this is what I want

java not displaying jpanel in jframe after button press

I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...

Open a menu from buttons

hello eveybody i created this code :
package project1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
public class ccc {
public static void main(String[] args){
JFrame frame = new JFrame("Food delivery"); // Create a frame
frame.setSize(1600, 1400); // Set the frame size
frame.setLocationRelativeTo(null); // New since JDK 1.4
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Display the frame
JPanel panel = new JPanel(new FlowLayout());
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
ImageIcon icon = new ImageIcon("hamburger.jpg");
frame.setIconImage(icon.getImage());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
try {
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("fd12.jpg")))));
} catch (IOException e) {
e.printStackTrace();
}
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel label = new JLabel("Welcome to Food Delivery");
label.setFont(new Font("Courier New", Font.BOLD, 38));
label.setForeground(Color.black);
System.out.println("");
JButton btn1= new JButton("Breakfast");
btn1.setFont(new Font("Courier New", Font.BOLD, 16));
btn1.setForeground(Color.BLACK);
JButton btn2= new JButton("Starters");
btn2.setFont(new Font("Courier New", Font.BOLD, 16));
btn2.setForeground(Color.BLACK);
JButton btn3= new JButton("Main Dishes");
btn3.setFont(new Font("Courier New", Font.BOLD, 16));
btn3.setForeground(Color.BLACK);
JButton btn4= new JButton("Deserts");
btn4.setFont(new Font("Courier New", Font.BOLD, 16));
btn4.setForeground(Color.BLACK);
JButton btn5= new JButton("Drinks");
btn5.setFont(new Font("Courier New", Font.BOLD, 16));
btn5.setForeground(Color.BLACK);
frame.add(label);
frame.add(new JSeparator());
frame.add(btn1);
frame.add(btn2);
frame.add(btn3);
frame.add(btn4);
frame.add(btn5);
frame.pack();
frame.setVisible(true);
}}
screen shot :
enter image description here
I would love to get a new page inside the page that get opens for each buttons and inside I will write the menu of the food to select and near to it have the prices written ?? please help me I couldn't not do it at all and can know how ...
Thanks
You can use JPanel to draw things inside other Containers. (JPanel and JFrame are Containers)
But u said u just want to write text. So u can use a JTextArea.
Javadoc will help u.
As noted in the comments by Emz, a CardLayout is the best fist for this scenario. Create a JPanel for each of the menus and add them to a JPanel with CardLayout. Then use the buttons to switch between the panels.
Here is an example:
public class Example extends JPanel {
Example() {
JPanel starters = new JPanel(new FlowLayout());
starters.add(new JLabel("starters..."));
JPanel drinks = new JPanel(new FlowLayout());
drinks.add(new JLabel("drinks..."));
JPanel main = new JPanel(new CardLayout());
main.add(starters, "starters");
main.add(drinks, "drinks");
JPanel buttons = new JPanel();
JButton startersButton = new JButton("Starters");
startersButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout)(main.getLayout());
cl.show(main, "starters");
}
});
JButton drinksButton = new JButton("Starters");
drinksButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout)(main.getLayout());
cl.show(main, "drinks");
}
});
buttons.add(startersButton);
buttons.add(drinksButton);
setLayout(new BorderLayout());
add(main);
add(buttons, BorderLayout.PAGE_START);
}
}
Add to a frame and run.

Centering image in a JFrame?

I'm creating an about JFrame for my program. I have an icon which I used for the program and I have that show up as the first thing on the about JFrame, but I'm having issues trying to center the image. If I do some kind of centering it screws up the whole alignment of everything else.
I'm trying to have all the JLabels, other than the icon, to be left aligned. Then have the icon aligned to the center.
I had to remove some personal information, whatever I did remove I put them between "[]".
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class About extends JFrame {
public About() {
super("About [PROGRAM]");
setIconImage([PROGRAM].getInstance().setIcon());
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel icon = new JLabel("", new ImageIcon(getClass().getResource(Constants.ICON_FULL)), JLabel.CENTER);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
main.add(icon);
main.add(Box.createRigidArea(new Dimension(0, 10)));
main.add(name);
main.add(expandedName);
main.add(copyright);
main.add(credits);
add(main);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
Consider using some layouts to help you out. Ones that come to mind include BorderLayout with the icon in the BorderLayout.CENTER position. You can stack stuff on one side using a BoxLayout using JPanel that is added to the main BorderLayout-using JPanel.
e.g.,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class About extends JDialog {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/"
+ "800px-European_Common_Frog_Rana_temporaria.jpg";
public About(JFrame frame) {
super(frame, "About [PROGRAM]", true);
ImageIcon myIcon = null;
try {
URL imgUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imgUrl);
myIcon = new ImageIcon(img);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JPanel main = new JPanel(new BorderLayout());
main.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel centerLabel = new JLabel(myIcon);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
int eb = 20;
centerLabel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.add(name);
leftPanel.add(Box.createVerticalGlue());
leftPanel.add(expandedName);
leftPanel.add(copyright);
leftPanel.add(credits);
leftPanel.add(Box.createVerticalGlue());
main.add(centerLabel, BorderLayout.CENTER);
main.add(leftPanel, BorderLayout.LINE_START);
add(main);
pack();
}
public static void main(String[] args) {
final JFrame frame = new JFrame("GUI");
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("About") {
#Override
public void actionPerformed(ActionEvent e) {
About about = new About(frame);
about.setLocationRelativeTo(frame);
about.setVisible(true);
}
}));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Categories