I have problem with displaying components on my JFrame. I'm closing my current window and opening new one and want to display jLabel on it but nothing is happening. Code is below :
Frame[] nF = DBChooser.getFrames();
nF[0].setVisible(false);
JFrame windoow = new JFrame("Processing");
JPanel pan = new JPanel();
windoow.setPreferredSize(new Dimension(400, 150));
pan.setPreferredSize(new Dimension(400, 150));
JLabel textLabel = new JLabel ("Processing...");
textLabel.setLayout(null);
pan.setLayout(null);
windoow.setLayout(null);
pan.add(textLabel);
pan.revalidate();
pan.repaint();
windoow.getContentPane().add(pan);
windoow.setLocationRelativeTo(null);
windoow.pack();
windoow.setVisible(true);
I appreciate any help
Why you need so many setLayout(null); ? I remove them and it worked
public class DBChooser extends Frame {
public static void main(String args[]) {
Frame[] nF = DBChooser.getFrames();
// nF[0].setVisible(false);
JFrame windoow = new JFrame("Processing");
JPanel pan = new JPanel();
windoow.setPreferredSize(new Dimension(400, 150));
pan.setPreferredSize(new Dimension(400, 150));
JLabel textLabel = new JLabel("Processing...");
// textLabel.setLayout(null);
// pan.setLayout(null);
// windoow.setLayout(null);
pan.add(textLabel);
pan.revalidate();
pan.repaint();
windoow.getContentPane().add(pan);
windoow.setLocationRelativeTo(null);
windoow.pack();
windoow.setVisible(true);
}
}
It is because you set a null layout to window and panel without specifying any width, lenght or position, either use some LayoutManager or set these properties (eg. bounds). A null LayoutManager means that you need to set everything yourself, because there is nothing (no LayoutManager) that would place your elements automatically. This example uses a BorderLayout, which creates a nice effect:
the code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
JFrame windoow = new JFrame("Processing");
JPanel pan = new JPanel();
windoow.setPreferredSize(new Dimension(400, 150));
pan.setPreferredSize(new Dimension(400, 150));
JLabel textLabel = new JLabel("Processing...");
textLabel.setLayout(null);
pan.setLayout(new BorderLayout());
windoow.setLayout(new BorderLayout());
pan.add(textLabel);
pan.revalidate();
pan.repaint();
windoow.getContentPane().add(pan);
windoow.setLocationRelativeTo(null);
windoow.pack();
windoow.setVisible(true);
}
}
Related
I'm writing this swing application and I'm using multiple panels in a BoxLayout format, but it seems to be that the empty space between the panels is being divided up between them and it looks really ugly. How do you adjust and customize how much space is put between panels? Sorry if this is a repost; I was unable to find an older post.
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class gui extends JFrame implements ActionListener{
JFrame frame = new JFrame("Ark Admin Spawn Commands");
JPanel panel = new JPanel();
JComboBox dinos;
JComboBox corruptedDinos;
public JSlider dinoLevel;
JLabel input;
JLabel dino;
JLabel title;
gui(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel panelOne = new JPanel();
JPanel panelTwo = new JPanel();
JPanel panelThree = new JPanel();
mainPanel.add(panelOne);
mainPanel.add(panelTwo);
mainPanel.add(panelThree);
title = new JLabel("Spawning Dinos");
String[] dinoNames= {"The Island:"};
String[] corruptedDinoNames = {"Extinction:"};
dinos = new JComboBox(dinoNames);
corruptedDinos = new JComboBox(corruptedDinoNames);
dinoLevel = new JSlider(JSlider.HORIZONTAL, 1, 600, 400);
dinoLevel.setMajorTickSpacing(20);
dinoLevel.setPaintTicks(true);
input = new JLabel("Select Level: ");
event e = new event();
dinoLevel.addChangeListener(e);
dinos.addActionListener(this);
corruptedDinos.addActionListener(this);
panelOne.add(title);
panelTwo.add(input);
panelTwo.add(dinoLevel);
panelThree.add(dinos);
panelThree.add(corruptedDinos);
this.getContentPane().add(mainPanel);
this.setTitle("Ark Admin Spawn Commands");
this.setSize(600, 600);
this.setVisible(true);
}
public static void main (String args[]) {
new gui();
}
public class event implements ChangeListener{
#Override
public void stateChanged(ChangeEvent e) {
int value = dinoLevel.getValue();
input.setText("Level: " + value);
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
}
but it seems to be that the empty space between the panels is being divided up between them
Correct. A BoxLayout will attempt to allocate extra space to all components.
However, it will respect the maximum size of each panel.
So to prevent the panels height from growing you can use code like:
JPanel panelOne = new JPanel()
{
#Override
public dimension getMaximumSize()
{
Dimension d = getPreferredSize()
d.width = Integer.MAX_VALUE;
return d;
}
};
Or because the default layout manager of the frame is a BorderLayout, you can just use:
//this.getContentPane().add(mainPanel);
add(mainPanel, BorderLayout.PAGE_START); // getContentPane() is not needed
The PAGE_START of the BorderLayout respects the preferred height of the component.
I am new to working with GUI's in Java and I am having a problem moving my text and buttons around. No matter what coordinates I give my button or any of the other JLabel it doesn't move, I was wondering how I could fix it this in such a way that I can place my components where ever I want on the JPanel
public class IntroPage extends JFrame {
public static void main(String[] args) {
IntroPage main = new IntroPage();
main.setVisible(true);
}
private JPanel contentPane;
public IntroPage (){
//make sure the program exits when the frame closes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Welcome");
contentPane = new JPanel();
setSize(400,700);
//This will center the JFrame in the middle of the screen
setLocationRelativeTo(null);
//Welcome Page stuff :D
JLabel ApplauseLabel = new JLabel("Welcome to U.X.Dot.X");
ApplauseLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 30));
ApplauseLabel.setLocation(100, 50);
contentPane.add(ApplauseLabel);
JLabel slogan = new JLabel("Register below");
slogan.setFont(new Font("Gill Sans MT", Font.PLAIN, 15));
slogan.setLocation(100, 400);
contentPane.add(slogan);
//FacebookSignUp.
JButton FBbutton = new JButton("Login With FaceBook");
FBbutton.setBackground(Color.BLUE);
FBbutton.setSize(50,50);
FBbutton.setLocation(20, 40);
FBbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Add JPanel to go to FB API. Much later
}
});
contentPane.add(FBbutton);
add(contentPane);
//make sure the JFrame is visible
setVisible(true);
}
}
You're ignoring the layout managers of your contentPane JPanel. Understand that it uses FlowLayout by default, and will ignore your setLocation and setBounds statements. Ror the JPanel to accept absolute positioning, you would have to give it a null layout via contentPane.setLayout(null).
Having said that, I do not advise you to do this! While null layouts, setLocation(...) and setBounds(...) might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example the following GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.*;
public class IntroPage2 extends JPanel {
public static final String TITLE = "Welcome to U.X.Dot.X";
private JLabel welcomeLabel = new JLabel(TITLE, SwingConstants.CENTER);
private JButton fbButton = new JButton("Login With Facebook");
public IntroPage2() {
fbButton.setBackground(Color.BLUE);
fbButton.setForeground(Color.CYAN);
welcomeLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 30));
int wlGap = 20;
welcomeLabel.setBorder(BorderFactory.createEmptyBorder(wlGap, wlGap, wlGap, wlGap));
JLabel registerBelowLabel = new JLabel("Register Below");
registerBelowLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
JPanel centralPanel = new JPanel(new GridBagLayout());
centralPanel.setPreferredSize(new Dimension(300, 600));
centralPanel.add(registerBelowLabel);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(fbButton, BorderLayout.LINE_START);
topPanel.add(welcomeLabel, BorderLayout.CENTER);
setLayout(new BorderLayout());
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
add(topPanel, BorderLayout.PAGE_START);
add(centralPanel, BorderLayout.CENTER);
}
private static void createAndShowGui() {
IntroPage2 mainPanel = new IntroPage2();
JFrame frame = new JFrame("Welcome");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
would create something like:
I am creating a JFrame that contains a JPanel with a grid of buttons. Everything works fine but I then want to add a JLabel above the panel of buttons but the label never appears. It does appear if I don't use BoxLayout, though. Any help is appreciated.
The first code part below is my JFrame class:
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame {
private static final long serialVersionUID = 1L;
Panel panel = new Panel();
Dimension frameDim = new Dimension(1000, 1000);
Dimension labelDim = new Dimension(100, 20);
Box box = new Box(BoxLayout.Y_AXIS);
JLabel label = new JLabel("Tic Tac Toe");
JPanel pane = new JPanel();
public Frame() {
pane.add(label);
pane.setPreferredSize(labelDim);
pane.setMinimumSize(labelDim);
add(pane);
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue());
add(box);
setTitle("Tic Tac Toe");
setSize(frameDim);
setMinimumSize(frameDim);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
The code below is my JPanel class with buttons:
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Panel extends JPanel {
private static final long serialVersionUID = 2L;
private int i;
JButton[] button = new JButton[9];
GridLayout layout = new GridLayout(3, 3);
Dimension dim = new Dimension(500, 500);
public Panel() {
for (i = 0; i<9; i++) {
button[i] = new JButton();
add(button[i]);
}
setPreferredSize(dim);
setMinimumSize(dim);
setMaximumSize(dim);
setLayout(layout);
}
}
The last code part below is the Main class:
public class RunGame {
public static void main(String[] args) {
new Frame();
}
}
add(box);
This is adding the label direct to the JFrame, the content pane of which is laid out using a BorderLayout. The default when adding to a component to a border layout without any constraint is the CENTER, which can only display a single component. To fix it use:
pane.add(box);
you can use the BorderLayout when adding your label into Pane into the Frame and remove that box thing as below
public Frame()
{
//create label and add it to the frame
JLabel label = new JLabel("Tic Tac Toe");
label.setHorizontalAlignment( JLabel.CENTER );
add(label, BorderLayout.NORTH);
//create buttonsPanel and add it to the frame
JPanel buttons = new JPanel();
buttons.setLayout( new GridLayout(3, 3));
for (int i = 0; i < 9; i++)
{
buttons.add(new JButton(""+i));
}
add(buttons, BorderLayout.CENTER);
//setup the title, other properties for the frame etc..
setTitle("Tic Tac Toe");
setSize(1000, 1000);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
hope this helps better :)
I am trying to set the width of the JTextField but non of the methods to change it's size are working I have tried to change the amount of columns to change the width of the JTextField but it's not working?
What is causing this?
And how will I be able to change the width?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
public class main {
public static void main(String[] args) {
//Create and set up the window.
final JFrame frame = new JFrame("Layout 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 1500, 1000);
frame.setBackground(new Color(255,255,255));
frame.setLayout(null);
Container pane = frame.getContentPane();
pane.setLayout(null);
JLayeredPane jlp = new JLayeredPane();
frame.setContentPane(jlp);
JPanel container = new JPanel();
//container.setBackground(new Color(241,241,241));
container.setBackground(Color.RED);
container.setBounds(0,0,frame.getWidth(), 75);
container.setLayout(null);
JPanel containerA = new JPanel();
containerA.setBackground(Color.blue);
containerA.setBounds(90 ,10,50,50);
JPanel containerB = new JPanel();
containerB.setBackground(Color.RED);
containerB.setBounds(95 ,20,50,50);
//This is the top textfield
JTextField textField = new JTextField(1000);
textField.setLayout(null);
textField.setPreferredSize(new Dimension(1000,1000));
textField.setBounds(0,0,2300,50);
textField.setColumns(1000);
textField.setSize(1000,10);
textField.invalidate();
textField.setMinimumSize(new Dimension(1000,100));
container.add(textField);
jlp.add(container, Integer.valueOf(2));
jlp.add(containerA, Integer.valueOf(1));
jlp.add(containerB, Integer.valueOf(3));
container.setVisible(true);
frame.invalidate();
frame.setVisible(true);
}
}
You need to change just this line, and will get width of text field,
textField.setSize(1000,25);
import javax.swing.*;
import java.awt.*;
class MainGui{
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon("C:\\Users\\BSK\\Desktop\\game5.jpg"));
public MainGui(){
frame.setSize(600,800);
frame.setVisible(true);
frame.setResizable(false);
setButtonSize();
frame.setLayout(new BorderLayout());
frame.setContentPane(backImage);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
insertBlankArea(frame);
frame.getContentPane().add(newBut);
insertBlankArea(frame);
frame.getContentPane().add(continueBut);
insertBlankArea(frame);
frame.getContentPane().add(exitBut);
frame.setSize(799,800);
}
public void insertBlankArea(JFrame frame){
frame.getContentPane().add(Box.createRigidArea(new Dimension(280,155)));
}
public void setButtonSize(){
Dimension dim = new Dimension(100,100);//here is the problem,i am not getting the desired dimension and the size of buttons remains the default.
newBut.setPreferredSize(dim);
continueBut.setPreferredSize(dim);
exitBut.setPreferredSize(dim);
}
public static void main(String[] args) {
MainGui mainGui = new MainGui();
}
}
So iam not getting the defined size for the buttons but when i set frame.setResizable(false); then when i stretch the screen the button's height increases but its width still remains the same.
So please tell me what is going wrong?
You should take a look at A Visual Guide to Layout Managers and choose the most appropriate one for your situation. You should also avoid explicitly setting sizes (ie: setSize, setMinimumSize, setMaximumSize, and setPreferredSize) because those methods are the responsibility of the layout manager. You may also be interested in reading this question on whether or not the use of the different set size methods should be avoided or not.
Finally, you should not be calling your MainGUI class outside of the Event Dispatch Thread (EDT). Most Swing GUI-related methods are not thread safe and therefore require being executed in the EDT. Below is a corrected version of your main method:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MainGui mainGui = new MainGui();
}
});
}
Just reading your short descrption, I have no idea what your problem is. But based solely on the question title
"How to give a preffered size to the JButton?"
Don't. Let the the layout manager handle this for you. If you want a bigger button, you can use JButton.setMargins(Insets) and/or JButton.setFont(Font) where you specify a bigger font.
If you want you button stretched or not to stretch, You need to select an appropriate layout manager, that will or won't respect the buttons preferred size. For instance, BorderLayout and GridLayout won't respect preferred sizes and will stretch the button the fit, and FlowLayout, BoxLayout, and GridBagLayout will respect the preferred size. As you can see here
See example with GridBagLayout
import javax.swing.*;
import java.awt.*;
class MainGui {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon(
getClass().getResource("images.jpg")));
public MainGui() {
backImage.setLayout(new BorderLayout());
frame.setContentPane(backImage);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
mainPanel.add(newBut, gbc);
gbc.gridy = 1;
mainPanel.add(continueBut, gbc);
gbc.gridy = 2;
mainPanel.add(exitBut, gbc);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.setSize(250, 275);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
MainGui mainGui = new MainGui();
}
});
}
}
And here's with nesting panels which will give the same result
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class MainGui {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon(
getClass().getResource("images.jpg")));
public MainGui() {
backImage.setLayout(new GridLayout(3,1));
frame.setContentPane(backImage);
JPanel p1= new JPanel(new GridBagLayout());
p1.setOpaque(false);
p1.add(newBut);
JPanel p2 = new JPanel(new GridBagLayout());
p2.setOpaque(false);
p2.add(continueBut);
JPanel p3 = new JPanel(new GridBagLayout());
p3.setOpaque(false);
p3.add(exitBut);
frame.add(p1);
frame.add(p2);
frame.add(p3);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 275);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
MainGui mainGui = new MainGui();
}
});
}
}