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.
Related
I am trying to learn java,but I met some problems where finding answers is not so simply for me.
Task I wanna do seems to be quite simply.
I wanna add a label to Frame. MyFrame is a JFrame class with some basics modyfications like size, color etc.
Main code looks like this:
public class Main {
public static void main(String[] args)
{
// a GUI window to add components
MyFrame myFrame = new MyFrame();
ImageIcon image = new ImageIcon("Images/background.png");
//a GUI display area for a string of text,image or both
JLabel label = new JLabel("Why it is happening?",image,JLabel.CENTER);
myFrame.add(label);
//label.setText("Why it is happening?");// set text of label
//label.setIcon(image);
label.setHorizontalTextPosition(JLabel.CENTER);
}
}
And the result I get is this which I want:
correct result
When I comment last line about label it is changing appearance of mine UI. It is displaying only JFrame without my label at all.
Not working code:
public class Main {
public static void main(String[] args)
{
// a GUI window to add components
MyFrame myFrame = new MyFrame();
ImageIcon image = new ImageIcon("Images/background.png");
//a GUI display area for a string of text,image or both
JLabel label = new JLabel("Why it is happening?",image,JLabel.CENTER);
myFrame.add(label);
//label.setText("Why it is happening?");// set text of label
//label.setIcon(image);
//Commented
//label.setHorizontalTextPosition(JLabel.CENTER);
}
}
Here is graphic result:
not working label
Did I miss some basics information ?
I think both should work the same.
This is an interesting one. At first glance I agreed with #VGR. But then if it is all down to the order of painting etc. - then I would have expected a call to 'repaint()' or even 'invalidate()' to fix the problem. Doesn't seem like it... so perhaps this is a bug in swing.
import javax.swing.*;
public class Main
{
public static void main(String[] args)
{
// a GUI window to add components
JFrame myFrame = new JFrame();
ImageIcon image = new ImageIcon("Images/background.png");
myFrame.setSize(500,250);
myFrame.setVisible(true);
JLabel label = new JLabel("Why it is happening?", image, JLabel.CENTER);
myFrame.add(label);
//label.setHorizontalTextPosition(JLabel.CENTER);
label.repaint(); //Should have the same effect as the line above, but doesn't!
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
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
I want to know how to put put console output into a JFrame. For example, putting this output into a JFrame:
import static java.lang.System.out;
public class frame{
public static void main(String [] args){
out.println("hello");
}
}
How is it possible?
You need to set up the JFrame first.
JFrame frame = new JFrame("title");
Then, set the properties of the JFrame:
frame.setSize(1280,720); //Sets the program's size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tells the program to exit on close
frame.setResizable(true); //Tells the program if resizing is enabled
Then, create a panel to store the components:
JPanel p = new JPanel();
After that, you must add the panel to the JFrame like so:
frame.add(p);
Then, with that done, you can use the components supplied in the swing framework, and add them to the panel. A reference for these components can be found here: http://docs.oracle.com/javase/tutorial/uiswing/components/componentlist.html.
To create a component, use the following code:
JLabel label = new JLabel();
Then, use it's build in functions to change it:
label.setText("new text");
Then, once again, to add a component to a panel, use the panel's add() method:
panel.add(label);
Those are just the basics of making a GUI with java. A full tutorial can be viewed here:
http://docs.oracle.com/javase/tutorial/uiswing/
Good Luck!
I can help you with this, but let me please fix some syntax errors you have. When you put the import, an import can't be static (that I know of) and when you want to print out something using "System.out.print" or "System.out.println" you MUST include the "System" part of the line. If you want to add text to a a JFrame use the JLabel to import both just do this bit of code:
import javax.swing.*;
That should import all of your swing elements such as JLabel and JFrame and JPanel, and try this code it will make a window that will have a button and a label. The button doesn't do anything in this code:
import javax.swing.*;
public class main{
public static void main(String[] args)
{
/*
* Creates the frame, makes it visible, and makes
* appear in the center of the screen. While also making it have a close operation
*/
JFrame frame = new JFrame("Button");
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//Creates the panel, and adds it to the frame
JPanel panel = new JPanel();
frame.add(panel);
//Creates the label and adds it to the panel, also sets the text
JLabel label = new JLabel();
label.setText("Welcome" + "\n" + "\n");
panel.add(label);
//Creates the button and adds it to the panel
JButton button1 = new JButton("Button 1");
panel.add(button1);
}
}
1.If you want to use JFrame you have to extend your class to a subclass of JFrame:
public class frame extends JFrame {}
2.a)If you want to put Text in your Frame use JLabel and add it to your frame:
JLabel hello = new JLabel("Hello");
add(hello);
2.b)If you want a console output just call System.out.println() in the constructor
Here is a small example class:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Frame extends JFrame {
public static void main(String args[]) {
new Frame();
}
Frame() {
System.out.println("Hello");
JLabel hello = new JLabel("Hello");
add(hello);
this.setSize(100, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
have a look to the oracle lessons... or any java book!
If that is the case, I don't want to get into GUI just yet. (Learning from a book) Can I convert my current project to a jar file and have it automatically open a command prompt window upon double click?
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.
I'm currently doing a Java assignment as a computer science fresher. As a part of that assignment I'm trying to bring up a secondary frame that the user can write UML code into which will then be passed into my main application and then into a class diagram.
The bit that I'm stuck with is that the JTextBox that I have put into this secondary frame is the size I want it to be, however the writing starts in the middle and does not change to a new line when it gets to the other size of the frame.
This is the image of what is currently happening:
Code
And this is the code that I currently have for this class if it's needed.
package classdesign;
import java.awt.*;
import javax.swing.*;
public class ClassCreation extends JFrame {
private JFrame frame;
private JLabel instructionlabel;
private JTextField inputUML;
private JButton upButton;
private String Message;
public void ClassCreation(){
frame = new JFrame();
frame.setSize(300, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Class Design");
JPanel CreationPanel = new JPanel();
CreationPanel.setLayout(new BorderLayout());
instructionlabel = new JLabel("Fill Class details in using UML");
CreationPanel.add(instructionlabel,BorderLayout.NORTH);
inputUML = new JTextField("",20);
CreationPanel.add(inputUML,BorderLayout.CENTER);
frame.add(CreationPanel);
}
public Frame getFrame() {
return frame;
}
}
So, to summarise what I was hoping somebody could tell me how to do is to get the text input from the user to start in the top left and change to the next line when it gets to the far right, like any normal text editor etc...
use JTextPane or JEditorPane. Sample can be found at
http://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html
JTextField is a lightweight component that allows the editing of a single line of text. (source)
As it is a single-line component, whatever its size is the cursor will always be centered and will never go to the next line.
I would suggest you use a JTextArea as it is a multi-line area and allow the user to enter input as you want him to.
An example of using a text area (with a few other tips thrown in free - check the comments).
import java.awt.*;
import javax.swing.*;
// Has an instance of frame, does not need to extend it.
public class ClassCreation { //extends JFrame {
private JFrame frame;
private JLabel instructionlabel;
// as mentioned by talnicolas
private JTextArea inputUML;
// Don't give a method the same name as a class!!
//public void ClassCreation(){
public void initGui(){
frame = new JFrame();
//frame.setSize(300, 400); //pack() instead!
//frame.setLocationRelativeTo(null); // do something better
frame.setLocationByPlatform(true); // better!
//frame.setVisible(true); // do later
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Class Design");
JPanel CreationPanel = new JPanel();
CreationPanel.setLayout(new BorderLayout());
instructionlabel = new JLabel("Fill Class details in using UML");
CreationPanel.add(instructionlabel,BorderLayout.NORTH);
inputUML = new JTextArea("",7,30);
// very important next 2 lines
inputUML.setLineWrap(true);
inputUML.setWrapStyleWord(true);
// add it to a scrollpane
CreationPanel.add(new JScrollPane(inputUML),BorderLayout.CENTER);
frame.add(CreationPanel);
frame.pack(); // assume the natural size!
frame.setVisible(true);
for (int ii=0; ii<150; ii++) {
inputUML.append(SENTENCE);
inputUML.setCaretPosition( inputUML.getText().length() );
}
}
public static void main(String[] args) {
// Swing GUIs should be created and altered on the EDT.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ClassCreation cc = new ClassCreation();
cc.initGui();
}
});
}
private static String SENTENCE = "The quick brown fox jumps over the lazy dog! ";
}