I have this code right here, and the idea is to have two buttons in a main window alongside a text area, which I have not added yet. After trying to use GridBagLayout and ripping off my hair in the process I decided not to use a layout and manually position buttons inside a non resizable window.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Tema extends JFrame implements ActionListener {
JMenuBar menubar = new JMenuBar();
JMenu actiuni = new JMenu("Actiuni");
JMenu contact = new JMenu("Contact");
JMenu help = new JMenu("Help");
JMenuItem ntest = new JMenuItem("Nou test");
JMenuItem vizarh = new JMenuItem("Vizualizare arhiva");
JMenuItem datcon = new JMenuItem("Date de contact");
JMenuItem sendmail = new JMenuItem("Trimite e-mail");
JMenuItem instrut = new JMenuItem("Instructiuni de utilizare");
JButton b1 = new JButton("Incepe testul!");
JButton b2 = new JButton("Vezi arhiva!");
JTextArea ta = new JTextArea("Default text", 5, 30);
public void common(String s)
{
setSize(800,450);
setLocationRelativeTo(null);
setResizable(false);
setTitle(s);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menubar.add(actiuni);
menubar.add(contact);
menubar.add(help);
actiuni.add(ntest);
actiuni.add(vizarh);
contact.add(datcon);
contact.add(sendmail);
help.add(instrut);
setJMenuBar(menubar);
}
public Tema()
{
common("Self-Esteem- Fereastra Principala");
JPanel cp = new JPanel();
cp.setLayout(null);
b1.setBounds(100,100,200,100);
cp.add(b1);
b2.setBounds(100,250,200,100);
cp.add(b2);
setContentPane(cp);
setVisible(true);
}
public static void main(String[] args)
{
Tema x = new Tema();
}
@Override
public void actionPerformed (ActionEvent e){
}
}
But the output is this:
My question is why isn't the space beneath the second button equal to the space above the first button? Shouldn't they both be 100 pixels?
JFrame
class unnecessarily.Absolute
/Null
LayoutManager
. Use an appropriateLayoutManager
, this includes nesting Layouts to achieve desired look. see here for good tutorials:JFrame#setSize(..)
onJFrame
rather just callJFrame#pack()
before settingJFrame
visible.JFrame#setContentPane(...)
just useadd(..)
onJFrame
instanceActionListener
for multiple components. Unless it will be accessed by other class(es) or components share aAction
. Rather use an Anonymous ActionListenerHere is an example I made (basically your code fixed) hope it helps:
In the above code space between both the buttons is 50px, if you use b2.setBounds(100,300,200,100); then the space will be 100px. Try it...