Here is my code. The button is the same size as the FlowLayout. How can I make the button smaller?
public class javalearning extends JFrame{{
FlowLayout f = new FlowLayout();
this.setSize(600,600);
JFrame j = new JFrame();
this.setTitle("this is a tittle");
JButton button = new JButton();
button.setText("Button");
this.add(button);
button.setBounds(10, 10, 10, 10);
this.setVisible(true);
}
}
I think you forget to setLayout, it works fine when I do. Don't use setBounds and put it in a javalearning constructor and I also suggest you setDefaultCloseOperation like
public javalearning() {
FlowLayout f = new FlowLayout();
this.setLayout(f);
this.setSize(600, 600);
this.setTitle("this is a tittle");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton();
button.setText("Button");
this.add(button);
// button.setBounds(10, 10, 10, 10);
this.setVisible(true);
}
public static void main(String[] args) {
javalearning m = new javalearning();
}
Finally, by convention, Java class names start with a capital letter and are camel case. Something like JavaLearning would follow that convention.
You never set the layout manager (FlowLayout) to the frame, therefore the JFrame is still using it's default layout manager of BorderLayout...
Try using something more like...
FlowLayout f = new FlowLayout();
setLayout(f);
this.setTitle("this is a tittle");
JButton button = new JButton();
button.setText("Button");
this.add(button);
this.pack();
this.setVisible(true);
instead...
Take a closer look at Laying Out Components Within a Container for more details
FlowLayout will lay out Components left-to-right (or right-to-left) wrapping them if required. If you wish to explicitly set the size of each JButton you should use setPreferredSize rather than setSize or setBounds as layout managers typically make use of the minimum, preferred and maximum sizes when performing a layout.
button.setBounds(x, y, height, width);
you can give height and width less than 10!
also you can use GridLayout for smaller buttons in one button with for loop
Related
So, I have a tiny GUI program and I decided to use the BoxLayout to display the components from top to bottom. Everything works fine but I'm not able to change the height of my JButtons. I tried many things like setPreferredSize() but then i had the problem that the width isn't correct, as well. Using setMaximumSize() sets the width like i want to but the height still doensn't change. Maybe some of you could help me :) Thanks
public class SimpleSkinViewer extends JPanel implements ActionListener{
private final Dimension boxDimension = new Dimension(320, 320);
private final Dimension buttonDimension = new Dimension(320, 60);
private final Dimension spaceDimension = new Dimension(0, 5);
private JLabel imagebox;
private JButton loadButton;
private JButton changeButton;
private JButton downloadButton;
public SimpleSkinViewer() {
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
imagebox = new JLabel("");
imagebox.setIcon(new ImageIcon(loadImage("http://skins.minecraft.net/MinecraftSkins/AvarionDE.png")));
loadButton = new JButton("Load Skin");
changeButton = new JButton("Change Skin");
downloadButton = new JButton("Download");
//add listeners
loadButton.addActionListener(this);
changeButton.addActionListener(this);
downloadButton.addActionListener(this);
//dimensions
imagebox.setMaximumSize(boxDimension);
loadButton.setMaximumSize(buttonDimension);
changeButton.setMaximumSize(buttonDimension);
downloadButton.setMaximumSize(buttonDimension);
add(imagebox);
add(Box.createRigidArea(spaceDimension));
add(loadButton);
add(Box.createRigidArea(spaceDimension));
add(changeButton);
add(Box.createRigidArea(spaceDimension));
add(downloadButton);
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
//and other stuff.....
public static void main (String[] args) {
JFrame frame = new JFrame("Avarion's Simple Skin Viewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new SimpleSkinViewer());
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
You need Box.createVerticalGlue()
Change
add(changeButton);
add(Box.createRigidArea(spaceDimension));
with
add(changeButton);
add(Box.createVerticalGlue());
Then you can use .setPreferredSize(new Dimension(x,y)); and buttons will adapt to your layout
From the docs for BoxLayout
When a BoxLayout lays out components from top to bottom, it tries to
size each component at the component's preferred height.
For a top-to-bottom box layout, the preferred width of the container
is that of the maximum preferred width of the children. If the
container is forced to be wider than that, BoxLayout attempts to size
the width of each component to that of the container's width (minus
insets). If the maximum size of a component is smaller than the width
of the container, then X alignment comes into play.
So, you can set both the maximumSize and preferredSize to get the desired size.
loadButton.setMaximumSize(buttonDimension);
loadButton.setPreferredSize(buttonDimension);
I am developing a GUI form in java. In that I am adding two panels in main frame which has FlowLayout. But now I want to change the size of panels and I tried changing using setsize(), and I can see no difference.
Here is my code:
public class Main_window extends JFrame implements ActionListener {
JFrame MainFrm = new JFrame("MCQ Generator");
JPanel LeftPanel = new JPanel();
JPanel RightPanel = new JPanel();
JButton BrowseButton = new JButton("Browse/Open");
TextArea ta1 = new TextArea();
TextArea ta2 = new TextArea();
JButton ClearWindow = new JButton("Clear Window");
JButton generateButton = new JButton("Generate MCQs");
String fname;
Main_window() {
MainFrm.setLayout(new FlowLayout(FlowLayout.LEFT));
MainFrm.setSize(1050, 400);
MainFrm.add(LeftPanel, FlowLayout.LEFT);
MainFrm.add(RightPanel);
LeftPanel.setLayout(new BorderLayout(30, 30));
//LeftPanel.setSize(10, 10);
//RightPanel.setSize(10, 10);
RightPanel.setLayout(new BorderLayout(40, 40));
LeftPanel.setOpaque(true);
LeftPanel.setBackground(Color.LIGHT_GRAY);
LeftPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
RightPanel.setOpaque(true);
RightPanel.setBackground(Color.LIGHT_GRAY);
RightPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JPanel InnerPanel = new JPanel();
InnerPanel.setLayout(new FlowLayout());
InnerPanel.setBackground(Color.LIGHT_GRAY);
InnerPanel.add(new JLabel("Choose File: "));
LeftPanel.add(InnerPanel, BorderLayout.NORTH);
LeftPanel.add(ta1, BorderLayout.CENTER);
RightPanel.add(new JLabel("Questions Generated:"), BorderLayout.NORTH);
RightPanel.add(ta2, BorderLayout.CENTER);
//ta1.setSize(10, 100);
//ta2.setSize(10, 100);
BrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Text Documents(*.txt)", "txt");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(LeftPanel);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You choose to open this file: " + chooser.getCurrentDirectory() + "\\" + chooser.getSelectedFile().getName());
fname = new String(chooser.getCurrentDirectory() + "\\" + chooser.getSelectedFile().getName());
try {
Jdbc_conn.truncateInputTable(ta1);
displayInput(fname);
//Jdbc_conn.truncateInputTable(ta1);
Give_input.getInput(fname);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
InnerPanel.add(BrowseButton);
LeftPanel.add(generateButton, BorderLayout.SOUTH);
generateButton.addActionListener(this);
RightPanel.add(ClearWindow, BorderLayout.SOUTH);
ClearWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
Jdbc_conn.truncateMcqAndNew_nountab(ta2);
} catch (Exception e) {
e.printStackTrace();
}
}
});
MainFrm.setVisible(true);
MainFrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Usually, when setSize() doesn't work, try with setPreferredSize().
In this case, as the Oracle tutorial says: "The FlowLayout class puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, the FlowLayout class uses multiple rows. If the container is wider than necessary for a row of components, the row is, by default, centered horizontally within the container. To specify that the row is to aligned either to the left or right, use a FlowLayout constructor that takes an alignment argument. Another constructor of the FlowLayout class specifies how much vertical or horizontal padding is put around the components."
First, take a look at Laying Out Components Within a Container for information about the layout API.
You should never (okay, very rarely) need to call setSize on a component directly. Any component under the management of a layout manager will be sized to meet the requirements of the layout manager, so generally speaking, call setSize is a pointless exercise
You might be able effect the size of a component by using an EmptyBorder, but this is just adding internal padding to the component, which might not be desirable.
Another choice is to use a different layout manager which gives you more control, something like MigLayout or GridBagLayout, but this will increase the general complexity of the code.
The other choice would be to override the getPreferredSize method of the components you want to size and return the values you want to use. Be warned though, this is not to be done lightly or without a lot of consideration to "why" you want to change the default size. The main reason is, different platforms can change the amount of space any component might need in order to be laid out correctly.
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.
I'm trying to place a series of JLabels at specific X and Y coordinates on a JPanel (and set its height and width, too). No matter what I do, each label winds up immediately to the right of the previous label and has the exact same size as all of the others.
Right now, my Jpanel is in a Grid Layout. I've tried Absolute Layout (illegal argument exception results), Free Design (no labels appear), Flow Layout (everything just gets squeezed to the center), and a few others.
Not sure what I need to do to make this work. Can anyone help? Thanks!
JLabel lbl1 = new JLabel("label 1");
JLabel lbl2 = new JLabel("label 2");
JLabel lbl3 = new JLabel("label 3");
JLabel lbl4 = new JLabel("label 4");
JLabel lbl5 = new JLabel("label 5");
myPanel.add(lbl1);
myPanel.add(lbl2);
myPanel.add(lbl3);
myPanel.add(lbl4);
myPanel.add(lbl5);
lbl1.setLocation(27, 20);
lbl2.setLocation(123, 20);
lbl3.setLocation(273, 20);
lbl4.setLocation(363, 20);
lbl5.setLocation(453, 20);
lbl1.setSize(86, 14);
lbl2.setSize(140, 14);
lbl3.setSize(80, 14);
lbl4.setSize(80, 14);
lbl5.setSize(130, 14);
You have to set your container's Layout to null:
myPanel.setLayout(null);
However is a good advise also to take a look at the Matisse Layout Manager, I guess it is called GroupLayout now. The main problem with absolute positioning is what happens when the window changes its size.
Set the container's layout manager to null by calling setLayout(null).
Call the Component class's setbounds method for each of the container's children.
Call the Component class's repaint method.
Note:
Creating containers with absolutely positioned containers can cause problems if the window containing the container is resized.
Refer this link:
http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
Layout managers are used to automatically determine the layout of components in a container. If you want to put components at specific coordinate locations, then you should not use a layout manager at all.
myPanel = new JPanel(null);
or
myPanel.setLayout(null);
My advise is to use an IDE like NetBeans with its GUI editor. To inspect the code and because there are many ways:
Setting the layout manager, or for absolute positioning doing a myPanel.setLayout(null), has several influences.
In general, assuming you do your calls in the constructor of a JFrame, you can call pack() to start the layouting.
Then, every layout manager uses its own implementation of add(Component) or add(Component, Constraint). BorderLayout's usage is with add(label, BorderLayout.CENTER) and so on.
// Best solution!!
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = (JPanel) frame.getContentPane();
panel.setLayout(null);
JLabel label = new JLabel("aaa");
panel.add(label);
Dimension size = label.getPreferredSize();
label.setBounds(100, 100, size.width, size.height);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
You can use your own method that calling by setSize, setLocation values for directly....! `
As well i show you how to use JProgress Bar
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class installComp{
void install(Component comp, int w, int h, int x, int y){
comp.setSize(w,h);
comp.setLocation(x,y);
}
}
class MyFrame extends JFrame{
int cur_val = 0;
JButton btn = new JButton("Mouse Over");
JProgressBar progress = new JProgressBar(0,100);
MyFrame (){
installComp comp=new installComp();
comp.install(btn,150,30,175,20);
comp.install(progress,400,20,50,70);
btn.addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent evt){
cur_val+=2;
progress.setValue(cur_val);
progress.setStringPainted(true);
progress.setString(null);
}
});
add(btn);
add(progress);
setLayout(null);
setSize(500,150);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setVisible(true);
}
}
class Demo{
public static void main(String args[]){
MyFrame f1=new MyFrame();
}
}
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: