Size of button in java game - java

I am a beginner. I am programming a Java game, and I am having trouble changing the size of the button buttonPlayAgain. The size of the button does not change using the code below. How can I change the size of the button?
Here is my code:
public hoppa(IModele modele) {
super(new GridLayout(1, 1));
setSize(VueGrille.FACT * modele.getGrille().getLongueur(), 1);
Dimension dim = new Dimension(1, 1);
labMines = new JLabel();
labMines.setPreferredSize(dim);
add(labMines);
buttonPlayAgain = new JButton("New Game");
//buttonPlayAgain.setSize(1, 1);
buttonPlayAgain.setPreferredSize(new Dimension(50,50));
add(buttonPlayAgain);
labTimer = new JLabel();
labTimer.setPreferredSize(dim);
add(labTimer);
initValues(modele);
}

It can be normal that your button is not resized while calling setPreferredSize. try setSize instead. See Java: Difference between the setPreferredSize() and setSize() methods in components

Use setSize() if your component's parent has no layout manager, and setPreferredSize() (see also setMinimumSize and setMaximumSize) if it does.
setSize() most likely won't do anything if the component's parent is using a layout manager

Related

Change JTextField height on Swing

I'm trying to fix the height of the "amountField" text field, but I can't.
I would like the height of amountField to have the same height as the JComboBox that it's above, so it looks better.
Right now, the JTextField looks very tall compared with the rest of design.
I've tried everything that I've read in this forum, but nothing seems to work.
I don't know if it's relevant, but this whole JPanel (WithdrawalScreen) is inside another JPanel with BorderLayout. This panel is the center part of it
Thanks
PictureHere
public class WithdrawalScreen extends JPanel {
Public JPanel init() {
this.setLayout(new GridLayout(0,1));
account = new JLabel("account");
accountSelect = new JComboBox(labels);
amount = new JLabel("amount");
amountField = new JTextField("");
submit = new JButton("SUBMIT");
this.add(account);
this.add(accountSelect);
this.add(amount);
this.add(amountField);
this.add(submit);
return this;
}
}
Try creating the Grid Layout with 5 rows and 1 column. I think the height is messed up because you are not setting the constructor arguments properly.
new GridLayout(5,1);
Grid layout will stretch the component and give the same size to all of its components. In order to keep the "default" size of each component, you can use BoxLayout with BoxLayout.Y_AXIS parameter in its constructor. Another way would be to use a dummy-nested JPanel with another layout. Let's say FlowLayout.
JTextField textField = new JTextField(10);
JPanel nestedPanel = new JPanel(new FlowLayout());
nestedPanel.add(textField);
gridLayoutPanel.add(nestedPanel);
JTextField will not be stretched. nestedPanel will be. Do some experiments yourself and you will find the way that fits your needs.
A link that will help you: A visoual guide to Layout Managers.

Java swing GUI absolute positioning

I know that absolute positioning is not recommended, but I need to show my labels randomly scattered as well as randomly changing their positions.
I have researched how to use setBounds but it doesn't seem to work. The following code shows the labels in a Flow Layout, and when I use setLayout(null) it shows a blank frame.
public class GUI extends JFrame{
device mobiles[];
device station;
JPanel pane= new JPanel();
public GUI()
{
setTitle("communication is Key");
setSize(1000, 1000);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pane.setBackground(Color.WHITE);
int x=0; int y=0;
mobiles= new device[10];
for (int i = 0; i < 10; i++) {
x=randInt();
y=randInt();
mobiles[i]= new device(1,x,y);
pane.add(mobiles[i]);
}
x=randInt();
y=randInt();
station = new device(0,x,y);
pane.add(station);
this.add(pane);
}
and this is class "devices" that extends JLabel
public class device extends JLabel{
ImageIcon mob = new ImageIcon("mob.png");
ImageIcon tow = new ImageIcon("tower.png");
public device(int num, int x, int y)
{ if(num==1)
this.setIcon(mob);
else this.setIcon(tow);
this.setBounds(x, y, 3, 7);
}
}
any help in finding out what the problem is, would be be appreciated.
The following code shows the labels in a Flow Layout, and when I use setLayout(null) it shows a blank frame.
The layout manager sets the size and location of the component.
If you don't use the layout manager, then you are responsible for set the size and location of each component.
Typically I would set the size to equal to the components preferred size.
Also, did you display the x/y value that are randomly generated? Maybe the values are larger than the size of the panel.
and when I use setLayout(null) it shows a blank frame.
What layout is set to null? The panel of the frame. Your code doesn't use the above method. Post the code that you use to cause the problem. We don't want to guess what you may or may not be doing.
thanks to #CasparNoree ... the answer suggested was to initialize the Japnel from the start:
JPanel pane = new JPanel(null);
When you set the layout to null you can set the bounds manually with coordinates.
JFrame jf = new JFrame();
JPanel p = new JPanel();
JButton jb = new JButton();
// this is where you make it so setting the bounds actually does something
p.setLayout(null);
jb.setBounds(100,100,100,100);
p.add(jb);
jf.add(p);
jf.setVisible(true);

Placing JTextFields in a JFrame of a Java GUI

I have:
public class BaseStationFrame1 extends JFrame
{
JButton activateButton;
JButton deactivateButton;
BaseStation bs;
JTextField networkIdField;
JTextField portField;
public BaseStationFrame1(BaseStation _bs){
bs = _bs;
setTitle("Base Station");
setSize(600,500);
setLocation(100,200);
setVisible(true);
activateButton = new JButton("Activate");
deactivateButton = new JButton("Deactivate");
Container content = this.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(activateButton);
content.add(deactivateButton);
networkIdField = new JTextField("networkId : "+ bs.getNetworkId());
networkIdField.setEditable(false);
content.add(networkIdField);
portField = new JTextField("portId : "+ bs.getPort());
portField.setEditable(false);
content.add(portField);}
}
My problem is that i don't want the two TextFields to appear on the right of Activate and Deactivate buttons but below them. How can i fix that?
Specify your layout manager, like this:
content.setLayout(new GridLayout(2,2));
That would use the Grid Layout Manager to establish a grid with 2 columns and 2 rows, that your components would then be placed in.
The layout manager you are currently using, FlowLayout, only adds contents onto the end of the current row. it will wrap around once it reaches the constrained edge of the pane, though.
You should also check the other layout managers here
You could alternatively use GridBagLayout , but you will have to specify a GridBagConstraints object you then add alongside the individual elements, like so:
content.add(networkIdField, gridConstraints);
see more on that in the linked tutorial.
can I suggest that you use a Null Layout for the parent component?
setLayout(null);
then use a setBounds(xPos,yPos, Width, Height);
to position the components on the panel etc?
Doing this will prevent Java's UI Manager to manage the components to the Frame, Panel etc.
That seems to be the easiest and less painful way.
Regards

Please help me understanding BoxLayout alignment issues

I'm trying to create a very simple window using Java Layouts. I have got three elements to arrange: a button, a progress bar and a label. The button has to be vertically centered, the progress bar has to take full width, and the label has to be left aligned.
Here's some code (just assume pane is the content pane of a JFrame, and button, progressBar and label have been created before):
BoxLayout layout = new BoxLayout(pane, BoxLayout.Y_AXIS);
pane.setLayout(layout);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
pane.add(button);
progressBar.setAlignmentX(Component.CENTER_ALIGNMENT);
pane.add(progressBar);
label.setAlignmentX(Component.LEFT_ALIGNMENT);
pane.add(label);
When I test the application I see everything misaligned and screwed up: the button and the label are randomly indented, and if I resize the window the indentation amount changes in a strange way.
The progress bar looks good (full width).
I just don't understand what's happening. Can you give me a clue?
BoxLayout cannot handle different alignments: see http://download.oracle.com/javase/tutorial/uiswing/layout/box.html
quoting from that article: "In general, all the components controlled by a top-to-bottom BoxLayout object should have the same X alignment. Similarly, all the components controlled by a left-to-right Boxlayout should generally have the same Y alignment."
Sometimes you need to get a little creative and use nested panels. But I like this approach better then trying to learn and memorize all the constraints required when using other layout managers (GridBagLayout, GroupLayout) there where designed to be used by IDE's that generate code for you.
import java.awt.*;
import javax.swing.*;
public class BoxLayoutVertical extends JFrame
{
public BoxLayoutVertical()
{
Box box = Box.createVerticalBox();
JButton button = new JButton("A button");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
box.add(button);
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setAlignmentX(Component.CENTER_ALIGNMENT);
box.add(progressBar);
JPanel panel = new JPanel( new BorderLayout() );
JLabel label = new JLabel("A label");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(label);
box.add(panel);
add(box, BorderLayout.NORTH);
}
public static void main(String[] args)
{
BoxLayoutVertical frame = new BoxLayoutVertical();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(300, 200);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
To complement my comment to the original question, here is a snippet that uses DesignGridLayout:
JButton button = new JButton("Button");
JProgressBar progressBar = new JProgressBar();
JLabel label = new JLabel("Label");
// The interesting stuff is in the next 4 lines
DesignGridLayout layout = new DesignGridLayout(getContentPane());
layout.row().center().add(button).withOwnRowWidth();
layout.row().center().fill().add(progressBar);
layout.row().left().add(label);
pack();
It does exactly what wou describe in your question and doesn't require any specific call of any of the components.
Maybe your code is just a snippet, but I'm missing a call to pack().
Coding swing layout by hand can be very frustrating with the standard Layout managers. I use MiG Layout for that purpose. It is straight forward and you have a nice layout with just a few lines of code. If you're not forced to use BoxLayout I would suggest you give it a try.
Don't use BoxLayout. It works only for very simple cases.
For your case, I would recommend either GridBagLayout or (my favorite) GroupLayout.
For GroupLayout, I created a subclass (LayoutHelper) with some utility methods and useful constructors, which makes writing the Layout much easier.
Of course, usually I align all components in a group the same way, so it is not as short in your case as it would be in the simple case.
LayoutHelper h = new LayoutHelper(pane);
h.setVerticalGroup
( h.sequential( button, progressBar, label));
h.setHorizontalGroup
( ((ParallelGroup)h.parallel())
.addComponent(button, Alignment.CENTER)
.addComponent(progressBar)
.addComponent(label, Alignment.TRAILING));
Here is a screenshot:
For a simple "everything aligned the same way", the horizontal group would look like this:
h.setHorizontalGroup
( h.parallel (button, progressBar, label));
(optionally with a first argument indicating the alignment).

Java Swing set "actual" Frame size (inside)

I have a JFrame which contains just one JPanel.
I have tried setting the Panel's size and packing the frame, but that has no effect.
If I set the JFrame's size, it will change the size so it includes the title bar and borders.
How do I set the "actual size" so it doesn't include the title bar and borders?
Example:
Thanks in advance, guys
You could set the contentPane's preferredSize and call pack on the JFrame, but in general it's usually best to let components size themselves based on their preferred sizes as determined by their layout managers.
This is an example of setting JPanel's size and packing the frame:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(200, 200));
frame.add(panel);
frame.pack();
frame.setVisible(true);
Did you try something like this?
If you set the preferred size of the JPanel then the JFrame's pack() method will respect it.
Use the .getInsets method on JFrame which gives you the dimensions of the sizes around the non-client area.
Then add it up to your wanted size, and set the size using setSize.
If you want to get Frame border then first use pack on your frame and after that get Frame Insets like in this code bellow:
frame.pack();
Insets insets = frame.getInsets();
int frameLeftBorder = insets.left;
int frameRightBorder = insets.right;
int frameTopBorder = insets.top;
int frameBottomBorder = insets.bottom;
Is better to use the pack method right after your setResizable(boolean) method, because resizable for some reason changes your frame borders, but if you dont use resize method then use pack method right on the start of frame constructor.
Setting the actual size of the usable space in JFrame could be done through setting the preferred size of the container in
createComponents(Container container) method. Done in this way, you skip setting the size of
the whole JFrame through setPreferredSize(new Dimension (width, length) in the run() method. So, the code will look like this:
#Override
public void run() {
JFrame frame = new JFrame();
// other code ...
this.createCompoents(frame.getContentPane());
}
private void createCompoents(Container container) {
// other code ...
container.setPreferredSize(new Dimension(width, length));
}

Categories