How do I center an object in java - java

I want to make a simple program that will have one button and multiple fields. When I was planning this out in my head I wanted to use a gridlayout, or at least cent the button at first since I am learning. Here is what I have so far, my question that I am leading to is where do I put in my grid layout, or do I set the alignment center in the panel, frame or button?
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Normal {
public static void main(String[] args) {
JFrame frame = new JFrame("test");
JButton button = new JButton("why");
JPanel panel = new JPanel();
JTextField field= new JTextField();
//button
button.setSize(50, 50);
//Field
field.setSize(250, 25);
//Frame
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(panel);
frame.add(field);
frame.add(button);
}
}

Always add the components in a Container of the JFrame. Set the Layout of Container as GridLayout. For example You can change your code as follows:
import java.awt.GridLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Normal {
public static void main(String[] args) {
JFrame frame = new JFrame("test");
JButton button = new JButton("why");
JPanel panel = new JPanel();
JTextField field= new JTextField();
Container c = frame.getContentPane();
c.setLayout(new GridLayout(3,1));//Devides the container in 3 rows and 1 column
c.add(panel);//Add in first row
c.add(button);//Add in second row
c.add(field);//Add in third row
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

In an approach where you extend your class from JFrame, you could simply set where you would like to add the components. If you have a panel with ex. a button, you could add it like this:
add(panel, BorderLayout.CENTER);
Hope this helps.

Related

Huge space between my JSlider and text underneath

I'm currently working on a media player for java, and with the power of VLCJ I was working on implementing an equalizer adjust window. There will be 11 vertical sliders with a JLabel underneath them indicating the hZ band and the dB level of the band. However, the slider keeps adding a huge gap between itself and the JLabel. I tried stacking just two JLabels on top of each other and there's barely a gap at all. My code is below. (The return equalizer stuff hasn't been implemented yet. I just want a basic UI working before I start adding in the functionality)
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import uk.co.caprica.vlcj.player.Equalizer;
public class VideoEQFrame {
public VideoEQFrame() {
//constructor
}
public Equalizer show() {
JFrame frame = new JFrame("Effects");
JPanel panel = new JPanel();
JPanel sliders= new JPanel();
JPanel gainObjects = new JPanel(new GridLayout(2, 0, 2, 0));
JSlider gainS = new JSlider(JSlider.VERTICAL, -12, 12, 0);
gainS.setMajorTickSpacing(2);
gainS.setPaintTicks(true);
gainS.setToolTipText("Adjust the gain");
JLabel gainL = new JLabel("Text");
gainObjects.add(gainS);
gainObjects.add(gainL);
sliders.add(gainObjects);
panel.add(sliders);
frame.add(panel);
frame.setSize(new Dimension(600, 300));
//frame.setResizable(false);
frame.setVisible(true);
Equalizer eq = new Equalizer(0);
return eq;
}
}
You are using GridLayout to lay the slider and the text label. That means that they will both occupy the same height. So because the slider has bigger height, the height of the label also adjusts to this height. Try using another LayoutManager like BorderLayout, like so:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
public class VideoEQFrame {
public VideoEQFrame() {
//constructor
}
public void show() {
JFrame frame = new JFrame("Effects");
JPanel panel = new JPanel();
JPanel sliders= new JPanel();
JPanel gainObjects = new JPanel(new BorderLayout());
JSlider gainS = new JSlider(JSlider.VERTICAL, -12, 12, 0);
gainS.setMajorTickSpacing(2);
gainS.setPaintTicks(true);
gainS.setToolTipText("Adjust the gain");
JLabel gainL = new JLabel("Text");
gainObjects.add(gainS, BorderLayout.CENTER);
gainObjects.add(gainL, BorderLayout.PAGE_END);
sliders.add(gainObjects);
panel.add(sliders);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
//frame.setResizable(false);
frame.setVisible(true);
// Equalizer eq = new Equalizer(0);
// return eq;
}
public static void main(final String[] args) {
new VideoEQFrame().show();
}
}

Trying to add a scrollbar to a JPanel with GridLayout, but the JCheckBoxes just get made smaller instead

So I'm trying to set up a Gui in Java which holds a list of checkboxes. What determines the length of the list is the highlighted checkboxes. However, when I add more things to the list the checkboxes just get smaller to fit the panel. I've added a vertical scrollbar, but this just doesn't do anything. Is there something I have to do to stop the GridLayout from resizing what it holds or is it the wrong layout?
package darrt;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestForScrollBat {
public static void main(String[] args){
new TestForScrollBat();
}
public TestForScrollBat(){
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(0, 1));
JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(50, 30, 300, 50);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JLabel label = new JLabel(" Soc Categories");
JCheckBox soc1 = new JCheckBox("Blood and Lymphatic System Disorder");
JCheckBox soc2 = new JCheckBox("Cardiac Disorders");
JCheckBox soc3 = new JCheckBox("Congenital, familial and Genetic Disorders");
JButton jbtn = new JButton("Go!");
panel.add(label);
panel.add(soc1);
panel.add(soc2);
panel.add(soc3);
panel.add(jbtn);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
I had it before so that it would add a scroll to this panel, but now it doesn't even do that.. It just creates a new JPanel on the JFrame
Your problem is about the following lines in your code:
scrollPane.setBounds(50, 30, 300, 50);
You should not set static sizes and locations when using layouts. You are telling a specific size and location to the scrollPane while you had add it to the center of the contentPane before. These two are in conflict.
And next problem is about this line:
frame.add(panel);
This line will detach the panel from you JScrollPane and add it directly to the contentPane of the JFrame.
By deleting/commenting these lines, your problem will be solved.

Use a layout in place of a component

I'd like to create a main window frame with a BorderLayout that contains other layouts as its components.
How can I add, say, a FlowLayout to my BorderLayout's NORTH position?
Here's a little program that shows you:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class LayoutExample {
public static void main (String[] args) {
JFrame frame = new JFrame("Frame with BorderLayout");
frame.setLayout(new BorderLayout());
JPanel flow = new JPanel();
JLabel label = new JLabel("This is a flowlayout.");
flow.setBorder(new LineBorder(Color.BLACK));
flow.setLayout(new FlowLayout());
flow.add(label);
frame.add(flow, BorderLayout.NORTH);
frame.setSize(300,300);
frame.setVisible(true);
}
}
That's how it looks like at the end:

Dynamically add fixed-height panels to a JScrollPane

JPanel panel = new JPanel(new GridLayout(0,1));
JScrollPane contentpane = new JScrollPane(panel);
JButton add = new JButton("ADD");
add.actionListener(new ActionListener() {
public void actionPerformed(){
MyPanel newpanel = new MyPanel("title","Button"); //MyPanel is a class which extends JPanel and contains constructor MyPanel(String TitleToSet ,String ButtonTitleTOAdd)
panel.add(newpanel);
panel.repaint();
}) ;
I have used this code thinking that it will add the MyPanel to the grid layout dynamically and "panel" would be scrollable if more "MyPanel"s are added. However, this was not the case, 1st "MyPanel" filled whole "panel" and on adding second "MyPanel" (by clicking button "Add"), the 1st "MyPanel" was shrinked to make space for second one to be added.. and on adding more, all the "MyPanel"s were fit in the viewport instead of making the "panel" scrollable.. How to add those "MyPanel"s dynamically and making the "panel" scrollable on adding more of those?? Any help would be appreciated.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html :
By default JScrollPane uses ScrollPaneLayout to handle the layout of
its child Components. ScrollPaneLayout determines the size to make the
viewport view in one of two ways:
[...]
getPreferredSize is used.
You should add the line
panel.setPreferredSize(new Dimension(0, panel.getComponents().size() * SUB_PANEL_HEIGHT));
to your ActionListener.
Full example:
package main;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;
class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(400, 400));
frame.setSize(400, 400);
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("BOO"));
panel.add(new JButton("BBBB"));
JScrollPane contentpane = new JScrollPane(panel);
frame.add(contentpane);
new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel newpanel = new JPanel();
newpanel.add(new JLabel("LOL"));
panel.add(newpanel);
System.out.println(100 * panel.getComponents().length);
panel.setPreferredSize(new Dimension(0, 100 * panel.getComponents().length));
contentpane.validate();
}
}).start();
frame.setVisible(true);
}
}

JTextArea Won't Update Unless I Resize JFrame

Whenever I run my program my JTextArea does not follow the dimension that I have given it, but if I resize my JFrame it updates and sets its size to what I put.
What is the issue?
public ControlPanel() {
// create our list of players
list = new JList(model);
// create our scroll panes
userspane = new JScrollPane(list);
consolepane = new JScrollPane(console);
// set sizes
userspane.setSize(100, 500);
jta.setSize(100, 500);
list.setSize(100, 500);
consolepane.setSize(100, 500);
console.setSize(100, 500);
// add to panel
panel.add(userspane, BorderLayout.CENTER);
panel.add(kick);
panel.add(ban);
panel.add(info);
panel.add(consolepane, BorderLayout.CENTER);
// set frame properties
setTitle("RuneShadows CP");
setSize(280, 400);
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(panel);
setVisible(true);
}
Don't set the sizes to anything.
For JTextArea you can use the constructor JTextArea(int rows, int charSpaces)
Just pack() the JFrame and it will respect all the preferred sizes of the components inside.
Also instead of setting the content pane to the panel, just add the panel. That will respect the preffered size of the panel when pack() is called
I'm not exactly sure what variable was what (or the sizes you wanted the), so I assumed text areas, and others as well. See this example where I just used the JTextArea constructor I mentioned and just packed.
EDITED with no sizes set
import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ControlPanel extends JFrame {
JScrollPane userspane;
JList list;
DefaultListModel model = new DefaultListModel();
JScrollPane consolepane;
JTextArea console = new JTextArea(20, 50);
JTextArea jta = new JTextArea(6, 50);
JPanel panel = new JPanel();
JButton kick = new JButton("Kick");
JButton ban = new JButton("Ban");
JButton info = new JButton("Info");
public ControlPanel() {
// create our list of players
list = new JList(model);
// create our scroll panes
userspane = new JScrollPane(list);
consolepane = new JScrollPane(console);
// add to panel
panel.add(userspane, BorderLayout.CENTER);
panel.add(kick);
panel.add(ban);
panel.add(info);
panel.add(consolepane, BorderLayout.CENTER);
add(panel);
pack();
setTitle("RuneShadows CP");
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new ControlPanel();
}
});
}
}
UPDATE - with positioning
Keep in mind also, with BorderLayout you need to specify a position for every component you add or else it will default to CENTER and each position an only have one component. I noticed you trying to add two components to the CENTER
import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ControlPanel extends JFrame {
JScrollPane userspane;
JList list;
DefaultListModel model = new DefaultListModel();
JScrollPane consolepane;
JTextArea console = new JTextArea(20, 50);
JTextArea jta = new JTextArea(6, 50);
JPanel panel = new JPanel(new BorderLayout());
JButton kick = new JButton("Kick");
JButton ban = new JButton("Ban");
JButton info = new JButton("Info");
public ControlPanel() {
// create our list of players
list = new JList(model);
// create our scroll panes
userspane = new JScrollPane(list);
consolepane = new JScrollPane(console);
// add to panel
panel.add(userspane, BorderLayout.SOUTH);
JPanel buttonPanel = new JPanel();
buttonPanel.add(kick);
buttonPanel.add(ban);
buttonPanel.add(info);
panel.add(buttonPanel, BorderLayout.CENTER);
panel.add(consolepane, BorderLayout.NORTH);
add(panel);
pack();
setTitle("RuneShadows CP");
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new ControlPanel();
}
});
}
}

Categories

Resources