#JButton Sizing Not Working
8 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @ornate thistle! Please use
/closeor theClose Postbutton above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
//import java.awt.Dimension;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.BorderFactory;
public class MyFrame extends LoginSim{
JButton button;
MyFrame(){
button = new JButton();
String name = JOptionPane.showInputDialog("Enter your username please!");
JOptionPane.showMessageDialog(null, "Welcome " + name + "!");
int age = Integer.parseInt(JOptionPane.showInputDialog("Enter your age please in numbers! (Ex: 2, not two.)"));
JOptionPane.showMessageDialog(null, "You are " + age + " years old.");
JFrame frame = new JFrame(); //creates frame, needs import
frame.setTitle("Welcome"); //sets title
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit out of application
frame.setResizable(true); //frame resizing true or false
frame.setSize(800,600); //set x dimension, and y dimension of frame
frame.setVisible(true); //make frame visible
frame.getContentPane().setBackground(new Color(245, 225, 225)); //change frame bg color, by rgb
//(250, 172, 172) or (245, 225, 225) possible colors
//button.setFont(new Font("Comic Sans"Font.BOLD,25));
//button.setBounds(20,20,10,10); //(x, y, width, height)
//button.setPreferredSize(new Dimension(50, 50));
button.setBounds(20,20,10,10);
button.addActionListener(e -> System.out.println("poo."));
button.setText("Bruh");
button.setFocusable(false);
button.setForeground(new Color(0, 0, 0));
button.setBackground(new Color(230, 223, 223));
button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.BOTTOM);
button.setIconTextGap(-15);
button.setBorder(BorderFactory.createEtchedBorder());
button.setEnabled(true);
frame.add(button);
}
}
frame.setVisible(true)should be the last statement in your constructor.- Add a LayoutManager. Ohterwise components like the button are placed on top of other components and always appear as full size.
Thank you!
Apologies for this, but can you explain where and how I should add the LayoutManager?
- These are the basic types of layout managers: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
- You should set the layout before adding components to the specified container
This Swing Java Tutorial describes developing graphical user interfaces (GUIs) for applications and applets using Swing components