java text in textfield messing up - java

[UPDATE] i fixed the problem. user "Hovercraft Full Of Eels" was right, i changed 3D graphics settings prefer to nvidea driver and problem fixed
i have problem and can't understand what is matter.
i am creating simple GUI window and putting JTextField object on it.
when i run project and enter text in text field it does not displays properly.
i already tryed to reinstal java, but can't fix problem.
can anyone help me?
here is my GUI window image
here is my code (no exception thrown, nor error was occured!)
package test;
import javax.swing.*;
import java.awt.*;
public class MainClass {
public static void main(String[] args) {
new Form().Run();
}
}
class Form{
JFrame form = new JFrame();
JButton btn = new JButton();
JTextField txt = new JTextField();
public Form(){
form.setLayout(new FlowLayout());
form.setSize(500, 500);
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn.setText("caption");
form.add(btn);
txt.setColumns(10);
form.add(txt);
}
public void Run(){
form.setVisible(true);
}
}

Try to change your "Look and Feel" settings in your GUI-Class, there should be the string "Nimbus". Change it to "Windows" and try it again. The second thing you can try is to set a Border to your JTextfield, probably it works.
The code for changing or to set a Border on your JTextfield:
JTextField your_field = new JTextField(10);
your_field.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.black));

Related

Java Swing adding a JButton to a JFrame doesn't work

I have been coding with Swing for a long moment in windows and when I switched to Manjaro Linux, something as basic as adding a JButton to a JFrame wouldn't work. (Also I have no output in the console, no missing libraries only a blank window).
Can someone help me figure this out?
Here is the code:
package test;
import javax.swing.JButton;
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
JFrame window = new JFrame();
JButton button = new JButton("My button");
window.setSize(600,600);
window.setVisible(true);
window.add(button);
}
}
As mentioned in a comment:
window.setSize(600,600);
window.setVisible(true);
window.add(button);
Should instead be
window.add(button);
window.pack();
window.setVisible(true);
Always add all the components before setting the window visible.
window.setSize(600,600); is no better than a guess, whereas window.pack(); makes the window the size it needs to be.
This is the code used for the above screenshot. Further details in code comments.
import java.awt.Insets;
import javax.swing.*;
public class DisplayButton {
public static void main(String[] args) {
JFrame window = new JFrame();
JButton button = new JButton("My button");
// This is a random guess as to how big the window should be. DON'T GUESS
//window.setSize(600,600);
// The button should be added before the frame is packed to size and displayed
window.add(button);
// But since you want it BIG, let's make it so,
// usefully by first increasing the text size
button.setFont(button.getFont().deriveFont(60f));
// Then add a chunk of insets - adjust to need.
button.setMargin(new Insets(20, 100, 20, 100));
// Make the window the size it NEEDS to be to display the button.
window.pack();
window.setVisible(true);
}
}

Java doesn't recognize equal sign

I have this piece of my code that doesn't work, it refuses to recognize the equal sign, it says error: '(' or '[' expected new newframe = new frame(); with an up arrow pointing to the = sign. However, even when I put in the ( and [, it still doesn't work. I am unsure what to do as I've never encountered this issue before. Any type of advice would be greatly appreciated, the full code is below. I am still very new to java so forgive me if this is something simple that I missed, I couldn't find any info elsewhere that helped me really. Thank you for any help
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class LoginFrame extends JFrame implements ActionListener {
Container container=getContentPane();
JLabel userLabel=new JLabel("USERNAME");
JLabel passwordLabel=new JLabel("PASSWORD");
JTextField userTextField=new JTextField();
JPasswordField passwordField=new JPasswordField();
JButton loginButton=new JButton("LOGIN");
JButton resetButton=new JButton("RESET");
JCheckBox showPassword=new JCheckBox("Show Password");
LoginFrame()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
}
public void setLayoutManager()
{
container.setLayout(null);
}
public void setLocationAndSize()
{
userLabel.setBounds(50,150,100,30);
passwordLabel.setBounds(50,220,100,30);
userTextField.setBounds(150,150,150,30);
passwordField.setBounds(150,220,150,30);
showPassword.setBounds(150,250,150,30);
loginButton.setBounds(50,300,100,30);
resetButton.setBounds(200,300,100,30);
}
public void addComponentsToContainer()
{
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(resetButton);
}
public void actionPerformed(ActionEvent e) {
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = userLabel.getText();
String ppaswd = passwordLabel.getText();
if(puname.equals("teacher") && ppaswd.equals("123"))
{
new newframe = new frame();
frame.setVisible(true);
dispose();
}
else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
userLabel.setText("");
passwordLabel.setText("");
userLabel.requestFocus();
}
}
});
}
}
It looks like your problem is here.
new newframe = new frame();
Did you mean to do this instead?
JFrame newframe = new JFrame();
If so, then I will break this down into parts, just to explain what is going on.
JFrame newframe -- This tells java that you have a variable called newframe that can only be a type of JFrame. Right now, newframe does NOT have a value, it's just an empty box that can hold a JFrame if you give it one.
= new JFrame(); -- This tells java that NOW you want to give the variable newframe a new JFrame. Remember, up until this point, newframe was an empty box. But this piece of code's job is to actually put a JFrame into that box.
Let us know if that solves your problem.
Just from looking at it, I'm pretty sure it's the way you're declaring it.
In Java, you only use the "new" keyword on the right side of the declaration.
Instead of new newframe = new frame();
Try the line frame newframe = new frame();
If that's not it, I'm not really sure. Let me know though, and I'll actually boot it up and give it a spin.
new keyword is used in Java to create an instance of a class. This instance can then be assigned to a variable that has a type that is compatible with the class for which the instance was created.
For example, in your code, with new frame() you are creating an object of type frame. You want to assign this object to a variable probably, in which case, the correct way to do that will frame someVariable = new frame()

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

How to proceed game dialogue by pressing a button?

I am trying to make a text-based RPG and have a question about how to proceed the story dialogue (I'm still quite new to Java).
I want to change the content of text area by pressing a button so the dialog continues everytime you press the button.
For example, if there's a dialog like this,
Hello. I have never seen your face before.
You look like an adventurer.
So you also came to kill that wizard?
I want to display these texts one by one, not at once.
Here's my code:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import java.awt.Container;
import javax.swing.*;
public class Dialogue extends JFrame implements ActionListener
{
//Window
JFrame window;
Container con;
//Font
Font basicfont;
Font bigfont;
Font timesnewroman;
//Main game screen
JPanel storyP;
JPanel inputP;
JPanel enterP;
//Main game screen Panel 3
JTextArea storyT;
//Main game screen Panel 5
JLabel inputA;
JTextField input;
JButton enterB;
public static void main(String[]args)
{
Dialogue game = new Dialogue();
game.setup();
}
public void setup()
{
window = new JFrame();
window.setBounds(0,0,1200,950);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(null); //Disabling the default layout.
window.setVisible(true);
basicfont = new Font("MS Gothic", Font.PLAIN, 24);
bigfont = new Font("MS Gothic", Font.BOLD, 28);
con = window.getContentPane();
// Panel Setup
storyP = new JPanel(); //This is where story text is displayed.
storyP.setBounds(50, 500, 800, 320);
storyP.setBackground(Color.white);
storyP.setLayout(new GridLayout());
inputP = new JPanel();
inputP.setBounds(50, 830, 500, 50);
inputP.setBackground(Color.black);
inputP.setLayout(new BorderLayout());
//p5.setLayout(new GridLayout());
enterP = new JPanel();
enterP.setBounds(600, 830, 120, 50);
enterP.setBackground(Color.black);
//STORY TEXT SETUP
storyT = new JTextArea();
storyT.setFont(basicfont);
storyT.setBackground(Color.black);
storyT.setForeground(Color.white);
storyT.setEditable(false);
//INPUT BOX SETUP
inputA = new JLabel(">");
inputA.setBackground(Color.black);
inputA.setForeground(Color.white);
inputA.setFont(bigfont);
input = new JTextField(15);
input.setBackground(Color.black);
input.setForeground(Color.white);
input.setBorder(null);
input.setFont(bigfont);
input.addActionListener(this);
enterB = new JButton("ENTER");
enterB.setFont(timesnewroman);
enterB.addActionListener(this);
//ADDING
storyP.add(storyT);
inputP.add("West",inputA);
inputP.add(input);
enterP.add(enterB);
//VISIBILITY
con.add(storyP);
con.add(inputP);
con.add(enterP);
Opening();
}
public void Opening()
{
storyT.setText("Hello. I have never seen your face before.");
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==enterB)
{
storyT.setText("You look like an adventurer.");
}
}
}
I could change the text from "Hello. I have never seen your face before" to "You look like an adventurer" by pressing ENTER button that I created.
But I don't know how to go further(to display "So you also came to kill that wizard?") from this point since my ENTER button's action is assigned to display a specific text ("You look like an adventurer").
I don't even know where to write the 3rd line so it is not written in this code yet.
There could be a counter and a loooong switch:
counter++;
switch(counter){
case 0: storyT.setText("You look like an adventurer.");
case 1: storyT.setText("So you also came to kill that wizard?");
case 2: ....
}
But it will be quite bad if you will have hunderds of texts.
For this i would use array of Strings or an ArrayList. then you can use counter to get to index of text to print
It will be much better if you will have these texts in a file. Than you can read it line by line with Scanner class.
Scanner sc = new Scanner(new File("texts.txt"));
ArrayList<String> texts = new ArrayList<String>();
while(sc.hasNextLine())
text.add(sc.nextLine());
sc.close();
it throws FileNotFoundException I think
Than your linstener content could be:
storyT.setText(texts.get(counter++));
The variable texts should be declared as an instance variable, not in method body:
private ArrayList<String> texts;
....
....
....
texts=new ArrayList<String>();
In your case, I'd do this...
declare a Stack.
Stack<String> texts = new Stack<String>();
A stack is like a physical stack. It has two main methods. Push(String a) and pop(). Push will put a String on top of the stack and pop() will return the String that is on the bottom.
In your main method, you simply fill this stack with the texts you want.
e.g.
texts.push("you look like an adventurer");
texts.push("etc..");
texts.push("etc..");
then, in you actionlistener, you just do this instead of what you had:
storyT.setText(texts.pop());
if you want some safety measures, you can do this:
if (texts.hasnext())
storyT.setText(texts.pop());
This checks if the stack still has texts stored up in it. If not, the stack won't be popped, in which case you'll get null, which isn't good.

Java, NetBeans IDE and JTextField

it's a shame that my first question on SO is so stupid but i can't manage to get around this thing.
After hours of "distilling" i have reduced the issue to this:
Using Netbeans i've made a JFrame, and put a Jbutton1 and a JTextField(named sinonimo) in it.
The idea is to use the text field to grab user input. so i set the onClick action of the button like this
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
System.out.println(sinonimo.getText());
}
Problem is: i can type anything in the text field, the getText() method will return only the string set in the "text" properties in Netbeans, it will never change.
Am i missing something huge about java? can someone point me in the right direction?
EDIT: while copying the complete code i found the problem: in the constructor of the frame, initComponents() was called two times, generating another copy of the textfield inaccessible from the MouseClicked event(i think). Now everything seem to work nicely, thank you guys for the lighting responses!
Using a JTextField, if you call getText() it will return null should the index be out of range or the Document is null. If you could post more code I could help further with this issue. With the following code this works perfectly fine.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test {
public static void main(final String[] args) {
final JFrame frame = new JFrame();
final JButton button = new JButton("Print");
final JTextField field = new JTextField();
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH);
frame.add(field, BorderLayout.SOUTH);
frame.setVisible(true);
frame.pack();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(field.getText());
}
});
}
}
From what I can see, until you post more code, is that either the method you print it from is not being used, the document is returning null or that the sinonimo instance was not added correctly and doesn't function how it should.

Categories