why the last GUI element i declare is filling the whole panel? - java

public class add extends JPanel {
private JPanel add = new JPanel();
JFrame frame;
public add(){
frame = new JFrame("Add");
frame.setBounds(550, 300, 700,500);
frame.setVisible(true);
JLabel nameLabel = new JLabel("Name");
final JTextField nameField = new JTextField();
frame.add(nameLabel);
frame.add(nameField);
nameLabel.setBounds(200, 40, 150, 30);
nameField.setBounds(350, 40, 150, 30);
...
JButton registerButton = new JButton("Salveaza");
frame.add(registerButton);
registerButton.setBounds(200,300,300, 30);
registerButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
}
}
and if i delete the JButton, than a label, which would be the last element, will fill the whole JPanel when i run the programm.
what can i do so i can make it work properly?

You're adding components to a container, the JFrame's contentPane, that uses a BorderLayout as its default layout manager. When you do this and don't specify constants, the component gets added BorderLayout.CENTER, covering up any components added before.
Good Solution: learn and use layout managers, including using nested JPanels, each using its own layout manager and components.
Bad Solution: use null layout with absolute positioning. While to a newbie this seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.

Related

Why can I not edit the location of my JButton?

Code:
public class launcher implements ActionListener {
private static JFrame window;
private static JPanel panel;
private JButton createPassword;
private JButton seePassword;
public launcher() {
window = new JFrame();
panel = new JPanel();
window.setTitle("Password Vault");
window.setSize(400, 260);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setVisible(true);
window.getContentPane().add(panel); // Adds panel to JFrame
createPassword = new JButton("Create Password");
createPassword.setBounds(20, 100, 150, 100);
createPassword.addActionListener(this);
seePassword = new JButton("View Password");
seePassword.setLocation(20, 50);
seePassword.addActionListener(this);
panel.add(createPassword);
panel.add(seePassword);
}
public static void main(String[] args) {
new launcher();
}
Why can I not change the location of my JButtons? I have tried the setBounds and setLocation function but my buttons still stay on the top middle part of the JFrame window. I have also tried declaring my buttons inside the launcher() method and declaring them as a static variable.
You should NOT attempt to set the size/location of your buttons.
Swing was designed to be used with layout managers. The layout manager will set the size/location of the button based on the rules of the layout manager.
The default layout manager for a JPanel is the FlowLayout, which is why you see the button centered.
If you want to position the buttons differently, then you need to change the layout manager.
Read the section from the Swing tutorial on Layout Managers for more information and examples.
It looks like you want the buttons displayed vertically, so maybe a BoxLayout or GridLayout can be used depending on your exact requirement.
Other issues with your code:
Class names should start with an upper case character
There is no need to use static variables. That is not how the static keyword should be used
Components should be added to the frame BEFORE the frame is made visible.
You should be invoking pack() on the frame, BEFORE invoking setVisible(...) so the components can be displayed at their preferred size.
While you really shouldn't change the place of your components without a layout manager, there is a way. If you put this line of code into your code, it should work with setBounds:
window.setLayout(null);

Why i cant move(locate) the button

i try to locate my buttons in frame to center, or, if to be honest, make my layout more flexible. But when i set properties like as .setBounds, my buttons have no reaction. Why? Thx for any help!
import com.sun.beans.editors.ColorEditor;
import javax.swing.*;
import java.awt.*;
public class windowsInterface extends JFrame{
windowsInterface(){
super("When the nearest HB");
setSize(800, 800);
JPanel panelForAddDel = new JPanel();
panelForAddDel.setSize(800, 100);
panelForAddDel.setLocation(0, 0);
panelForAddDel.setBackground(Color.gray);
JTextField nameOfStaff = new JTextField();
JTextField dateOfBirth = new JTextField();
JButton addRec = new JButton("Добавить");
addRec.setBounds(100, 100, 200, 50);
JButton delRec = new JButton("Удалить");
delRec.setBounds(100, 100, 200, 50);
addRec.setBounds(320, 125, 200, 50);
delRec.setBounds(420, 125, 200, 50);
JPanel panelForWatch = new JPanel();
panelForWatch.setLocation(0, 100);
panelForWatch.setSize(800, 600);
panelForWatch.setBackground(Color.BLUE);
add(panelForAddDel);
add(panelForWatch);
panelForAddDel.add(nameOfStaff);
panelForAddDel.add(dateOfBirth);
panelForAddDel.add(addRec);
panelForAddDel.add(delRec);
}
}
But when i set properties like as .setBounds, my buttons have no reaction. Why?
Because there is a default layout in the Java Components. For instance, JFrame uses a default BorderLayout manager which determines how your added components within the JFrame will position and overrules your setBounds() methods, hence giving you the impression that it isn't working.
You will realise that if you remove this layout by setting it to null this.setLayout(null), setBounds() will seem to function again.
However, it is recommended that you choose an appropriate layout based on your needs instead of using null layout.
I would recommend you to add your components to a JPanel and add the JPanel to the JFrame instead of adding directly into the JFrame.
Set an appropriate layout for your JPanel
If needed, you can use nested JPanels with each having different layout to meet your needs.
This might be because the default layout for panel is flow layout. Read about it
http://www.javatpoint.com/FlowLayout. A more flexible layout is GridBagLayout you can change the layout of panels or JFrames to your choice.
To learn about GridBagLayout: https://www.tutorialspoint.com/swing/swing_gridbaglayout.htm

Layouts Issue on Different Components?

I'm writing a gui program in which use flow layout to set components.I know this layout start from default center and goes left to right like this
I also know structure of all other layouts but i want to make a gui like this
All components in center.But layout use in that picture is null.I only want to know about how can we do that in these type of layout like border,flow etc.
Code :
public class Main {
public static void main(String[] args) {
JFrame obj = new JFrame();
obj.setTitle("My Frame");
obj.setSize(800, 600);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setLocationRelativeTo(null);
JLabel l1 = new JLabel("Enter Name");
l1.setFont(new Font("Tahoma", Font.PLAIN, 21));
JTextField t1 = new JTextField(20);
t1.setFont(new Font("Tahoma", Font.PLAIN, 16));
JButton b1 = new JButton("Submit");
obj.setLayout(new FlowLayout());
obj.add(l1);
obj.add(t1);
obj.add(b1);
obj.setVisible(true);
}
}
You could use a BoxLayout. Something like:
box.add(label);
box.add(textField);
box.add(button);
box.add(Box.createVerticalGlue());
You may have to play with the setAlignmentX(...) property to allow the components to be centered horizontally.
Read the section from the Swing tutorial on How to Use BoxLayout for more information and examples.
Or you could use a GridBagLayout. The tutorial also has a section on How to Use GridBagLayout.

Java Swing - JTable not showing

I'm having some troubles with Java Swing.
I'm trying to make a frame with a control panel at the top with some buttons in it.
and below that i want a JTable to show
I've been trying but the table is not showing.
If I remove the controlPanel at the top, it sometimes shows and sometimes not.
The code that I use inside my constructor of my JTable is provided in the same application,
so it's no network error
public ServerMainFrame(GuiController gc){
this.gc = gc;
initGUI();
}
private void initGUI() {
System.out.println("initiating GUI");
createFrame();
addContentPanel();
addControls();
//openPopUpServerSettings();
addSongTable();
}
private void createFrame()
{
this.setTitle("AudioBuddy 0.1");
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(800, 600);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
private void addContentPanel()
{
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.setSize(new Dimension(800, 600));
this.setContentPane(p);
}
private void addControls()
{
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.setBorder(BorderFactory.createLineBorder(Color.black));
controlPanel.setSize(700,100);
// Buttons
JButton play = new JButton("Play");
JButton pause = new JButton("Pause");
JButton stop = new JButton ("Stop");
JButton next = new JButton("Next");
JButton prev = new JButton("Previous");
controlPanel.add(play);
controlPanel.add(pause);
controlPanel.add(stop);
controlPanel.add(next);
controlPanel.add(prev);
// Currently playing
JLabel playing = new JLabel("Currently playing:");
controlPanel.add(playing);
JLabel current = new JLabel("Johnny Cash - Mean as Hell");
controlPanel.add(current);
this.getContentPane().add(controlPanel);
}
private void addSongTable()
{
JTable songTable = new JTable(Server.getSongTableModel());
songTable.setVisible(true);
JPanel tablePanel = new JPanel();
tablePanel.setVisible(true);
tablePanel.add(songTable);
songTable.repaint();
this.getContentPane().add(tablePanel);
JButton btnMulticastList = new JButton("send list to clients");
btnMulticastList.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Server.MulticastPlaylist();
}
});
getContentPane().add(btnMulticastList);
}
if I remove the controlPanel at the top, it sometimes shows and
sometimes not.
everything is hidden in Server.getSongTableModel(), nobody knows without posting an SSCCE with hardcoded value returns from
GUI has issue with Concurency in Swing
XxxModel loading data continiously with building GUi, then exception caused described problems
The code that I use inside my constructor of my JTable is provided in
the same application, so it's no network error
no idea what you talking about
have to create an empty GUI, see InitialTread
showing GUI, then to start loading data to JTable
then starting Workers Thread (Backgroung Task) from SwingWorker or (descr. Network issue) better Runnable#Thread (confortable for catching an exceptions and processing separate threads)
output from Runnable to the Swing GUI must be wrapped into invokeLater()
If you want controls at the top of your window, and the table filling the majority of the window, then I'd suggest you try using BorderLayout instead of FlowLayout. Create it like this...
private void addContentPanel()
{
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.setSize(new Dimension(800, 600));
this.setContentPane(p);
}
And add the components by specifying the location in the BorderLayout. In this case, the controls should be added to the top in their minimal size...
this.getContentPane().add(controlPanel,BorderLayout.NORTH);
And the table should be in the center, filling the remaining window space...
this.getContentPane().add(tablePanel,BorderLayout.CENTER);
In your case, you also have a button at the bottom...
getContentPane().add(btnMulticastList,BorderLayout.SOUTH);
For the layout you're after, BorderLayout is much more appropriate. The benefit of using BorderLayout here is that the components should be automatically resized to the size of the window, and you're explicitly stating where each component resides, so panels shouldn't not appear.
It would also be my recommendation that you find an alternative to calling getContentPane() in all your methods. Maybe consider keeping a global variable for the main panel, like this...
private mainPanel;
private void addContentPanel()
{
mainPanel = new JPanel(new BorderLayout());
mainPanel.setSize(new Dimension(800, 600));
this.setContentPane(mainPanel);
}
Then you can reference the panel directly when you want to add() components to it.
Finally, I'd also suggest using GridLayout for your controls, as it will allow you to place all your buttons in it, and they'll be the same size for consistency. Define it like this to allow 5 buttons in a horizontal alignment...
JPanel controlPanel = new JPanel(new GridLayout(5,1));
then you just add the buttons normally using controlPanel.add(button) and they'll be added to the next slot in the grid.
For more information, read about GridLayout or BorderLayout, or just see the Java Tutorial for a Visual Guide to Layout Managers to see what alternatives you have and the best one for your situation. In general, I try to avoid FlowLayout, as I find that there are other LayoutManagers that are more suitable in the majority of instances.

Having trouble re-sizing JButton in Java

Whenever I add my jbutton to my container it's really huge. I thought using the label.setBounds() function would work but it didn't
public Liability_Calculator(String s)
{
super(s);
setSize(325,200);
Color customColor = Color.WHITE;
c = getContentPane();
c.setLayout(new BorderLayout());
//the button
ok = new JButton("OK");
//ok.setSize(50, 50);
//HERE IS WHERE I TRY AND RESIZE!
ok.setBounds(30,30,50,50);
c.add(ok, BorderLayout.SOUTH);
setVisible(true);
}
Suggestions:
You will want to read up on the layout managers to
understand why your GUI is behaving this way
and to see how to use the layout managers to your advantage to create better looking GUI's in an easy way.
You'll also want to avoid setting bounds on any gui components.
For instance, a JPanel uses FlowLayout(FlowLayout.CENTER)) by default, and you can use that to your advantage by placing your ok JButton into a JPanel and then the JPanel into the contentPane:
ok = new JButton("OK");
// ok.setBounds(30, 30, 50, 50);
JPanel southPanel = new JPanel();
southPanel.add(ok);
c.add(southPanel, BorderLayout.SOUTH);
This will change the first image to the second:

Categories

Resources