So, I just need to add a title to my swing. Here's the code:
import javax.swing.*;
import java.util.Scanner;
public class Wall extends JFrame {
public static void main(String[] args) {
new Wall();
}
public Wall() {
final String title = "Wall Game";
this.setSize(300,300); //sets the screen
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle(title);
this.setVisible(true);
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Welcome to the Wall Game!");
JLabel label2 = new JLabel("Click the button to read the instructions!");
panel1.add(label1);
panel1.add(label2);
this.add(panel1);
}
}
I want the Welcome to the Wall Game! part of this to be bigger. Is it possible to make it bigger? If there's a bonus, I wonder if you can add different fonts. But that's not important right now.
Thanks to anyone who knows :P.
I believe all you need is something like this:
JLabel label1 = new JLabel("Welcome to the Wall Game!");
label1.setFont(new java.awt.Font("Arial", 1, 24));
This will set the font to type Arial, '1' will set it to plain, and '24' is the font size. Just read this if you want to do more with the font: https://docs.oracle.com/javase/7/docs/api/java/awt/Font.html
Font font = new Font("Font Name", Font.TYPE_OF_FONT, size);
yourLabel.setFont(font);
Basically, you're creating a "new" font (not really "new" because Arial already exists, but you're just making it bigger (deriving it)).
The first parameter: "Font Name" is self-explanatory: The name of the font; e.g Arial.
The second parameter: Font.TYPE_OF_FONT determines what type your font is: for example, Font.ITALIC italicizes your label. Font.BOLD bolds your label. For more information, see here.
The third parameter: size, which is, in fact, the size! Changing size to 42 makes the font size 42, and changing it to 12345.67890f changes the font size to 12345.67890.
Applying the font
label.setFont(font);
Pretty self-explanatory.
For more information, read this link.
Related
I have been working to try and make a JFrame that has text in the middle that is really big, but every attempt I've made to change the size of the text has just resulted in teeny tinny little words in the corner of the screen.
public class StuffMost {
public static JLabel three = new JLabel();
public static JFrame one = new JFrame();
public static JButton four = new JButton();
public static void seconday() {
one.setVisible(true);
one.setResizable(true);
one.setDefaultCloseOperation(one.EXIT_ON_CLOSE);
one.setSize(1280, 800);
one.setTitle("Hello! Welcome to my window. You Shall Never Leave.");
one.setBackground(Color.BLUE);
three.setText("Dont");
one.add(three);
three.setSize(900, 300);
one.add(four);
}
}
Do not use setSize on the Label, for that does not change the font. If you want to make the font bigger then you would use:
three.setFont(new Font("Courier", Font.BOLD,75));
if you wanted a different font, then you could change it to "Arial" or something like that, if you don't want it bolded, then change the second parameter to Font.PLAIN, and the last parameter is the font size, which in this case is 75
Here is my java code:
JLabel persAdi,persSoyadi,persKodu,ust,alt;
JTextField ad,soyad,tckimlikno;
JButton bul,iptal;
public persBul(){
setSize (400,600);
setResizable(false);
setLocation (20, 20);
setVisible(true);
Container icerik = getContentPane();
icerik.setLayout(null);
icerik.getX();
ust=new JLabel("Bulmak İstediğiniz Personelin;");
ust.setBounds(10, 10, 200, 30);
icerik.add(ust);
persAdi=new JLabel("Adı:");
persAdi.setBounds(10,40,80,15);
icerik.add(persAdi);
ad=new JTextField();
ad.setBounds(50, 40, 80, 20);
icerik.add(ad);
persSoyadi=new JLabel("Soyadı:");
persSoyadi.setBounds(10, 180, 80, 30);
icerik.add(persSoyadi);
soyad=new JTextField();
soyad.setBounds(200, 40, 100, 30);
Icon bulPng=new ImageIcon(getClass().getResource("search.png"));
Icon iptalPng=new ImageIcon(getClass().getResource("cancel.png"));
bul=new JButton("",bulPng);
bul.setBounds(20, 120, 40, 40);
icerik.add(bul);
iptal=new JButton("",iptalPng);
iptal.setBounds(90, 120, 40, 40);
icerik.add(iptal);
}
public static void main(String[] args){
persBul app=new persBul();
}
When I debug this code, my JTextField doesn't appear. Only first JLabel can appear and I don't see any other JLabel or JTextField or JButton. My button appears when my cursor is on it. I have to do this project but I haven't created the user interface yet. Can anybody help me?
You should avoid using null layouts.
You can achieve the same (or a ver aproximate) UI by using layout managers. As I pointed in this comment.
Here's a MCVE which I recommend you to do in further questions. Also look at How to ask guide in order to make better questions.
I made a new class because trying to modify yours was more work than this. Copy-paste it and understand how it works, then adapt it to your own class.
Edit
You can add separators to add spaces. Also as #Andrew Thompson said in his comment, you can look at How to use multiple layout managers (I did something like that in the example). Here are other options on How to add spaces in swing. Maybe GridBag Layout is the one which seems more like a null layout.
Here's a guide on layouts (link also provided by Andrew).
After reading your question:
Can I use setBounds(x,y,width,height); function with this code? Or What can I do for using this function (setBounds(x,y,width,height);)? Because I want to determine my own self x,y points of the JLabel,JTextField,JButton
You should avoid using setBounds(x,y,width,height); at all costs, because, as also Andrew gave the explanation of why:
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components.
Using a null layout could bring some unexpected errors while executing program. It is fine to use null layout (I mean, setBounds(x,y,width,height);, if and only if you're a newbie on swing, but as soon as posible try to start using the Layout Managers instead of the null layout.
What I want to say is: It's not wrong to use null layout only for educational purposes, but even as it is larger and sometimes more complex and requires a bit more thinking, it's better to use them in order to avoid unexpected errors. While you're a student use it, but avoid it if it's for a professional program.
Here's the output of this answer So you can see the use of spaces in swing.
import javax.swing.*;
import java.awt.*;
class example {
JFrame frame;
JPanel panel, hPanel1, hPanel2;
JLabel label1, label2;
JTextField field1, field2;
example() {
frame = new JFrame("example");
panel = new JPanel();
hPanel1 = new JPanel();
hPanel2 = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
hPanel1.setLayout(new FlowLayout());
hPanel2.setLayout(new FlowLayout());
label1 = new JLabel("Label 1");
label2 = new JLabel("Label 2");
field1 = new JTextField();
field2 = new JTextField();
field1.setColumns(6);
field2.setColumns(6);
hPanel1.add(label1);
hPanel1.add(field1);
hPanel2.add(label2);
hPanel2.add(field2);
panel.add(hPanel1);
panel.add(hPanel2);
frame.add(panel);
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new example();
}
});
}
}
I'm trying to create a JFrame with a background image, a JLabel over the background image centered and toward the bottom, with two buttons on the right and left that say "Stay" and "Leave". This is already created. The issue arises with the order of each of the items. I cannot get the JLabel with text and buttons over the background image, with both of them showing. Here is my code; any advice would be appreciated. Thank you in advance.
public class SceneOne {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
JFrame SceneOne = new JFrame();
ImageIcon image = new ImageIcon(
"C:/Users/alan/Downloads/scary_forest_2.jpg");
JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add(imageLabel, BorderLayout.CENTER);
SceneOne.add(panel);
SceneOne.setResizable(true);
imageLabel.setVisible(true);
SceneOne.pack();
JButton Leave=new JButton("Leave");
JButton Stay= new JButton ("Stay");
JPanel Leave1= new JPanel(new FlowLayout());
JPanel Stay1=new JPanel(new FlowLayout());
FlowLayout two = new FlowLayout(FlowLayout.LEFT);
FlowLayout three = new FlowLayout(FlowLayout.RIGHT);
Leave1.setLayout(two);
Stay1.setLayout(three);
Stay1.add(Leave);
Leave1.add(Stay);
Leave1.setOpaque(false);
Stay1.setOpaque(false);
SceneOne.add(Leave1);
SceneOne.add(Stay1);
JLabel label1 = new JLabel("Test");
SceneOne.add(label1);
label1.setText("<html><font color='red'> It was approximately 11:30 pm. The night sky was black not a single star piercing through the darkness"
+ "except the thick and powerful moonlight."
+ "<br>"
+ "You are alone leaving a costume party at a friend's place."
+ "It was rather boring and you decided to leave early."
+ "A stutter is heard and your"
+ "<br>"
+ "car begins to shake"
+ "Your headlights and car lights crack. The engine is left dead silent."
+ "You are left in a total silence"
+ "and baked in merely the moonlight."
+ "<br>"
+ "There is a mere second of silence till a harsh chill ripes through the"
+ "car like a bullet through paper. You are left dumbfounded. What do you do?</font><html>");
label1.setHorizontalAlignment(JLabel.CENTER);
label1.setVerticalAlignment(JLabel.BOTTOM);
label1.setVisible(true);
label1.setOpaque(false);
SceneOne.setComponentZOrder(panel, 0);
SceneOne.setComponentZOrder(label1, 0);
// SceneOne.setComponentZOrder(Leave1,0);
// SceneOne.setComponentZOrder(Stay1,0);
SceneOne.setSize(400,320);
SceneOne.setTitle("The Car");
SceneOne.setVisible(true);
SceneOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SceneOne.setLocation(500, 300);
}
}
First of all follow Java naming conventions. Variable names should NOT start with an upper case character. I have never seen a tutorial, text book or forum example that uses variable names like you are using. Don't make up your own conventions!
The default layout manager for a JFrame is a BorderLayout. When you use the frame.add(...) method the component is added to the CENTER of the BorderLayout by default. Only on component can be added to the CENTER so only the last component is displayed.
If you want components to appear on top of the image, then you need to add the components to the image. The basic code would be:
JLabel label = new JLabel( new ImageIcon(...) );
frame.add(label);
label.setLayout(....);
label.add(leaveButton);
label.add(labelWithText);
label.add(stayButton);
I'll let you work out the exact layout that you want.
I've written a long code involving several frames using only JFrame, and now I need a scrollbar for one of the frames. It seems like the only way to use JScrollPane is with JPanel, but I dont want to rewrite everything, is there a way?
frames[2] = new JFrame("Title");
frames[2].setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);//EXIT_ON_CLOSE
frames[2].setContentPane(new JLabel(new ImageIcon("/Users/mac/Downloads/bg.000.jpg")));
frames[2].setLayout(new BorderLayout());
frames[2].setLayout(new FlowLayout());
frames[2].setResizable(true);
frames[2].setSize(750,433);
label[4] = new JLabel (" Search : ", JLabel.CENTER);
label[4].setFont(new Font("Serif", Font.ITALIC, 16));
label[4].setForeground(Color.BLACK);// font color
frames[2].add(label[4]);
TextField[2]= new JTextField ("Enter name", 15);
TextField[2].setFont(font);
frames[2].add(TextField[2]);
This is the frame (frame[2]) that I would like the scrollbar to be used in.
The default JLabel draws its text at the middle of its bounds. For example, if height of the label is 20, font height is 14, the Y coordinate would be (20 - 14)/2 = 3. Like this:
What should I do if want to align the text to the TOP of the JLabel bounds? Like this:
UPD:
public class LabelTest extends JFrame {
public LabelTest() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));
contentPanel.add(Box.createHorizontalStrut(10));
final JLabel label1 = new JLabel("JLabel");
label1.setVerticalAlignment(SwingConstants.TOP); // by the answer of Kevin Workman, doesn't help
label1.setBorder(BorderFactory.createLineBorder(Color.RED));
label1.setFont(new Font("Arial", Font.PLAIN, 14));
contentPanel.add(label1);
setContentPane(contentPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LabelTest();
}
});
}
}
You should be packing the frame. If you so this, there should be no unused space in the label. If you want empty space, use an empty border
label.setBorder(new EmptyBorder(0, 0, 5, 0));
top, left, bottom, right
Also, don't set sizes, Use Layout Mangers and let them do the sizing for you. Setting sizes will give you. Setting sizes will give you a rigid look that may look and perform differently on different platforms. Layout Managers will allow your GUI to be more fluid and adaptable to different environments.
See Laying out Components Within a Container for more information on working with layouts
Also see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
As always, the API is your best friend: http://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html#setVerticalAlignment(int)
Edit- Based on your updated SSCCE, the problem is that your BoxLayout is shrinking the JLabel as small as it will go, so the vertical text position doesn't really matter. Try using a BorderLayout to check that.
The problem is that the insets of the JLabel are adding a small space to the top and bottom of the JLabel, so your text looks centered even though it's at the top. Here's a fix for the insets problem: How to change gap in swing label