JTextArea default font very small in Windows - java

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.

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();
}
});
}
}

Eclipse project wont run

I'm new to eclipse and java, I'm trying to switch between two panels with the use of a button. i want to test my project but when i try to run it it launches, gives no errors and then nothing happens.
Have i missed something that i need to do before to make this run?
This is the version i have and i downloaded it earlier today.
Eclipse IDE for Java Developers
Version: 2019-09 R (4.13.0)
Build id: 20190917-1200
And below is my code if there is anything stopping it from working in there.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Music_Test {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Music_Test window = new Music_Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Music_Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel Menu = new JPanel();
Menu.setBounds(6, 6, 438, 266);
frame.getContentPane().add(Menu);
Menu.setLayout(null);
Menu.setVisible(true);
JPanel Select_Level = new JPanel();
Select_Level.setBounds(6, 6, 438, 266);
frame.getContentPane().add(Select_Level);
Select_Level.setVisible(false);
JButton btnSelectLevel = new JButton("Select Level");
btnSelectLevel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.setVisible(false);
Select_Level.setVisible(true);
}
});
btnSelectLevel.setBounds(158, 45, 117, 29);
Menu.add(btnSelectLevel);
JLabel lblMenu = new JLabel("Menu");
lblMenu.setFont(new Font("Comic Sans MS", Font.BOLD, 22));
lblMenu.setBounds(187, 17, 61, 29);
Menu.add(lblMenu);
JLabel lblSelectLevel = new JLabel("Select Level");
lblSelectLevel.setFont(new Font("Comic Sans MS", Font.BOLD, 22));
lblSelectLevel.setBounds(187, 17, 61, 29);
Select_Level.add(lblSelectLevel);
}
}
Start by using a different layout manager, FlowLayout or GridBagLayout might work better
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
These layouts will honour the preferred sizes of your buttons
As for opening another window, well, you've already create one, so the process is pretty much the same. Having said that, you might consider having a look at The Use of Multiple JFrames: Good or Bad Practice? before you commit yourself to far.
A better approach might be to use a JMenuBar and JMenuItems to act as the "open" and "exit" actions. Take a look at How to Use Menus then you could use a CardLayout to switch between views instead, for example
From a pure design perspective (I know it's only practice, but perfect practice makes perfect), I wouldn't extend anything from JFrame and instead would rely on building your main GUIs around something like JPanel instead.
This affords you the flexibility to decide how to use these components, as you could add them to frames, applets or other components...
AND
Although you have implemented the actionPerformed method as per the ActionListener interface, you class is not of that that type as you haven't implemented the interface. Once you implement that interface and register it with the JButton btnAdd,
btnAdd.addActionListener(this);
the method will be called.
A more compact alternative might be to use an anonymous interface:
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle button ActionEvent & display dialog...
}
});
Side notes:
Using more than one JFrame in an application creates a lot of overhead
for managing updates that may need to exist between frames. The
preferred approach is to use a modal JDialog if another window is
required. This is discussed more Here

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());

Setting font in JOptionPane without using HTML

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.

How to create formatted text to show in a Java Swing Component (JTextPane, JEditorPane...)

I've searched and researched in everywhere I could to find an answer with no result. So I ask for help once more.
I want to show formatted text in a desktop java swing application. This text would be programactly generated in base of some variable objects and wouldn't be editable.
I don't know if is best to use JTextPane, or JEditorPane, or what. The matter is that I don't find anywhere some manual or tutorial that explain how to use them. Do I have to create an HTMLDocument to insert the text? How do I create it?...
Is is the right way to show text in this case?, or may I go using tables or labels or something like that.
I need some advice from you please, if there is some where I could learn how to do it, tell me please.
Here have a look at this code example, if you want to modify this a bit more, add Font too as an argument and use that appropriate argument at the specified location. Write something in the JTextField and press ENTER several times.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame {
private JPanel topPanel;
private JTextPane tPane;
private JTextField tfield;
private int counter;
private Color[] colours = {
Color.RED,
Color.BLUE,
Color.DARK_GRAY,
Color.PINK,
Color.BLACK,
Color.MAGENTA,
Color.YELLOW,
Color.ORANGE
};
public TextPaneTest() {
counter = 0;
}
private void createAndDisplayGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));
tPane = new JTextPane();
tPane.setBorder(eb);
tPane.setMargin(new Insets(5, 5, 5, 5));
JScrollPane scroller = new JScrollPane();
scroller.setViewportView(tPane);
tfield = new JTextField();
tfield.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
counter++;
if (counter == 8)
counter = 0;
String text = tfield.getText() + "\n";
appendToPane(tPane, text, colours[counter]);
tfield.selectAll();
}
});
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(tfield, BorderLayout.PAGE_END);
setSize(200, 100);
setVisible(true);
tfield.requestFocusInWindow();
}
private void appendToPane(JTextPane tp, String msg, Color c) {
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
int len = tp.getDocument().getLength();
tp.setCaretPosition(len);
tp.setCharacterAttributes(aset, false);
tp.replaceSelection(msg);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TextPaneTest().createAndDisplayGUI();
}
});
}
}
I've searched and researched in everywhere I could to find an answer with no result. So I ask for help once more.
everything is described with required details in the Oracle How to Use Editor Panes and Text Panes, including support for styled text
Do I have to create an HTMLDocument to insert the text? How do I create it?...
not you don't need to create a HTML contens, about HTML is Oracle tutorial How to Use HTML in Swing Components
Is is the right way to show text in this case?, or may I go using tables or labels or something like that.
for styled text is JEditorPane / JTextPane best of the choices
examples in the tutorial or here

Categories