Change font of a part of a JLabel? - java

I want to change only the first two words of a JLabel to a different font than the rest of the JLabel. I have found that I could make a JPanel, and have two JLabels with different fonts in it. I cannot use this way, because I can only have one JLabel (This is since I have a mouse listener which changes the text of that JLabel based on entrance or exit of different other JLabels, which are in a seperate JPanel). Is there any way? I have tried this (adding a JLabel side by side to another JLabel):
JLabel Giraffesays = new JLabel("Giraffe says:");
Giraffesays.setFont(new Font("TimesRoman", Font.BOLD, 60));
status.setText(Giraffesays +"Hi!"); //status is a JLabel
but this didn't work. I also tried making it a string:
String Giraffesays = "Giraffe says:
Giraffesays.setFont(new Font("TimesRoman", Font.BOLD, 60));
status.setText(Giraffesays +"Hi!"); //status is a JLabel
But you cannot change the font of a String...

Try using HTML String with JLabel:
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override public void run() {
JFrame frm = new JFrame("Text formatting");
frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
String giraffesays = "<html><span style=\"font-family:Arial;font-size:13px;\">Giraffe says :</span>Hi there!</html>";
frm.getContentPane().add(new JLabel(giraffesays));
frm.pack();
frm.setLocationByPlatform(true);
frm.setVisible(true);
}
});
}
}
This is the line with the error
String giraffesays = "<html><font size="6"><span style=\"font-family:Arial;\">Giraffe says :</font></span></html>";
Problem is you need to escape the quotes size=\"6\".

Two approaches would be:
use two separate JLabels
JComponent supports HTML, so you could simply use font tags to change the appeareance of the text. http://docs.oracle.com/javase/tutorial/uiswing/components/html.html

Related

Fixed height and width for JTextField

I've been working with Java Swing recently and when I try to add 3 JTextFields beneath each other they fill out the whole JFrame. But I want them to have a fixed height and width. What can I do?
Since I'm new to this topic I wasn't able to try out many things. I haven't found anything in other forums either.
My goal was to make a simple GUI for Users to fill in their credentials. Those credentials should be filled into an array but I haven't got there yet.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PeopleGUI extends JFrame{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField(30);
JTextField jt1 = new JTextField(30);
JTextField jt2 = new JTextField(30);
JButton jb = new JButton("Enter");
public PeopleGUI(){
setTitle("PeopleGUI");
setVisible(true);
setSize(400,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
jp.add(jt);
jp.add(jt1);
jp.add(jt2);
jt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String input = jt.getText();
jl.setText(input);
}
});
jp.add(jb);
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String input = jt.getText();
jl.setText(input);
}
});
jp.add(jl);
add(jp);
}
public static void main(String[] args) {
PeopleGUI p = new PeopleGUI();
}
}
I expect JTextFields that don't adjust to the size of the window.
Currently, it is looking like this:
.
But it should rather look like:
.
That layout is easily reproduced by putting 3 panels, each with a centered FlowLayout, into a single column GridLayout.
The important part is the FlowLayout, which will respect the preferred size of the components it is displaying.
Combinations of different layouts are often used when making a GUI. The idea is for each to handle a small part of the layout needs of the entire user interface. Here is a screenshot from that answer which lists the layouts used, by way of titled borders for each one.
But I think it would be better if the RHS of the label and the LHS of the fields are aligned vertically. To do that, use a single GridBagLayout.
You have to use a Layout e.g. BoxLayout. You will find some documentation here

Can not display the features using JFrame [duplicate]

I'm fairly new to JFrame and I want to know why my items are not showing up on the window. I know i dont have a ActionHandler but I just want my textfield's to show up on my window. Here's my code:
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FirstGUI extends JFrame{
public void GUI(){
setTitle("Welcome");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(600,600);
JLabel title = new JLabel();
title.setText("Apple Inc. Member Login Port");
title.setFont(new Font("Arial", Font.PLAIN, 24));
JTextField login = new JTextField("Login",10);
JPasswordField pass = new JPasswordField("Password");
add(title);
add(login);
add(pass);
}
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
}
}
but when i run it i get this:
but when i run it i get this:
You get an empty screen because you add the components to the frame after the frame is visible.
As has already been suggested you need to use an appropriate layout manager. FlowLayout is the easiest to start with.
invoke setVisible(true) AFTER adding the components to the frame.
So the code should be more like:
panel.add(...);
panel.add(...);
add(panel);
pack();
setVisible(true);
I agree to MadProgrammer's suggestions (+1)
Well, lets take a look at your program though
You actually have created a JFrame with components in it. Its working fine as well, but your question of "why are my items not showing up in the JFrame" is not because you did something wrong but because missed out something i.e. revalidate()
Try:
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
a.revalidate();
}
I'm not saying this will give you perfect UI.. what I'm trying to say is this will help you understand the Swing better. Learn about Swing Layout managers and then work on your UI to have better results
revalidate(): This component and all parents above it are marked as needing to be laid out. This means the Layout Manager will try to realign the components. Often used after removing components. It is possible that some really sharp swing people may miss this. I would think that you will only know this if you are actually using Swing.
The default layout manager for JFrame is BorderLayout.
This means that your components are essentially all been added ontop of each other.
Try changing the layout manager to something like FlowLayout (for example)...
Take a look at A Visual Guide to Layout Managers and Using Layout Managers for more details.
Also, avoid setSize where possible, use Window#pack instead
Update
I'd also like to introduce you to Initial Threads which should be used to launch your UI code...
The only one reason :
setVisible(True); method for the frame should be put on the end of the code.
if you give this line on the top of the code that is when you create a frame. This will cause that problem.
Don't add the components directly to your frame. Instead add to the content pane, which is where a JFrame stores all of the components that it draws. Usually this is a JPanel.
Here is an example:
public class GUI
{
private JPanel content;
public void GUI
{
/*Other code*/
content = new JPanel();
add(content); //make content the content pane
content.add(title);
content.add(login);
content.add(pass);
}
If that fails, call setVisible(true) and setEnabled(true) on all of your components.
On a side note you may want to make your GUI function a constructor.
import javax.swing.*;
import java.awt.*;
class Myframec extends JFrame
{
Myframec()
{
Container c = this.getContentPane();
c.setLayout(null);
this.setBounds(10,10,700,500);
this.setTitle("Welcome");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBounds(0,0,700,500);
panel.setBackground(Color.gray);
panel.setLayout(null);
c.add(panel);
Font f = new Font("Arial",Font.BOLD,25);
Font f1 = new Font("Arial",Font.BOLD,20);
JLabel lable = new JLabel();
lable.setBounds(130,10,400,100);
lable.setText("Apple Inc. Member Login Port");
lable.setFont(f);
panel.add(lable);
JTextField login = new JTextField("Login",10);
login.setBounds(120,150,400,30);
login.setFont(f1);
panel.add(login);
JPasswordField pass =new JPasswordField("Password");
pass.setBounds(120,200,400,30);
pass.setFont(f1);
lable.setFont(f);
panel.add(pass);
c.setVisible(true);
this.setVisible(true);
}
public static void main(String[] argm)
{
Myframec frame = new Myframec();
frame.setVisible(true);
}
}

Unicode text is not displayed correctly in awt Label

I have the following simple Java test program:
import java.awt.*;
public class test3 {
public test3() {
Frame f = new Frame();
f.setLayout(null);
f.setBounds(50,50, 400,400);
Label l = new Label("你好吗");
l.setBounds(10,100, 50,30);
TextField t = new TextField("你好吗",20);
t.setBounds(100,100,50,30);
f.add(l);
f.add(t);
f.setVisible(true);
}
public static void main(String[] args) {
test3 t = new test3();
}
}
The output of running this test program is 3 square boxes for the label text, and 你好吗 (how are you as in Chinese) in the text field.
TextField and Label are awt components, while there is no problem displaying unicode in the text field, not sure how to get Label to display unicode correctly.
It is most likely an issue with the font that the awt Label uses. You will need to find a font that supports UTF-8 and use that. However, if you use Swing components instead of AWT components it works fine:
import javax.swing.*;
public class Example {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(null);
f.setBounds(50,50, 400,400);
JLabel l = new JLabel("你好吗");
l.setBounds(10,100, 50,30);
JTextField t = new JTextField("你好吗",20);
t.setBounds(100,100,50,30);
f.add(l);
f.add(t);
f.setVisible(true);
}
}
Output:
Label uses a default font which not supports UTF-8. Just change the font of Label to a font which supports UTF-8.
For example you can set the same font of TextField also for Label with
l.setFont(t.getFont());
But anyway you should consider to use swing instead of awt components.

How to work with JLabel?

Hi i am trying to make java desktop application where i am using JLabel I wrote some test on JLabel I want to set text from the top and I am using multiple line in JLabel I want to set different different color for every line.
Here is my code:
JLabel label = new JLabel("<html>Case Item CaseNum<br>Party1<br>Party2</html>");
How can I achieve this?
You can try using the html tables for new lines as below,
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* #author JayaPrasad
*
*/
public class SwingHtml {
public static void main(String[] args) {
JFrame frame = new JFrame();
JLabel label = new JLabel(
"<html>Case Item CaseNum<table><tr><font color=blue>Party1</font></tr><tr><font color=red>Party2</font></tr></table></html>");
frame.add(label);
frame.setSize(new Dimension(250, 130));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
Use a JTable for this, rendered the same way as in the Nimbus PLAF.
You can do something like this:
<html><p><font color="green">line 1</font></p><br /><p><font color="red">line2</font></p></html>
if you want to change the line 1 text colour and add a new line 2 with a new colour

How to add button in text field?

I'm creating a text field in java using swing components. I want to make a search text field like one appears in Mozilla or other browsers.
I have added a button in text field. I have set border layout of JTextField. everything is working fine but whenever large text is written in text field (as it reaches the given size of text field) it goes behind the button. As everyone of you must have seen, this does not occur in search bars. Text must not go behind the button rather there must be some gap between button and text.
Does anyone know how to do that?
Maybe start with something like this:
The blinking cursor is positioned at the far right of the text field.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
class ButtonsInTextField {
JPanel gui = new JPanel(new GridBagLayout());
JTextField textField;
ButtonsInTextField(int cols) {
JPanel textFieldWithButtonsPanel = new JPanel(new FlowLayout(
SwingConstants.LEADING, 5, 1));
textField = new JTextField(cols);
textFieldWithButtonsPanel.add(textField);
addButtonToPanel(textFieldWithButtonsPanel, 8);
addButtonToPanel(textFieldWithButtonsPanel, 16);
addButtonToPanel(textFieldWithButtonsPanel, 24);
// WARNING: Not sensitive to PLAF change!
textFieldWithButtonsPanel.setBackground(textField.getBackground());
textFieldWithButtonsPanel.setBorder(textField.getBorder());
textField.setBorder(null);
// END WARNING:
gui.add(textFieldWithButtonsPanel);
}
private final void addButtonToPanel(JPanel panel, int height) {
BufferedImage bi = new BufferedImage(
// find the size of an icon from the system,
// this is just a guess
24, height, BufferedImage.TYPE_INT_RGB);
JButton b = new JButton(new ImageIcon(bi));
b.setContentAreaFilled(false);
//b.setBorderPainted(false);
b.setMargin(new Insets(0,0,0,0));
panel.add(b);
}
public final JComponent getGui() {
return gui;
}
public final JTextField getField() {
return textField;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
ButtonsInTextField bitf = new ButtonsInTextField(20);
JOptionPane.showMessageDialog(null, bitf.getGui());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
As people have noted above, it might have helped to see the code, especially the Layout manager.
However, you might try the following (if you haven't yet):
Call setColumns
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html#setColumns(int)
Call setPreferredSize /setMaximumSize/setMinimumSize depending on your layout manager.
But I'd try to avoid this solution because it's pixel-level maintenance.
Regards
As an alternative solution you can use a Component Border, which allows you to use the button as a Border so it appears within the text field.

Categories

Resources