JButton doesnt show text; fills JFrame - java

I am trying to make a JFrame with a button in it, but my button doesnt have my wanted text! I'm setting it in the button constructor AND afterwards with setText, but it still doesnt show up! Also, the button fills the whole frame, is there a way to make it not stick to the edges of the JFrame?
import javax.swing.*;
public class main
{
public static void main(String[] args)
{
JFrame mainWindow = new JFrame("8 Game");
mainWindow.setSize(200, 200);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setSize(30, 30);
eightButton.setBounds(5, 5, 25, 25);
eightButton.setContentAreaFilled(false);
eightButton.setAction(new buttonAction());
mainWindow.add(eightButton);
mainWindow.setVisible(true);
}
}

Why does it work for me and not you? (with the FlowLayout suggested by others
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class main
{
public static void main(String[] args)
{
JFrame mainWindow = new JFrame("8 Game");
mainWindow.setLayout(new FlowLayout(FlowLayout.CENTER));
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(200, 200);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setSize(30, 30);
eightButton.setBounds(5, 5, 25, 25);
//eightButton.setAction(new buttonAction());
//eightButton.setContentAreaFilled(false);
mainWindow.add(eightButton);
mainWindow.setVisible(true);
}
}
EDIT
an Action needs a title. If you don't specify one, the button will have no title. If you did this
eightButton.setAction(new buttonAction(), "8");
it would work.

Use a layout manager that respects the component's preferred size
mainWindow.setLayout(new FlowLayout(FlowLayout.CENTER));

Swing components expect a layout manager context when they are added to a window.
The default layout is BorderLayout, which is why you're getting that odd behavior. With only a single element, BorderLayout fills the pane with that element.
Try something like FlowLayout or AbsoluteLayout (or null)
http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html

Use another LayoutManager default frame's layout manager is BorderLayout that if you add a component without specification will add to the center. You can use FlowLayout. See example with SwingUtilities.invokeLater you ensure that will run in EDT.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame mainWindow = new JFrame("8 Game");
mainWindow .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setLayout(new FlowLayout());
mainWindow.setLocationRelativeTo(null);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setContentAreaFilled(false);
eightButton.setAction(new buttonAction());
mainWindow.add(eightButton);
mainWindow.pack();
mainWindow.setVisible(true);
}
});
}
Take a look of more complete correct examples in official tutorials How to use Buttons

Related

How do I create a new JFrame?

I'm a complete beginner to Java, and I'm finding some answers a bit too technical for me (even the most basic tutorials seem to give me syntax errors when I run the code). How, in really simple terms do I add a JButton to a JFrame? I've got as far as:
import javax.swing.JButton;
import javax.swing.JFrame;
public class JF {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
/*some pretty basic code to initialize the JFrame i.e.
myFrame.setSize(300, 200);
This is as far as I got
*/
}
}
I would seriously appreciate some help!
Creating a new JFrame
The way to create a new instance of a JFrame is pretty simple.
All you have to do is:
JFrame myFrame = new JFrame("Frame Title");
But now the Window is hidden, to see the Window you must use the setVisible(boolean flag) method. Like this:
myFrame.setVisible(true);
Adding Components
There are many ways to add a Component to a JFrame.
The simplest way is:
myFrame.getContentPane().add(new JButton());//in this case we are adding a Button
This will just add a new Component that will fill the JFrame().
If you do not want the Component to fill the screen then you should either make the ContentPane of the JFrame a new custom Container
myFrame.getContentPane() = new JPanel();
OR add a custom Container to the ContentPane and add everything else there.
JPanel mainPanel = new JPanel();
myFrame.getContentPane().add(mainPanel);
If you do not want to write the myFrame.getContentPane() every time then you could just keep an instance of the ContentPane.
JPanel pane = myFrame.getContentPane();
Basic Properties
The most basic properties of the JFrame are:
Size
Location
CloseOperation
You can either set the Size by using:
myFrame.setSize(new Dimension(300, 200));//in pixels
Or packing the JFrame after adding all the components (Better practice).
myFrame.pack();
You can set the Location by using:
myFrame.setLocation(new Point(100, 100));// starting from top left corner
Finally you can set the CloseOperation (what happens when X is pressed) by
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
There are 4 different actions that you can choose from:
DO_NOTHING_ON_CLOSE //Nothing happens
HIDE_ON_CLOSE //setVisible(false)
DISPOSE_ON_CLOSE //Closes JFrame, Application still runs
EXIT_ON_CLOSE //Closes Application
Using Event Dispatch Thread
You should initialize all GUI in Event Dispatch Thread, you can do this by simply doing:
class GUI implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new GUI());
}
#Override
public void run() {
JFrame myFrame = new JFrame("Frame Title");
myFrame.setLocation(new Point(100, 100));
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
myFrame.getContentPane().add(mainPanel);
mainPanel.add(new JButton("Button Text"), BorderLayout.CENTER);
myFrame.pack();
myFrame.setLocationByPlatform(true);
myFrame.setVisible(true);
}
}
//I hope this will help
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
public class JF extends JFrame
{
private JButton myButton;//Here you begin by declaring the button
public JF()//Here you create you constructor. Constructors are used for initializing variable
{
myButton = new JButton();//We initialize our variable
myButton.setText("My Button"); //And give it a name
JPanel panel1 = new JPanel();//In java panels are useful for holding content
panel1.add(myButton);//Here you put your button in the panel
add(panel1);//This make the panel visible together with its contents
setSize(300,400);//Set the size of your window
setVisible(true);//Make your window visible
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
JFrame frame = new JF();
frame.setTitle("My First Button");
frame.setLocation(400,200);
}
}

JTextField in swing out of bounds

I was trying to create form using swing, but the created input field is out of bounds.
My code
package lista_designer_1;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class lista_designer_2 extends JFrame {
JTextField text1;
public static void main(String[] args) {
lista_designer_2 frame1 = new lista_designer_2();
frame1.setSize(450, 300);
frame1.setVisible(true);
}
public lista_designer_2() {
super("Hello World");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text1 = new JTextField();
text1.setBounds(10, 10, 76, 21);
add(text1);
setVisible(true);
}
}
After running this code it looks like this:
How can i fix it?
You can use layout managment see A Visual Guide to Layout Managers
For examples see Swing Layout Examples.
Example to use FlowLayout layout:
getContentPane().setLayout(new FlowLayout ());
Try setLayout(null); This will remove the LayoutManager from your JFrame which causes the textfield to appear linke this.

JFrame Button Logic error

I've been spending some time relearning java and a peculiar logic error hit me here.
import javax.swing.*;
import java.awt.*;
class Frame
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
Container content = frame.getContentPane();
content.setBackground(Color.blue);
content.add(btn1);
content.add(btn2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//end main
}
I've created 2 JButton objects, and they should be the same size, with different location and text. This of course is not the case, the "FOO" button is exactly where and how I want it to be, but the "BAR" button is the size of the entire frame.
Help!
1) You are attempting to use Absolute LayoutManager via setSize and setLocation etc, but without calling setLayout(null) on the component you are adding the JButtons to. However this is not a best practice in Swing.
When adding to JFrame contentpane default layout is BorderLayout which adds components to is default position of BorderLayout.CENTER.
Have a read on A Visual Guide to Layout Managers
2) Also when using a correct LayoutManager you would omit JFrame#setSize(..) call and replace it with JFrame#pack() before setting the JFrame visible.
3) Also have a read on Concurrency in Swing specifically on The Event Dispatch Thread
which dictates all swing components be created on EDT via SwingUtillities.invokeXXX(..) block:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//create and manipulate swing components here
}
});
4) Also rather use JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); as this will allow any other threads timers etc to carry on execution even after JFrame has been disposed.
add:
frame.getContentPane().setLayout(null);
To your code after the line:
frame.setSize(400, 500);
Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).In your code the buttons are stacked over the other.That is why you get this Error(as you think it is).
This will solve your problem:-
import javax.swing.*;
import java.awt.*;
class OP3
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
JPanel p = new JPanel(new FlowLayout());
p.add(btn1);
p.add(btn2);
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//end main
}
Just add a panel to the frame and add the buttons to the panel.
import javax.swing.*;
import java.awt.*;
class source
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JPanel panel=new JPanel();//panel added here
panel.setSize(frame.size());
panel.setLocation(0, 0);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
panel.add(btn1);
panel.add(btn2);
Container content = frame.getContentPane();
content.setBackground(Color.blue);
content.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//endmain

Java Swing Button

I've written this:
JButton saveButton = new JButton(saveAction);
How do I then call it so that it displays within the window? (I've already got the code for the window, I just don't know how to call it so it shows)
saveButton.setVisible(true);
your_window.add(saveButton);
Thats all.
Firstly you should create some ContentPane for window (I guess you mean JFrame). Adding a button directly to window is not a good idea :P Next you can add your button to that pane:
panel.addComponent(button);
The last thing to do is:
frame.setContentPane(panel)
And that's all :P Just in a nutshell ;)
Use something like this
public class MainWindow extends JFrame {
public static void main(String[] args) {
MainWindow frame = new MainWindow();
frame.setVisible(true);
}
public MainWindow() throws IOException {
setTitle("Conveyor");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 851, 515);
contentPane = new JPanel();
JButton refreshButton = new JButton("refresh");
contentPane.add(refreshButton, BorderLayout.EAST);
}
}

How to add components to JDialog

d1=new JDialog();
d1.setSize(200, 100);
t1=new JTextField();
t1.setBounds(10,10,40,20);
d1.add(t1);
I want to add components in JDialog such as TextField, Button...
1) first create a Jpanel
JPanel pan=new JPanel();
pan.setLayout(new FlowLayout());
2) add the components to that JPanel
pan.add(new JLabel("label"));
pan.add(new JButton("button"));
3) create JDialog
JDialog jd=new JDialog();
4) add the JPanel to JDialog
jd.add(pan);
You have to make sure you use no layout manager.
d1.setLayout(null);
By default, a BorderLayout is used. It is great to use layout manager, but the real good ones, that make your windows resizable etc, are hard to understand. Without layout manager, you can specify the bounds as you tried.
You can add components to a JDialog just the way you add to a JFrame since JDialog is a java.awt.Container . You should use a a layout manager or set the layout to null if you want to set the sizes of the components you are adding.
I am not sure of how you really want your components to be laid out but the following snippet should achieve what I am guessing you are trying to do with your current code. Try to work as much as possible with LayoutManager's, Layout constraints, preferred/maximum/minimum sizes and avoid using setLocation/setSize/setBounds.
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test5 {
protected static void initUI() {
JDialog dialog = new JDialog();
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 0));
JTextField textfield = new JTextField(8);
textfield.setBounds(10, 10, 40, 20);
panel.add(textfield);
dialog.add(panel);
dialog.setSize(200, 100);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initUI();
}
});
}
}
You should probably read about LayoutManager's. Take the time to go through it, understand how they work and the different ones that exists. You won't regret spending a few minutes on that.

Categories

Resources