How would i disable a text box? - java

SO i am working on a project and i was trying to disable the frame and the field from the program so that only the window is front is this one being active
here is my code :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class password
{
private static String password = "pass";
public static void main(String[]args) {
JFrame frame = new JFrame("Password");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,100);
JLabel label = new JLabel("Enter password");
JPanel panel = new JPanel();
frame.add(panel);
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
pass.addActionListener(new AL());
panel.add(label, BorderLayout.WEST);
panel.add(pass, BorderLayout.WEST);
}
static class AL implements ActionListener
{
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char [] passy = input.getPassword();
String p = new String(passy);
if (p.equals(password)){
JOptionPane.showMessageDialog(null, "Correct");
System.out.print("Welcome to Adam's Quirky program.");
}
else
JOptionPane.showMessageDialog(null, "Incorrect");
}
}
}
the program i am currently using to program is Eclipse.

I'd take a look at a modal dialog.
Either use a JOptionPane or roll your own.
If these don't suit your needs, try taking a look at JLayer (Java 7) or JXLayer (Java 6 and below)
Have a look at LockableUI (It's a little out of date, but the basic idea is the same)
If that doesn't appeal, you could use a "blocking glass pane"
Take a look at
glassPane is not blocking input
Is there a problem with this blocking GlassPane?
as some examples

Related

How to Add text to JTextArea

Im creating a programme using java. I want the user to enter some text, then push the button so the text entered shows in the label. However, I have 2 problems. First, the text are isn´t displaying when I execute the app. Second, I don´t know how to allow the user to type in the area. Im new in java so that´s why Im asking. Here is the code. Thank you.
import javax.swing.*;
import java.awt.event.*;
class Boton extends JFrame implements ActionListener {
JButton boton;
JTextArea textArea = new JTextArea();
JLabel etiqueta = new JLabel();
public Boton() {
setLayout(null);
boton = new JButton("Escribir");
boton.setBounds(100, 150, 100, 30);
boton.addActionListener(this);
add(boton);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == boton) {
try {
String texto = textArea.getText();
etiqueta.setText(texto);
Thread.sleep(3000);
System.exit(0);
} catch (Exception excep) {
System.exit(0);
}
}
}
}
public class Main{
public static void main(String[] ar) {
Boton boton1 =new Boton();
boton1.setBounds(0,0,450,350);
boton1.setVisible(true);
boton1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Problems:
You never add the JTextArea into your GUI, and if it doesn't show, a user cannot directly interact with it.
You are calling Thread.sleep on the Swing event thread, and this will put the entire application to sleep, meaning the text that you added will not show.
Other issues include use of null layouts and setBounds -- avoid doing this.
Solutions:
Set the JTextArea's column and row properties so that it sizes well.
Since your JTextArea's text is going into a JLabel, a component that only allows a single line of text, I wonder if you should be using a JTextArea at all. Perhaps a JTextField would work better since it allows user input but only one line of text.
Add the JTextArea to a JScrollPane (its viewport actually) and add that to your GUI. Then the user can interact directly with it. This is most easily done by passing the JTextArea into a JScrollPane's constructor.
Get rid of the Thread.sleep and instead, if you want to use a delay, use a Swing Timer. check out the tutorial here
For example:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Main2 {
public static void main(String[] args) {
// create GUI in a thread-safe manner
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
BotonExample mainPanel = new BotonExample();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class BotonExample extends JPanel {
private JLabel etiqueta = new JLabel(" ");
private JButton boton = new JButton("Escribir");
// jtext area rows and column properties
private int rows = 5;
private int columns = 30;
private JTextArea textArea = new JTextArea(rows, columns);
public BotonExample() {
// alt-e will activate button
boton.setMnemonic(KeyEvent.VK_E);
boton.addActionListener(e -> {
boton.setEnabled(false); // prevent button from re-activating
String text = textArea.getText();
etiqueta.setText(text);
// delay for timer
int delay = 3000;
Timer timer = new Timer(delay, e2 -> {
// get current window and dispose ofit
Window window = SwingUtilities.getWindowAncestor(boton);
window.dispose();
});
timer.setRepeats(false);
timer.start(); // start timer
});
// create JPanels to add to GUI
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 5));
topPanel.add(new JLabel("Etiqueta:"));
topPanel.add(etiqueta);
JPanel bottomPanel = new JPanel();
bottomPanel.add(boton);
JScrollPane scrollPane = new JScrollPane(textArea);
// use layout manager and add components
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
}
textarea.setText("Text"); // this will insert text into the text area
textarea.setVisable(true); // this will display the text area so you can type in it
textarea.setSize(500,500); // set size of the textarea so it actually shows
The user should be able to type in the TA when it is displayed and just do a getText to pull the text

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

Use KeyListener in a loop

I don't have a lot of experience with KeyListeners but I used one in my application and it works fine except I need to wait for input before my program can continue. For this I made a while loop that loops until the String temp is not null (which would mean there would be input).
The problem is there is no way to type in the JTextField (called input). Below is code from my two methods that are supposed to work together so that the text in my JTextField (input) can be returned (as temp). I'm not sure why this doesn't work or how to fix it.
The keyPressed method for my KeyListener:
public void keyPressed(KeyEvent e)
{
//only sends text if the enter key is pressed
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
//if there really is text
if (!input.getText().equals(""))
{
//String temp is changed from null to input
temp=input.getText();
//text sent to another JTextField
output.append(temp+"\n");
//input no longer has text
input.setText("");
}
}
}
The method thats trying to get text, also in my KeyListener class
public String getTemp()
{
booleans isNull=temp==null;
//loops until temp is not null
while (isNull)
{
//unnecessary line of code, only used so the loop not empty
isNull=checkTemp();
}
return temp;
}
public boolean checkTemp()
{
return temp==null;
}
Your while loop is a common console program construct, but understand that you're not creating a console program here but rather an event-driven GUI, and in this situation, the while loop fights against the Swing GUI library, and you need to get rid of it. Instead of a while loop with continual polling you now want to respond to events, and if you're listening for user input into a JTextField do not use a KeyListener as this low-level listener can cause unwanted side effects. Instead add a DocumentListener to the JTextField's Document.
Edit: You're listening for the enter key, and so the solution is even easier: add an ActionListener to the JTextField!
e.g.,
input.addActionListener(e -> {
String text = input.getText().trim();
if (text.isEmpty()) {
return;
}
output.append(text + "\n");
input.setText("");
});
More complete example:
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ChatBox extends JPanel {
private static final int COLS = 40;
private JTextField input = new JTextField(COLS);
private JTextArea output = new JTextArea(20, COLS);
private JButton submitButton = new JButton("Submit");
public ChatBox() {
output.setFocusable(false); // user can't get into output
JScrollPane scrollPane = new JScrollPane(output);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
ActionListener inputListener = e -> {
String text = input.getText().trim();
if (text.isEmpty()) {
return;
}
output.append(text + "\n");
input.setText("");
input.requestFocusInWindow();
};
input.addActionListener(inputListener);
submitButton.addActionListener(inputListener);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(input);
bottomPanel.add(submitButton);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
ChatBox mainPanel = new ChatBox();
JFrame frame = new JFrame("Chat Box");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

How to display one Jframe at a time? [duplicate]

I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).

Java Dialog - Find out if OK is clicked?

I have a dialog for a client-GUI that asks for the IP and Port of the server one wants to connect to. I have everything else, but how would I make it so that when the user clicks "OK" on my dialog box, that it runs something? Here's what I have so far:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class ClientDialog {
JTextField ip = new JTextField(20);
JTextField port = new JTextField(20);
GUI gui = new GUI();
Client client = new Client();
JOptionPane optionPane;
public void CreateDialog(){
Object msg[] = {"IP: ", ip, "\nPort: ", port};
optionPane = new JOptionPane();
optionPane.setMessage(msg);
optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = optionPane.createDialog(null, "Connect to a server");
dialog.setVisible(true);
if(dialog == JOptionPane.OK_OPTION){
System.out.println(ip);
String ipMsg = ip.getText();
int portMsg = Integer.parseInt(port.getText());
gui.CreateConsole(client, ipMsg, portMsg);
}
}
} //End class
I know that the code isn't correct, but what I want is that when the user hits "OK" on the dialog, I can run some code. Thanks!
I'd suggest to use showConfirmDialog instead
int result = JOptionPane.showConfirmDialog(myParent, "Narrative",
"Title", JOptionPane.INFORMATION_MESSAGE);
and there you can test for various returns value from JDialog/JOptionPane
if (result == JOptionPane.OK_OPTION,
JOptionPane.CANCEL_OPTION,
JOptionPane.CLOSED_OPTION, etc..
I'd suggest creating a JPanel and using JOptionpane.showConfirmDialog() (or even JOptionPane.showOptionDialog() to display the dialog and retrieve the option. Here's a modification of your code as an example:
import java.awt.*;
import javax.swing.*;
class ClientDialog {
private JTextField ip = new JTextField(20);
private JTextField port = new JTextField(20);
private JOptionPane optionPane;
private JPanel panel;
public void CreateDialog(){
panel = new JPanel(new GridLayout(2, 2));
panel.add(new JLabel("IP"));
panel.add(ip);
panel.add(new JLabel("Port"));
panel.add(port);
int option = JOptionPane.showConfirmDialog(null, panel, "Client Dialog", JOptionPane.DEFAULT_OPTION);
if (option == JOptionPane.OK_OPTION) {
System.out.println("OK!"); // do something
}
}
}
public class Test {
public static void main(String args[])
{
ClientDialog c = new ClientDialog();
c.CreateDialog();
}
}
Damn, took too long to post. Anyway just design the layout of the JPanel as you would for any other sort of frame.
Please understand that the 2nd parameter in a JOptionPane, the object parameter, can be any Swing component including a JPanel that holds a simple or complex GUI.
Consider creating a JPanel, placing a few components in it including JLabels and two JTextFields, one for IP, one for port, and then displaying this JPanel in a JOptionPane. Then you can easily check if OK has been pressed and act accordingly.
import javax.swing.*;
public class OptionEg {
public static void main(String[] args) {
final JTextField ipField = new JTextField(10);
final JTextField portField = new JTextField(10);
JPanel panel = new JPanel();
panel.add(new JLabel("IP:"));
panel.add(ipField);
panel.add(Box.createHorizontalStrut(15));
panel.add(new JLabel("Port:"));
panel.add(portField);
int result = JOptionPane.showConfirmDialog(null, panel,
"Enter Information", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("IP: " + ipField.getText());
System.out.println("Port: " + portField.getText());
}
}
}
Good solutions.
If you want not to use something else, this is a working example:
1) set DO_NOTHING_ON_CLOSE to ensure user MUST press OK
2) verify if the JDialog is still visible.
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setModal(false);
dialog.setVisible(true);
dialog.setAlwaysOnTop(true);
while(dialog.isVisible())try{Thread.sleep(50);}
catch(InterruptedException e){}
This can be a solution if you want to implement a non-modal dialog box.

Categories