I've researched the ways to change the size of a jbutton to be displayed on a JFrame.
I am trying both the button.setSize(200,200) and button.setPreferredSize(new Dimension(200,200)), but it does not change. Here's the code:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Index extends JFrame{
private String title = "This is the motherfucking title";
Dimension dim = new Dimension(500,500);
public Index(){
this.setResizable(false);
this.setTitle(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(dim);
this.getContentPane().setBackground(Color.BLACK);
JButton button = new JButton("Button");
button.setSize(200,200);
this.add(button);
}
public static void main(String args[]){
Index ih = new Index();
ih.setVisible(true);
}
}
Here's the result: http://i.imgur.com/Llj0pfo.png
What am I doing wrong?
try this:
JButton button = new JButton("Button");
button.setSize(200,200);
getContentPane().setLayout(null);
getContentPane().add(button);
setVisible(true);
inside your constructor.
this.add(button);
You are adding the button to the content pane of the frame. By default the content uses a BorderLayout and the component is added to the CENTER. Any component added to the CENTER will automatically get the extra space available in the frame. Since you set the size of the frame to (500, 500) there is lots of space available.
As a general rule you should NOT attempt to set the preferred size of a component, since only the component know how big it should be in order to paint itself properly. So your basic code should be:
JButton button = new JButton("...");
frame.add(button);
frame.pack();
frame.setVisible(true);
Now the button will be at its preferred size. However, the button will change size if you resize the frame. If you don't want this behaviour, then you need to use a different Layout Manager.
Use SwingUtilities.invokeLater(); create your Index() inside it, then call setVisible(true); at the end of constructor. At the same time remeber that by default JFrame uses BorderLayout.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Index();
}
});
Related
I added a button into JPanel and tried to change the size and the position of the button. I've tried different lines of codes but they wont work. Also putting in parent.setLayout(null); or panel.setLayout(null); will just completely remove the button and the background
Here is the code:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
public class app {
public static void main(final String[] args) {
final JFrame parent = new JFrame("CPS TEST");
JButton button = new JButton("Button");
JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(button);
panel.setBackground(Color.DARK_GRAY);
parent.add(panel, BorderLayout.CENTER);
parent.setSize(500, 300);
parent.setBackground(Color.CYAN);
parent.setLocationRelativeTo(null);
parent.setVisible(true);
parent.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Here are three ways to increase the size of a button:
Changing the position of a component is worthy of a separate question, but changing the size of a button is easy.
I want to construct a Swing component JTextField, here is my Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTextFieldGui{
JTextField textField;
JLabel labelInput;
JLabel labelOutput;
public static void main(String[] args) {
JTextFieldGui gui = new JTextFieldGui();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
JPanel panelInput = new JPanel();
JPanel panelOutput = new JPanel();
labelInput = new JLabel("Your first name: ");
labelOutput = new JLabel("Enter your name, and you will see it here.");
textField = new JTextField(20);
JButton enter = new JButton("Enter");
JButton selectAll = new JButton("Select all text");
frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelInput.setLayout(new BoxLayout(panelInput, BoxLayout.X_AXIS));
textField.addActionListener(new LabelActionListener());
enter.addActionListener(new LabelActionListener());
selectAll.addActionListener(new TextFieldActionlistener());
frame.getContentPane().add(BorderLayout.NORTH, panelInput);
panelInput.add(labelInput);
panelInput.add(textField);
panelInput.add(enter);
panelInput.add(selectAll);
frame.getContentPane().add(BorderLayout.CENTER, panelOutput);
panelOutput.add(labelOutput);
}
class LabelActionListener implements ActionListener{
public void actionPerformed(ActionEvent event){
labelOutput.setText(textField.getText());
}
}
class TextFieldActionlistener implements ActionListener{
public void actionPerformed(ActionEvent event){
textField.selectAll();
}
}
}
Question1: I define the width of the text field in 20 columns, but it always take up a row, like image:
Question2: how to use the selectAll() method, I use it in a listener of the button selectAll, but when I click the button, nothing happens, why
I define the width of the text field in 20 columns, but it always take up a row,
This is the rule of a BoxLayout. A component is resized to fill the space available. A JTextField doesn't have a maximum size so it grows. The buttons and label do have a maximum size so they don't grow.
Don't use a BoxLayout, just use a FlowLayout. It will automatically leave space between each component which is a better layout.
I use it in a listener of the button selectAll, but when I click the button, nothing happens, why
Focus is still on the button. The selected text only displays when the text field has focus.
So in he listener code you need to add:
textField.requestFocusInWindow();
The following code is old:
frame.getContentPane().add(BorderLayout.NORTH, panelInput);
you don't need to get the content pane. You can just add the component to the frame.
the constraint should be the second parameter
there are new constraints to make the names more meaningful
So the code should be:
frame.add(panelInput, BorderLayout.PAGE_START, panelInput);
See the section from the Swing tutorial on How to Use BorderLayout for more information.
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
public Test() {
super("A test");
setSize(360,300);//Size of JFrame
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);//Sets if its visible.
JButton num1 = new JButton("1");//Set the JButton name
JButton num2 = new JButton("2");
JButton num3 = new JButton("3");
num1.setBounds(80,70,50,50);
num2.setBounds(130,70,50,50);
num3.setBounds(180,70,50,50);
add(num1);
add(num2);
add(num3);
}
public static void main (String[] args) {
new Test().setVisible(true);
}
}
Here the num3 button is set as the background, I want the buttons to be aligned. This might be a trivial mistake I'm not sure as I've just started working with JFrame. Thank you.
The Problem
Basically, there are three parts that are causing this problems...
JFrame uses a BorderLayout by default. This means that only the last component add to any one of the five available layout positions will be managed
You call setVisible(true) before adding anything to the frame
You call setBounds on the buttons.
Because the components are generally painted in z-order (in FIFO order generally) and because of the optimisation in the code, the last button is been controlled by the BorderLayout of the frame, but the other two maintain the bounds you set before
Really interesting problem
Solution(s)
Use an appropriate layout manager, maybe a FlowLayout or GridBagLayout
Call setVisible last where ever possible
Check out Laying Out Components Within a Container for details
This is because of Layout Manager. Please check the code below.
i use another JPanel to put all the buttons. i set the panel as it will have 1 row and 3 columns objects.
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
JPanel buttonPanel;
public Test() {
super("A test");
setSize(360,300);//Size of JFrame
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);//Sets if its visible.
setLayout(null);
buttonPanel = new JPanel(new GridLayout(1, 3));
buttonPanel.setBounds(80, 70, 150, 50);
JButton num1 = new JButton("1");//Set the JButton name
JButton num2 = new JButton("2");
JButton num3 = new JButton("3");
buttonPanel.add(num1);
buttonPanel.add(num2);
buttonPanel.add(num3);
add(buttonPanel);
}
public static void main (String[] args) {
new Test().setVisible(true);
}
}
Well, never use raw placing and no Layout Manager.
This is your Bible
You can do that with some Layout tricks. For example this one:
First of all import the Layout classes.
import java.awt.GridLayout;
import java.awt.BorderLayout;
Make the frame a BorderLayout frame by copying this in the constructor of it.
setLayout(new BorderLayout());
Then make another JPanel and make it a GridLayout JPanel:
JPanel panel = new JPanel(new GridLayout(1,3));
panel.add(num1);
panel.add(num2);
panel.add(num3);
Arguments 1 and 3 mean "use exactly 1 row and 3 columns to place the widgets in this JPanel".
Finally add the last panel at the center of the frame:
add(panel,BorderLayout.CENTER);
This way you won't deal with dimensions or precise spots and still do what you want...
(to test it copy all the code in "Test" constructor)
I try to just use a add.method to add a button to a frame. But only the frame pops up.
I don't see any buttons.
import javax.swing.*;
public class okd {
public static void main() {
JFrame frame = new JFrame();
JButton b1 = new JButton();
frame.setSize(500,500);
frame.add(b1);
b1.setSize(400,400);
b1.setVisible(true);
frame.setVisible(true);
}
}
There is a button there. Add some text to it and it will magically appear.
public static void main(String[] args){
JFrame frame = new JFrame();
JButton b1 = new JButton();
frame.setSize(500,500);
b1.setSize(400,400);
b1.setVisible(true);
b1.setText("HelloWorld");
frame.add(b1);
frame.setVisible(true);
}//SSCCE1
Your button has been added to the frame. You'll notice a difference if you remove your frame.add() line. The 'problem' lies with the following.
You haven't specified a layout resulting in your frame using the
default BorderLayout manager.
You haven't specified a constraint in frame.add(). Because of this the
component has been added to whatever the default position is for the
layout which is BorderLayout.CENTER. Components added to the center
take up the much space as possible hence why your button is filling the entire frame.
Here's some tutorials on layout managers. You might want to have a read through these at some point.
To remove the Large appearance of the button, You need to add a layout Manager to the Code
Like this:
import javax.swing.*;
import java.awt.*;
public static void main(String[] args)
{
JFrame frame = new JFrame();
JButton b1 = new JButton();
frame.setSize(500,500);
b1.setVisible(true);
b1.setText("HelloWorld");
frame.setLayout(new FlowLayout());
frame.add(b1);
frame.setVisible(true);
}
I have this code
package com.net.Forms;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainForm {
protected static JFrame window = new JFrame("Test Form");
protected static JButton btnOK = new JButton("OK!");
public static void Main() {
load();
return;
}
public static void load() {
window.setSize(500, 500);
window.setVisible(true);
//btnOK.setSize(50, 50); //here
window.add(btnOK);
btnOK.setEnabled(true);
btnOK.setVisible(true);
}
}
Why is the button still filling the frame instead of being 50 X 50 like i stated above
Any help would be appreciated
The default Layout for JFrame is BorderLayout. That's why when you are adding a JButton to it , It is adding the JButton to the center and expanding it to cover entire window. BorderLayout doesn't respect the setSize(..) method of components being added to them. If you still want to give a preferred size to the component being added to JFrame you should change the layout to be FlowLayout or GridLayout or others.. and then use setPreferredSize(..) method with the component while adding it to the JFrame. For example Your code could be modified in following way.
import java.awt.*;
import javax.swing.*;
public class MainForm {
protected JFrame window = new JFrame("Test Form");
protected JButton btnOK = new JButton("OK!");
public static void main(String st[]) {
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
MainForm mf = new MainForm();
mf.load();
}
});
}
public void load() {
Container c = window.getContentPane();
c.setLayout(new FlowLayout());//Set layout to be FlowLayout explicitly.
btnOK.setPreferredSize(new Dimension(100,50));//use set PreferredSize
c.add(btnOK);
c.setSize(500, 500);
c.setVisible(true);
}
}
Its just a bug or sth.
the last element added to frame Takes Whole of it.
all you need to do :
declare a new simple component like JLabel()
add it to frame.
Dont set Bounds Or Size For it.just a new Label.
MAKE SURE that this label is the last element added to frame.
Hope it Works.