So I've been learning Java for the very first time and it's time for me to attempt my first project. And I'm stuck at the "first hurdle" haha.
The issue I have is the fact that I don't actually know how to space J Items apart.
I have a 250,350 window for a Log In form with a JLabel, a JTextField for username and JLabel JPassword for Password with a JButton at the bottom.
What I want to do now is style it so that the spacing between the top and the bottom of the form makes it so that the form is centered as well as adding a line's height space between the JLabel and the JTextField. (Basically a \n type deal but that isn't working.)
Hopefully this makes sense, if not, I apologise and I'll try to rephrase/add code!
public Game() {
this.setSize(250,350);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Sticket Cricket - Login");
JPanel loginMenuPanel = new JPanel();
loginButton = new JButton("Login");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setColumns(10);
passwordField.requestFocus();
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
this.add(loginMenuPanel);
loginMenuPanel.add(usernameLabel);
loginMenuPanel.add(usernameField);
loginMenuPanel.add(passwordLabel);
loginMenuPanel.add(passwordField);
loginMenuPanel.add(loginButton);
this.setVisible(true);
}
Short Answer:
Create a JPanel, set the layoutmanger of the panel (some examples, GridLayout, BorderLayout, Check out the tutorial here where more of these are explained)
Then add your components to this panel accordingly
For the layout you are looking for it would possibly be easier to use an IDE to create this, I find Net Beans to be the easiest for doing this.
My recommendation would be for you to create a JPanel with a grid layout of 2 columns and 2 rows, to this add you JLabels and Text fields for the logon name and password.
Then create another JPanel possibly BorderLayout or Flow Layout and add the above panel to this then add this parent panel to the frame.
Related
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.
I want to add the possibility for my users to add a comment on a form. To display them, I created JPanel inside a simple JScrollPane. I set the layout of this JPanel to BoxLayout because I wish to add them all in only one column and it seemed to be the easiest way by calling BoxLayout.Y_AXIS in the constructor. I also tried GridLayout and GridBagLayout but it was not what I was looking for.
My problem is that when a JPanel has the BoxLayout layout, it's width automatically is the same as it's container, but my container is a JScrollPane and the caret hides the right side of my comment!
You can see the JTextField and a JButton on the bottom left, here's the code on the click event :
private void btnAjoutCommentaireActionPerformed(java.awt.event.ActionEvent evt) {
//I take the text from the JTextField and format it to html
String formattedComment = "<html><br><div style='width:280px;'>" +
txtArCommentaire.getText().replaceAll("\n", "<br>") +
"</div><br></html>";
JLabel label = new JLabel(formattedComment);
//I add a blue border
label.setBorder(new TitledBorder(new EtchedBorder(Color.lightGray, Color.blue), ConfigUser.getCu().toString()));
//this below doesn't work
label.setSize(280, 200);
//I tried adding a JPanel in between but it didn't really worked out
//JPanel panel = new JPanel();
//panel.setLayout(new GridLayout(1, 1));
//panel.setSize(297, 200);
//panel.add(label);
///pnlCommentaire is the JPanel inside the JScrollPane
pnlCommentaire.setLayout(new BoxLayout(pnlCommentaire, BoxLayout.Y_AXIS));
pnlCommentaire.add(label);
pnlCommentaire.revalidate();
pnlCommentaire.repaint();
}
As you can see I tried to adust the size in html using style='width:280px'and on the JLabel using label.setSize(280, 200); but none of them worked.
Do you have any idea on how I could resize this Jlabel?
EDIT :
I added a margin-right property to the div so that I can at least fully see the text in the JLabel but the right border is still hidden.
String formattedComment = "<html><br><div style='width:280px;margin-right:50px;'>" +
txtArCommentaire.getText().replaceAll("\n", "<br>") +
"</div><br></html>";
I am trying to make a 2x2 grid layout that has a JLabel on the top left, and three buttons on the other three spaces. When I do this, I get the unexpected result of one big button (filling up the entire JDialog) that says "Do you want to push me". I don't know why this result shows up, please help, Thanks!
public void sinceyoupressedthecoolbutton() {
JDialog replacementwindow = new JDialog(); //Like a window
JButton best = new JButton("best");
JButton first = new JButton("FIRST");
JButton second = new JButton("Second");
replacementwindow.setLayout(new GridLayout(2,3,0,0)); //Row, column, distance horizontally, distance vertical
JPanel panel = new JPanel();
replacementwindow.add(panel); //adding the JPanel itself
replacementwindow.add(first);
replacementwindow.add(second);
replacementwindow.add(best);
replacementwindow.setSize(500, 500);
replacementwindow.setTitle("NEW WINDOW!");
replacementwindow.setVisible(true);
}
It's because you set the layout of your JButton, and not of your JDialog
Change
label.setLayout(new GridLayout(2,2,0,0));
to
YES.setLayout(new GridLayout(2,2,0,0));
Also, your variable called label is a JButton, you probably want to change that.
Don't add components to a button. You add components to a panel.
So the basic code should be:
JDialog dialog = new JDialog(...);
JPanel panel = new JPanel( new GridLayout(...) );
panel.add(label);
panel.add(button1);
...
dialog.add(panel);
Also, variable names should NOT start with an upper case character! "Yes" does not follow Java standards. The other variables do. Be consistent!
Please consider this Java code fragment:
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(new JCheckBox("Select all"));
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(new JLabel("Filter: "));
buttonBox.add(new JTextField());
Box paneBox = Box.createVerticalBox();
paneBox.add(buttonBox);
paneBox.add(new JScrollPane(jList));
For some reason i don't get, the JTextField takes up most of the screen. The jList isn't even visible anymore. I would like to know why and how to fix it.
When i comment the line with the JTextField, it looks fine (except no JTextField, of course). Why does the JCheckBox and the JLabel not get ridiculously big? What is the purpose of a one-line JTextField being able to take up almost the whole screen?
Most people suggest to set the size of the JTextField field to my needs. However, i read that i should not call these methods, but let the LayoutManager take care of it. Now what is the most elegant solution to prevent the JTextField from becoming so big?
Try using the setPreferredSize method like this:
textFieldName.setPreferredSize(new Dimension(x, y));
Obviously input the values for x and y that you wish the JTextField size to be
You can avoid this problem by using a simple JPanel() instead of a Box for the horinzontal one. And after just set the prefered size to your JTextField.
//Box buttonBox = Box.createHorizontalBox();
JPanel buttonBox = new JPanel();
buttonBox.add(new JCheckBox("Select all"));
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(new JLabel("Filter: "));
JTextField jt = new JTextField();
jt.setPreferredSize(new Dimension(100,25));
buttonBox.add(jt);
EDIT
Btw the defaut Layout of a JPanel is the FlowLayout which place components from left to right and with centered alignement by default. You can still change the alignement.
For example:
JPanel buttonBox = new JPanel(new FlowLayout(FlowLayout.LEFT));
You can also change the gap between each components. There is some other Layout like the BorderLayout or GridLayout / GridBagLayout. I let you search on Google for more information about them.
See in yellow the JPanel, in red the VerticalBox
Box box = Box.CreateVerticalBox();
Use box.setMaximumSize(Dimension(160,80))
and box.setMinimumSize(Dimension(160,80))
then it will work :D
If you need a strut for your layout, put it in between boxes.
I am trying to make a panel to have 4 items on top. these are a JLabel, JTextField, JLabel and JTextField.
In the center I need a JTextArea and to the left of it a JList that is scrollable.
On the bottom I need 3 buttons.
What would be the best layout manager for this and how should I go about it?
Would having just 3 columns be a good idea?
Heres what I have so far:
JPanel panel = new JPanel();
JTextField IDLabel = new JLabel("ID: ");
IDLabel.setBounds(10, 10, 80, 25);
panel.add(IDLabel);
JTextArea IDText = new JTextField(5);
IDText.setBounds(100, 10, 160, 25);
panel.add(IDText);
JLabel TitleLabel = new JLabel("Title: ");
TitleLabel.setBounds(10, 10, 80, 25);
panel.add(TitleLabel);
JTextField TitleText = new JTextField(10);
TitleText.setBounds(100, 10, 160, 25);
panel.add(TitleText);
JList list = new JList(new String[]{"test1", "test22"});
list.setFixedCellWidth(150);
list.setFixedCellHeight(50);
list.setFont(new Font("Serif",Font.BOLD,16));
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
panel.add(list);
JTextArea BodyArea = new JTextArea();
BodyArea.setSize(200, 200);
BodyArea.setText("Test area");
panel.add(BodyArea);
You will mostly likely need to use a combination of layouts (AKA compound layouts), for example
North Panel
Create a JPanel and assign it a FlowLayout or GridBagLayout or GridLayout depending on what you want to achieve.
Add the JLabel, JTextField, JLabel, JTextField to it.
Center Panel
Create a JPanel with BorderLayout. Add the JTextArea to the CENTER position and the JList to the WEST position
South Panel
Craete a JPanel with a FlowLayout or GridBagLayout or GridLayout depending on what you want to achieve.
Add the buttons to it.
Putting it together
Create a JPanel with a BorderLayout, add the "north" panel to the NORTH position, the "center" panel to the CENTER position and the "south" panel to the SOUTH position
You could use a single container and a GridBagLayout, but that's a lot of work.
Take a look at Laying Out Components Within a Container for more details
Maybe start with a BorderLayout for the main layout. Then you can add components to the PAGE_START (NORTH), LINE_START (WEST) and CENTER and PAGE_END (SOUTH). Check out the section from the Swing tutorial on Using Layout Manager, for more information and examples.
Of course you would also use panels when you want to display multiple components in a single area. So your buttons would first be added to panels.
Also, follow standard naming conventions. Variable names should NOT start with an upper case character( ie. BodyArea, TitleText). You got variable like (panel, list) correct so be consistent.