how to align buttons in the middle java - java

I am a beginner in Java, but somehow have a bit of knowledge but still beyond. I wanted to ask , how do align buttons in this main menu I just created. The buttons are somehow aligned horizontally.
This is my code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class mainmenu extends JFrame
{
JButton b1;
JLabel l1;
JButton b2;
public mainmenu() {
setResizable(false);
setLocation(100, 100);
setSize(500, 500);
setVisible(true);
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Master Boat\\Desktop\\PH\\BG HOROR.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
b2=new JButton(" EXIT! ");
b1.addActionListener(new btnFunc());
background.add(l1);
background.add(b1);
background.add(b2);
}
public void armaged() {
add(new gamesamplingbeta());
}
public static void main(String args[])
{
new mainmenu();
}
public class btnFunc implements ActionListener {
public void actionPerformed (ActionEvent e) {
}
}
public class btnFunc2 implements ActionListener {
public void actionPerformed2 (ActionEvent e) {
System.exit(1);
}
}
}

You should take a look at Swing Layouts for a whole bunch of different layout managers that allow you to position your components in a bunch of different ways.
The one I believe you should be using for this question is the Box Layout if you would like your buttons centered vertically.
Here is an example of one.
import javax.swing.*;
import java.awt.*;
public class MainFrame
{
JFrame mainFrame = new JFrame("Main Frame");
JPanel mainPanel = new JPanel();
JLabel label1 = new JLabel("Vertical Buttons");
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
public MainFrame()
{
label1.setAlignmentX(Component.CENTER_ALIGNMENT);
button1.setAlignmentX(Component.CENTER_ALIGNMENT);
button2.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(label1);
mainPanel.add(button1);
mainPanel.add(button2);
mainFrame.add(mainPanel);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
If you would like to add spacing in between any of the components, use a Rigid Area like so
container.add(component);
container.add(Box.createRigidArea(new Dimension(100, 100));
container.add(component1);

Related

How to add a button to a JFrame Gui

I'm trying to add a button to a frame gui.
i tried making a panel and adding it to that, but it does not work.
please help!
here is my code:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button;
JPanel panel;
// my error lines are under the "panel" and "button"
// it says i must implement the variables. what does that mean???
panel.add(button);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
Change:
JButton button;
JPanel panel;
to:
JButton button = new JButton();
JPanel panel = new JPanel();
You can also pass a String value in JButton() constructor for that string value to be shown on the JButton.
Example: JButton button = new JButton("I am a JButton");
Example Code:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
// Create JButton and JPanel
JButton button = new JButton("Click here!");
JPanel panel = new JPanel();
// Add button to JPanel
panel.add(button);
// And JPanel needs to be added to the JFrame itself!
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
Output:
Note:
Create the JButton and JPanel using new JButton("..."); and new JPanel()
Add the JPanel to the JFrame's content pane using getContentPane().add(...);
If you can Change this Program, You can adjust the button place also
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class agui extends JFrame
{
agui()
{
setTitle("My GUI");
setSize(400,400);
setLayout(null);
JButton button = new JButton("Click Here..!");
button.setBounds(50,100,100,50); /*Distance from left,
Distance from top,length of button, height of button*/
add(button);
setVisible(true);
}
public static void main(String[] args)
{
JFrame agui = new agui();
}
}
Output

When i want to add the label on the Panel, it will not appear until resizing the frame [duplicate]

This question already has an answer here:
Dynamically adding components to JPanel
(1 answer)
Closed 7 years ago.
When I want to add a label to the Panel, it will not appear until resizing the frame. It does not update.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Actions_GUI
{
JFrame frame;
JPanel panel;
JButton button;
JLabel label;
Actions_GUI()
{
frame = new JFrame();
frame.setSize(400,300);
frame.setTitle("WHY ?");
panel = new JPanel();
panel.setBackground(Color.black);
button = new JButton(" WHY ?");
Here's the event for creating a label on the main panel.
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
label=new JLabel(" Why Don't Upadate? ");
label.setForeground(Color.magenta);
panel.add(label);
}
});
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String [] args)
{
Actions_GUI object = new Actions_GUI();
}
}
You need a call to repaint()
public void actionPerformed(ActionEvent e)
{
label=new JLabel(" Why Don't Upadate? ");
label.setForeground(Color.magenta);
panel.add(label); // adding a label will automatically invalidate the component
panel.revalidate();
panel.repaint(); // you need to repaint
}

How to clear JFrame area by clicking another sub menu of JMenuBar in java Swing?

the code is there for clearing the Frame area by clicking the sub menu(sub_menu_purchase and sub_menu_sale) of main menu.
public void clear()
{
Graphics g = getGraphics();
Dimension d = getSize();
g.setColor(Color.WHITE);
g.fillRect(0,0,d.width,d.height);
}
void sale()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblform =new JLabel("From Party : ");
lblto =new JLabel("To Party : ");
txtto=new JTextField();
txtfrom=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblto.setBounds(50,135,80,25);
txtto.setBounds(140,135,200,25);
lblform.setBounds(50,170,80,25);
txtfrom.setBounds(140,170,100,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblto);
add(lblform);
add(txtto);
add(txtfrom);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
void purchase()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblparty =new JLabel("Party Name: ");
txtparty=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblparty.setBounds(50,135,80,25);
txtparty.setBounds(140,135,200,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblparty);
add(txtparty);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
public void actionPerformed(ActionEvent event) //set up actionlistening
{
Object source=event.getSource();
if (source.equals(sub_menu_purchase))
{ clear();
purchase();
}
if (source.equals(sub_menu_sale))
{ clear();
sale();
}
}
But it is not clear the area and override to one another.
what code should I write?
There's a lot I would do differently from what you're doing, including
Don't get a component's Graphics via getGraphics(). The Graphics object thus obtained will not persist, and so it is not useful for making stable changes to a GUI's appearance.
Don't clear the GUI's graphics but rather change the view. Even if your code worked, the components would not have been removed from the GUI with your code. They would still exist and still sit on the GUI -- not good.
A CardLayout would work well for allowing you to swap a container's view, and is often used to swap JPanels, each holding its own GUI.
Avoid null layout and using setBounds(...) as this will lead to creation of GUI's that are a "witch" to upgrade and maintain and that look bad on all platforms except for one. Better to nest JPanels, each using its own simple layout, to achieve complex, beautiful and easy to maintain and improve GUI's.
Read/study the Swing tutorials as all of this is well explained there.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class UglyGui2 {
private static final String SALE = "Sale";
private static final String PURCHASE = "Purchase";
private JMenuItem sub_menu_sale = new JMenuItem(SALE);
private JMenuItem sub_menu_purchase = new JMenuItem(PURCHASE);
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
private JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
public UglyGui2() {
cardPanel.add(new JLabel(), "");
cardPanel.add(createSalePanel(), SALE);
cardPanel.add(createPurchasePanel(), PURCHASE);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(new JButton("Reset"));
buttonPanel.add(new JButton("Save"));
buttonPanel.add(new JButton("Print"));
buttonPanel.add(new JLabel());
buttonPanel.add(new JButton("Cancel"));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.add(cardPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.PAGE_END);
}
private JComponent createSalePanel() {
JPanel salePanel = new JPanel(new GridBagLayout());
salePanel.add(new JLabel("Sales"));
salePanel.add(new JTextField(10));
return salePanel;
}
private JComponent createPurchasePanel() {
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Purchases"));
topPanel.add(new JTextField(10));
JPanel purchasePanel = new JPanel(new BorderLayout());
purchasePanel.add(topPanel, BorderLayout.PAGE_START);
purchasePanel.add(new JScrollPane(new JTextArea(30, 60)), BorderLayout.CENTER);
return purchasePanel; }
private Component getMainPanel() {
return mainPanel;
}
private JMenuBar getJMenuBar() {
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, e.getActionCommand());
}
};
sub_menu_purchase.addActionListener(aListener);
sub_menu_sale.addActionListener(aListener);
JMenu menu = new JMenu("Menu");
menu.add(sub_menu_purchase);
menu.add(sub_menu_sale);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
private static void createAndShowGui() {
UglyGui2 uglyGui = new UglyGui2();
JFrame frame = new JFrame("Ugly Gui Example");
frame.setJMenuBar(uglyGui.getJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(uglyGui.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Swing Methods on submission of button

How to close current frame (Frame1) and open a new frame (Frame2) already created and pass the data to frame2 from frame1 on the clicking of button?
Use a CardLayout1. Either that or one JFrame and one or more JDialog2 instances.
How to Use CardLayout
How to Make Dialogs
The very best way to accomplish this, is very much told to you by #Andrew Thompson.
And the other way to accomplish, the motive of the question as described in the code. Here as you make object of your new JFrame, you have to pass the things you need in the other class as an argument to the other class, or you can simply pass the object(with this you be passing everything in one go to the other class)
A sample code for a bit of help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFramesExample
{
public JFrame frame;
private JPanel panel;
private JButton button;
private JTextField tfield;
private SecondFrame secondFrame;
public TwoFramesExample()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
tfield = new JTextField(10);
tfield.setBackground(Color.BLACK);
tfield.setForeground(Color.WHITE);
button = new JButton("NEXT");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Here we are passing the contents of the JTextField to another class
// so that it can be shown on the label of the other JFrame.
secondFrame = new SecondFrame(tfield.getText());
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(tfield, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFramesExample();
}
});
}
}
class SecondFrame
{
private JFrame frame;
private JPanel panel;
private JLabel label;
private JButton button;
private TwoFramesExample firstFrame;
public SecondFrame(String text)
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
label = new JLabel(text);
button = new JButton("BACK");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
firstFrame = new TwoFramesExample();
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(label, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
}
Hope this be of some help.
Regards

Swing JLabel text change on the running application

I have a Swing window which contains a button a text box and a JLabel named as flag. According to the input after I click the button, the label should change from flag to some value.
How to achieve this in the same window?
Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:
jLabel.setText("new Value");
A simple demo code will be:
JFrame frame = new JFrame("Demo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250,100);
final JLabel label = new JLabel("flag");
JButton button = new JButton("Change flag");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
label.setText("new value");
}
});
frame.add(label, BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.setVisible(true);
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}

Categories

Resources