I was making a GUI to reverse an input string, I am taking input from the first textfield, then reversing the string using my function strRev() then trying to produce the result on the second textfield. But am not getting any output on 2nd textfield.
package com.awt;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.InputMethodEvent;
public class Buttons{
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Buttons window = new Buttons();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Buttons() {
initialize();
}
public String strRev(String s) {
char a;
String ans="";
for(int i=0;i<s.length();i++) {
a=s.charAt(i);
ans=a+ans;
}
return ans;
}
private void initialize() {
frame = new JFrame("Label Demo");
frame.setBounds(150, 200, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
textField = new JTextField();
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton okButton = new JButton("Reverse");
frame.getContentPane().add(okButton);
textField_1 = new JTextField();
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
String str=textField.getText();
final String ans=strRev(str);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField_1.setText(ans);
}
});
}
}
The GUI looks like this:-
Please let me know my mistake, Thanks
You need to read the contents of textField only when the user clicks on the Reverse button. At the moment, you read the contents when the GUI loads at which time there is nothing in the textField. So calling a reverse on empty string is going to give you an empty string and that is what you see in your textField_1. Move the code where you read the textField into your addActionListener.
private void initialize() {
frame = new JFrame("Label Demo");
frame.setBounds(150, 200, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
textField = new JTextField();
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton okButton = new JButton("Reverse");
frame.getContentPane().add(okButton);
textField_1 = new JTextField();
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// THIS BLOCK IS RUN EVERYTIME THE BUTTON IS CLICKED!
// Read the contents of textField
String str=textField.getText();
// Reverse the string you just read
final String ans=strRev(str);
// Set the answer on the other textField.
textField_1.setText(ans);
}
});
}
Related
I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}
I have one Swing project and I have an action listener on JTextField for Tab key as follows.
There is a JOptionPane.showMessageDialog() inside the action listener. And when Tab is pressed option pane will show an Information message.
My problem is that, when I press Enter on OK button of Information Message dialog, a serie of action is invoked viz Tab action of JTextField and Enter action of btnNewButton.
If I use mouse click on OK button of Error Message dialog, every thing is fine and no problem.
Can I solve this using key bindings instead of key listener?
Please suggest a solution
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnNewButton;
private JDialog dialog;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
contentPane.setLayout(null);
textField = new JTextField();
textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.emptySet());
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
JOptionPane.showMessageDialog(dialog, " Please Press ENTER Key", "information",
JOptionPane.INFORMATION_MESSAGE);
btnNewButton.grabFocus();
}
}
});
textField.setBounds(73, 28, 178, 28);
contentPane.add(textField);
textField.setColumns(10);
btnNewButton = new JButton("New button");
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(dialog, " That Invoked New Button Also", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(223, 137, 117, 25);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("Please Press TAB Key");
lblNewLabel.setBounds(83, 55, 183, 15);
contentPane.add(lblNewLabel);
dialog = new JDialog();
dialog.setAlwaysOnTop(true);
}
}
The problem is that you are overriding method keyReleased(). The JOptionPane is closing before the keyReleased() method is called and since you make btnNewButton the focused component after the JOptionPane is closed, the keyReleased() method is invoked – which displays the other JOptionPane.
Simply rename the method to keyPressed().
Also, you don't need the dialog member. The first parameter to JOptionPane#showMessageDialog should be the JFrame.
Here is your code with my corrections.
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
contentPane.setLayout(null);
textField = new JTextField();
textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.emptySet());
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
JOptionPane.showMessageDialog(Test.this, " Please Press ENTER Key", "information",
JOptionPane.INFORMATION_MESSAGE);
btnNewButton.grabFocus();
}
}
});
textField.setBounds(73, 28, 178, 28);
contentPane.add(textField);
textField.setColumns(10);
btnNewButton = new JButton("New button");
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(Test.this, " That Invoked New Button Also", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(223, 137, 117, 25);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("Please Press TAB Key");
lblNewLabel.setBounds(83, 55, 183, 15);
contentPane.add(lblNewLabel);
}
}
Note that (at least in JDK 15) there is no need to explicitly set the default close operation for JFrame since the default is EXIT_ON_CLOSE
When I run this code which should take the text from a JLabel, use a getter method to move it to the button action class, modifiy it and then use a setter method to set it in the original class, it updates the JLabel variable but does not update the GUI.
I have tried repaint(), revalidate(), doLayout() on the label, the frame and the panel that holds the label.
The class that initializes the label:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class Testing4 {
private JFrame frame;
private JLabel lblNewLabel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Testing4 window = new Testing4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Testing4() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
lblNewLabel = new JLabel("label");
lblNewLabel.setBounds(52, 101, 277, 53);
frame.getContentPane().add(lblNewLabel);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(114, 28, 156, 53);
frame.getContentPane().add(btnNewButton);
btnNewButton.addActionListener(new ButtonAction());
}
public String getLabelText()
{
return this.lblNewLabel.getText();
}
public void setLabelText(String text)
{
System.out.println(text);
this.lblNewLabel.setText(text);
System.out.println(lblNewLabel.getText());
}
}
If you look at the setLabelText(String) method, it sets the text to the label called lblNewLabel and then it prints out the text to the console in the next line of code. That .getText() shows that the label has been modified, however the GUI does not show that it has been modified.
Here is the code for the button:
public class ButtonAction implements ActionListener
{
Testing4 test;
public void actionPerformed(ActionEvent e)
{
test = new Testing4();
String x = test.getLabelText();
System.out.println(x);
x = x + " hello";
System.out.println(x);
test.setLabelText(x);
}
}
For all intents and purposes, this should update the GUI with the new text, I've done this before and not had an issue but something this time is causing an issue.
I am creating a JTextField everytime a label is clicked. My problem is to get the text inside those created textfields.
This is my code:
public void mouseClicked(MouseEvent arg0) {
List<JTextField> mine = new ArrayList<JTextField>();
box = new JTextField();
name = new JTextField();
pnlPanel.add(box);
pnlpanel.add(name);
lay++;
if (lay > 0) {
box.setBounds(283, 145, 182, 27);
name.setBounds(81, 145, 182, 27);
mine.add(box);
}
GetData mydata = new GetData();
mydata.doGetData();
frame.repaint();
}
This is my code for getting the data inputted by the user, but it doesnt work:
public class GetData {
public void doGetData(List<JTextField> myFields) {
for (JTextField txt: myFields) {
}
}
}
How does I get the user input?
You will have to store the fields in some kind of way. I prefer to use an ArrayList, but (as mentioned by Klemens Morbe) there are many ways to that.
Here is a basic example, the output will appear in the console.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class MoreAndMoreTextfields extends JFrame {
// the panel, that we will add the visible fields to
private JPanel panel = new JPanel();
// a collection of all fields, so that we can access them afterwards
private Collection<JTextField> textFields = new ArrayList<JTextField>();
public MoreAndMoreTextfields() {
// basic window layout stuff
setSize(400, 300);
setLayout(new FlowLayout());
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setContentPane(panel);
// add label, that will create new input fields
JLabel addInputLabel = new JLabel("click for more fields");
addInputLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JTextField textField = new JTextField();
panel.add(textField);
textField.setPreferredSize(new Dimension(100,20));
textFields.add(textField);
revalidate();
}
});
panel.add(addInputLabel);
// add new label, that will print out contents
JLabel outputLabel = new JLabel("click for contents");
outputLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Contents of fields:");
for (JTextField textField : textFields) {
System.out.println(" input:"+textField.getText());
}
}
});
panel.add(outputLabel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MoreAndMoreTextfields().setVisible(true);
}
});
}
}
For getting the text of the JTextField use textfield.getText().
You could save the JTextFields to a list List<JTextField>
or iterate through the panels componentspanel.getComponents().
Aslo you could give every JTextField an id like this textfield.setName("id");.
So what I've got is that I would love to try and make an little login applet. I'm using Java Windowsbuilder for it, to make it easyer for me. I hope the code isn't to messy, because I'm just a starter.
The problem I've got is that My JButton "login" only registers a keyevent when it's selected trought tab, or when you first click it. What I want is that I can use the button always just by pressing the "ENTER" key.
Hope you guys solve my problem :)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import java.awt.event.KeyAdapter;
public class nummer1 extends JFrame{
private JPanel contentPane;
public static nummer1 theFrame;
private JTextField textFieldUsername;
private JTextField textFieldPass;
private nummer1 me;
private JLabel lblCheck;
private String password = "test", username = "test";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nummer1 frame = new nummer1();
nummer1.theFrame = frame;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void Check(){
String Pass = textFieldPass.getText();
String Username = textFieldUsername.getText();
System.out.println(Pass);
if (Pass.equals(password) && Username.equals(username)){
lblCheck.setText("Correct Login");
}else{
lblCheck.setText("Invalid username or password");
}
}
/**
* Create the frame.
*/
public nummer1() {
me = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 356, 129);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 61, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 61, 14);
contentPane.add(lblPassword);
textFieldUsername = new JTextField();
textFieldUsername.setBounds(81, 8, 107, 20);
contentPane.add(textFieldUsername);
textFieldUsername.setColumns(10);
me.textFieldUsername = textFieldUsername;
textFieldPass = new JTextField();
textFieldPass.setBounds(81, 33, 107, 20);
contentPane.add(textFieldPass);
textFieldPass.setColumns(10);
me.textFieldPass = textFieldPass;
JButton btnLogin = new JButton("Login");
contentPane.requestFocusInWindow();
btnLogin.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
me.Check();
System.out.println("hi");
}
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
me.Check();
}
});
btnLogin.setBounds(198, 7, 89, 23);
contentPane.add(btnLogin);
JLabel lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.TRAILING);
lblCheck.setBounds(10, 65, 264, 14);
contentPane.add(lblCheck);
me.lblCheck = lblCheck;
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new
Component[]{lblUsername, lblPassword, textFieldUsername, textFieldPass, btnLogin, lblCheck}));
}
}
Thanks Emil!
What I want is that I can use the button always just by pressing the "ENTER" key
Sounds like you want to make the "login" button the default button for the dialog.
See Enter Key and Button for the problem and solution.
When using panels KeyListeners won't work unless the panel is focusable. What you can do is make a KeyBinding to the ENTER key using the InputMap and ActionMap for your panel.
public class Sample extends JPanel{
//Code
Sample() {
//More code
this.getInputMap().put(KeyStroke.getKeyStroke((char)KeyEvent.VK_ENTER), "Enter" );
this.getActionMap().put("Enter", new EnterAction());
}
private class EnterAction extends AbstractAction(){
#Override
public void ActionPerformed(ActionEvent e){
//Acion
}
}
}