Setting font in JOptionPane without using HTML - java

I tried this: Code Zip
Sorry for the inconvenience but I could not attach the whole code (though it's not too big) and could not provide .java extension link so you have to get the zip and it open in html where code is with syntax highlighting.
I read these:
Java GUI - JOptionPane/JDialog customization issue
How to make font bold in java dialogue box?
But I don't want to use HTML.
Code
public static void main(String argv[]) {
JFrame jf;
jf = new JFrame();
JPanel jp = new JPanel();
jf.setBounds(100, 100, 530, 350);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().setLayout(null);
jp.setFont(new Font("Algerian", Font.ITALIC, 11));
jf.add(jp);
String message = "Hello World!”;
JOptionPane jop;
jop = new JOptionPane();
Object[] obj = { UIManager.put("Panel.font",new Font("Algerian", Font.ITALIC, 11)) , message };
JOptionPane.showMessageDialog(jp,obj,"Dialog",JOptionPane.NO_OPTION);
}

This MCVE shows one label in 3 option panes with 3 different variants of the same (default) font. It is simply a matter of passing the option pane a component that has the font set, as opposed to a string or a generic object.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class FontInOptionPane {
FontInOptionPane() {
JLabel l = new JLabel();
Font f = l.getFont();
l.setText(f.toString());
JOptionPane.showMessageDialog(null, l);
f = f.deriveFont(Font.ITALIC);
l.setText(f.toString());
l.setFont(f);
JOptionPane.showMessageDialog(null, l);
f = f.deriveFont(50f);
l.setText(f.toString());
l.setFont(f);
JOptionPane.showMessageDialog(null, l);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new FontInOptionPane();
}
};
SwingUtilities.invokeLater(r);
}
}

In Java Swing, you globally set your JOptionPane font by using the following code lines:
UIManager.put("OptionPane.messageFont", new Font("Arial", Font.PLAIN, 15));
UIManager.put("OptionPane.buttonFont", new Font("Arial", Font.PLAIN, 18));
This works like a charm.

Related

How can I start a newline in a JPanel when the added text are two different font sizes

So I am creating a project that is a skeleton of a Java GUI but I am having some alignment issues. When I run my code the centered top text that says "Help Page" is pushed to the left side, while the help string is shifted downwards a little bit but also pushed to the right.
My goal is to have the top text centered and underlined with the other text below it and also centered. I have tried using multiple panels but still nothing has worked, Im guessing it's the mismatching font size by I dont know. Any help is appreciated!
private void helpGUI() {
clearGUI();
helpStr = "<html><br>This is the help page where the user can come for help<html/>";
label = new JLabel("<html><u>Help Page</u></html>");
label.setFont(new Font("Times", Font.PLAIN, 24));
helpTxt = new JLabel(helpStr);
helpTxt.setFont(new Font("Times", Font.PLAIN, 16));
panel.add(label);
panel.add(helpTxt);
panel.setAlignmentX(CENTER_ALIGNMENT);
button = new JButton("Previous");
bttnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
bttnPanel.add(button);
frame.add(panel);
class previousButton implements ActionListener {
public void actionPerformed (ActionEvent e) {
GUIPG1(name);
}
}
button.addActionListener(new previousButton());
}
It really depends on what you are trying to achieve (for instance, what other components is that JPanel supposed to contain. Is it just those two labels? You show a button in your code as well. Where is that supposed to be added?). Regardless, for that specific panel with the two texts on the top, you could use BoxLayout for adding your JLabels vertically, and use setAlignmentX() to set the horizontal alignment of the texts. Example below:
Edit:
Alternatively (regarding underlying and centering the text), you can use the following in the example below:
titleLbl = new JLabel("<html><u>Help Page</u></html>", SwingConstants.CENTER);
titleLbl.setFont(new Font("Times New Roman", Font.PLAIN, 24));
titleLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
App.java
import java.awt.*;
import java.awt.font.*;
import javax.swing.*;
import java.util.*;
public class App {
private void addComponentsToPane(Container pane) {
JLabel titleLbl = new JLabel("Help Page");
// add text attributes (i.e., underline, font family, font size, etc)
Font font = titleLbl.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
attributes.put(TextAttribute.FAMILY, "Times New Roman");
attributes.put(TextAttribute.SIZE, 24);
titleLbl.setFont(font.deriveFont(attributes));
titleLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
JLabel infoLbl = new JLabel("This is the help page where the user can come for help");
infoLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
infoLbl.setFont(new Font("Times New Roman", Font.PLAIN, 16));
Box box = new Box(BoxLayout.Y_AXIS);
box.add(titleLbl);
box.add(Box.createRigidArea(new Dimension(0, 5)));// creates space between the JLabels
box.add(infoLbl);
pane.add(box, BorderLayout.NORTH);
}
private void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.setSize(640, 480);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new App().createAndShowGUI();
}
});
}
}

java; TextField wont go Under the JLabel

NOTE: My English isn't the best so Please Don't mind too much Grammar Mistakes.
Hey there, Java Starter here, Anyways i was Testing a mini "beta" version of the Program i'm planning to code, So i made a TextField And it wont go Under my JLabel i made, i tried to use BorderLayout.PAGE_END to get it under / at the bottom but it won't get it. Here's the Code:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextTest {
private static TextField field;
private static void createGUI() {
Font a = new Font(null, Font.BOLD, 0);
Font size = a.deriveFont(20f);
JLabel test = new JLabel("");
test.setPreferredSize(new Dimension(200,200));
test.setText("<html> Welcome to the EMOJI Translator! Type the <br> Emoji in the Text Area And hit Enter! and it will say What the emoji means! <html>");
test.setFont(size);
field = new TextField(2);
field.setSize(new Dimension(200,200));
field.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String test = field.getText();
String search1 = ":D";
if(test.equals(search1)) {
System.out.println("This is an Happy Smiley.");
}
}});
JFrame b = new JFrame("TEST");
b.setLocationRelativeTo(null);
b.setPreferredSize(new Dimension(350,350));
b.setLayout(new FlowLayout());
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.getContentPane().add(field, BorderLayout.PAGE_END);
b.getContentPane().add(test, BorderLayout.CENTER);
b.pack();
b.setVisible(true);
}
public static void main(String[] args) {
createGUI();
}
}
Here's a Link to the screenshot of how it ended looking in my Computer:
http://imgur.com/y988zUx
If you know Whats wrong please respond to this question.
You are trying to use properties of BorderLayout for a gui make with FlowLayout. In Java, you cannot mix different layout managers, by doing this the layout properties will be ignored.
You should set you layout manager to BorderLayout, so it accepts your properties:
b.setLayout(new BorderLayout());

JTextArea default font very small in Windows

I'm using platform look-and-fell and on Linux my JTextArea is pretty readable
But on Windows it uses "Monospaced 9" and the text is very small.
Why and what is the best way to fix that?
Why default Windows look-and-fell uses such small font in JTextArea?
Instead of creating new font, it is better to derive existing font, because this way you'll save the font set by platform look and feel, and it may also avoid problems with unicode characters:
textArea.setFont(textArea.getFont().deriveFont(12f)); // will only change size to 12pt
Here's a solution that you can use to change all JTextAreas at once instead of using setFont() every time you add new text area:
UIManager.getDefaults().put("TextArea.font", UIManager.getFont("TextField.font"));
Call this on start of your application, after setting the Look and Feel.
Most L&Fs use the same font for JTextArea and JTextField, it's strange that Windows doesn't.
If you want a consistent look then use the Nimbus or Metal look and feel instead of the OS default. That will also allow you to tweak any settings. Plus I personally I think the Nimbus Look and Feel is much smoother looking than the others.
I've just used TextField font in TextArea...
textArea = new JTextArea();
textArea.setFont(UIManager.getFont("TextField.font"));
You can use the JTextArea1.setFont(Font(String name, int style, int size)) method to specify the specific type of font for a JTextArea component. As an example
jTextArea1.setFont(new Font("Arial Black", Font.BOLD, 8));
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
public class NewJFrame extends javax.swing.JFrame {
private JTextArea jTextArea1;
private JTextArea jTextArea2;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
NewJFrame inst = new NewJFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public NewJFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
jTextArea1 = new JTextArea();
getContentPane().add(jTextArea1, BorderLayout.NORTH);
jTextArea1.setText("This is a fox running slow");
jTextArea1.setFont(new Font("Arial Black", Font.BOLD, 8));
jTextArea1.setPreferredSize(new java.awt.Dimension(164, 114));
}
{
jTextArea2 = new JTextArea();
getContentPane().add(jTextArea2, BorderLayout.SOUTH);
jTextArea2.setText("This is a fox running slow");
jTextArea2.setFont(new Font("Book Antiqua", Font.ITALIC, 12));
jTextArea2.setPreferredSize(new java.awt.Dimension(384, 129));
}
pack();
setSize(400, 300);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
}
Just do
textArea.setFont(new Font("Arial", Font.PLAIN, 16));
That changes all of the text inside of the textarea to the same size font.

how to add labels without them overlapping each other

I wanted to add 2 labels in my JDialog; one label will have animated gif ; other will have text. How to add these two so that they dont overlap? I don't want to hardcode their positions. I want the program to make the inherent adjustments.
Thanks in Advance
code:
JLabel l2=new JLabel("");
try {
Image img = ImageIO.read(getClass().getResource("resources/wait_animated.gif"));
ImageIcon imgnew=new ImageIcon("G:\\my java\\DesktopApplication1\\src\\desktopapplication1\\resources\\wait_animated.gif");
l2.setIcon(imgnew);
imgnew.setImageObserver(l2);
}
catch (IOException ex) {
}
l2.setLocation(300,300);
JDialog d=new JDialog();
JLabel l=new JLabel("Please Wait While Processing is Done... ");
JDesktopPane dp=new JDesktopPane();
dp.setPreferredSize(new Dimension(300,50));
l.setPreferredSize(new Dimension(250,50));
l2.setPreferredSize(new Dimension(20,20));
d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
d.setTitle("Wait dialog");
d.add(l);
d.add(l2);
Use a LayoutManager (such as FlowLayout) to arrange your labels. It’s hard to say without any more details.
You do realize that one label can have both text and an image, right? E.G.
import javax.swing.*;
import java.net.URL;
class AnimatedGifInLabelWithText {
public static void main(String[] args) throws Exception {
final URL url = new URL("http://pscode.org/media/starzoom-thumb.gif");
Runnable r = new Runnable() {
public void run() {
ImageIcon ii = new ImageIcon(url);
JLabel label = new JLabel("Zoom!", ii, SwingConstants.CENTER);
JOptionPane.showMessageDialog(null, label);
}
};
SwingUtilities.invokeLater(r);
}
}

Change Swing L&F at command line not work well

I made an application with some widgets and at command line I want change their look and feel:
java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel LookAndFeelAppl
but after invoked that command only a widget into the class constructor change its L&F but other that I created into a separate methods don't!!! Also tha JFrame itself not change.
public class LookAndFeelAppl extends JFrame
{
private JLabel label;
private JButton button;
public LookAndFeelAppl()
{
super("Look And Feel Demo");
setLayout(null);
final UIManager.LookAndFeelInfo plaf[] = UIManager.getInstalledLookAndFeels();
JLabel lable_laf = new JLabel("Choose L&F:");
final JComboBox cb = new JComboBox();
createOtherGUI();
cb.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
int ix = cb.getSelectedIndex();
try
{
UIManager.setLookAndFeel(plaf[ix].getClassName());
SwingUtilities.updateComponentTreeUI(LookAndFeelAppl.this);
}
catch (Exception ex)
{
}
}
});
// HERE IS THE PROBLEM!!!! THIS LOOP GOES BEFORE
// THE ITEMLISTENER BECAUSE WHEN I ADD ITEMS AN ITEMEVENT
// IS RAISED THAT SET AGAIN THE L&F WITH setLookAndFeel!!!
for (int i = 0, n = plaf.length; i < n; i++)
{
cb.addItem(plaf[i].getName());
}
//--------------------------------------------------------
add(lable_laf);
add(cb);
lable_laf.setBounds(10, 10, 150, 25);
cb.setBounds(10, 35, 150, 25);
}
public void createOtherGUI()
{
button = new JButton("BUTTON!!!!");
add(button);
button.setBounds(300, 45, 150, 35);
}
public static void main(String args[])
{
LookAndFeelAppl window = new LookAndFeelAppl();
window.setSize(1000, 700);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setLocationRelativeTo(null);
}
}
I ran this in Eclipse (latest version) using JDK 1.6.0_13 on windows. In the run configuration (VM arguments) of Eclipse I used -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel
public class Test extends JFrame {
public Test() {
super("Test L&F");
JComboBox box = new JComboBox(new String[] {"One", "Two", "Three"});
getContentPane().add(box, BorderLayout.SOUTH);
createControls();
setSize(300, 300);
setVisible(true);
}
private void createControls() {
JComboBox box = new JComboBox(new String[] {"One", "Two", "Three"});
getContentPane().add(box, BorderLayout.NORTH);
}
public static void main(String[] args) {
new Test();
}
}
Sorry, formatting is weird but you get the idea...
Few things to try and questions:
I see you are setting the L&F for windows, so I'm assuming you are running this on a windows box? The reason I ask is I'm not sure what the JDK is supporting as far as cross-platform L&Fs, just something to think about.
Did you try other L&Fs with the same result? (e.g. Nimbus)
This may or may not do anything but where do you have main(...)? Try putting it in the JFrame and in a separate class that constructs the JFrame.
Worst comes to worse you could always pass the L&F classname in as an arg to main(...) (or a props file) then use the UIManager to set it BEFORE any swing components are created.
Good luck,
Dave

Categories