How to validate a JTextField in eclipse? - java

I want to be able to validate a number of different JTextFields in my java project. One being to ensure the user enters a number into a particular field.
Another problem I'm having is being able to validate a particular number, such as 1234 in a field when a submit button is pressed.
If I have to create a method in a separate class then that fine but how would I call the method into my GUI class to use for my JTextField.
I'm quite new to Java and find some of this hard so any help is greatly appreciated.
At the minute I have:
import java.awt.BorderLayout;
public class CashDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField txtEmilysBistro;
private JTextField textconfirmNumber;
private String confirmNumber;
private JButton btnSubmit;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
CashDialog dialog = new CashDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public CashDialog() {
this.confirmNumber = confirmNumber;
setBounds(100, 100, 526, 372);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBackground(new Color(255, 0, 153));
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
txtEmilysBistro = new JTextField();
txtEmilysBistro.setBackground(new Color(255, 0, 153));
txtEmilysBistro.setHorizontalAlignment(SwingConstants.CENTER);
txtEmilysBistro.setForeground(new Color(255, 255, 255));
txtEmilysBistro.setFont(new Font("AR ESSENCE", Font.PLAIN, 50));
txtEmilysBistro.setEditable(false);
txtEmilysBistro.setText("Emily's Bistro");
txtEmilysBistro.setBounds(0, 0, 504, 57);
contentPanel.add(txtEmilysBistro);
txtEmilysBistro.setColumns(10);
}
JTextArea txtrConfirm = new JTextArea();
txtrConfirm.setForeground(new Color(255, 255, 255));
txtrConfirm.setBackground(new Color(255, 0, 153));
txtrConfirm.setEditable(false);
txtrConfirm.setFont(new Font("AR ESSENCE", Font.PLAIN, 25));
txtrConfirm.setText("Please allow your waiter/waitress to enter the confirmation number.");
txtrConfirm.setBounds(54, 73, 407, 77);
contentPanel.add(txtrConfirm);
txtrConfirm.setLineWrap(true);
textconfirmNumber = new JTextField();
textconfirmNumber.setFont(new Font("AR ESSENCE", Font.PLAIN, 30));
textconfirmNumber.setBounds(147, 148, 227, 47);
contentPanel.add(textconfirmNumber);
textconfirmNumber.setColumns(10);
btnSubmit = new JButton("Submit");
btnSubmit.setBackground(new Color(102, 51, 255));
btnSubmit.setForeground(new Color(255, 255, 255));
btnSubmit.setFont(new Font("AR ESSENCE", Font.PLAIN, 25));
btnSubmit.setBounds(184, 211, 162, 29);
contentPanel.add(btnSubmit);
}
}
In this particular text field I only want it to accept the number 1234 in the text field.

There are a few issues with your code, but that is beside the point. To address your question specifically here is one approach. Grant it, you'd probably want to handle it differently, verify you are getting an integer instead of comparing strings, but still this is how you'd add a listener to your submit button.
btnSubmit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
final String data = txtrConfirm.getText();
if( data.compareTo("1234") != 0 )
{
// alert the user
}
else
{
// data is good, do something with it
}
}
});

Related

Exception in thread ... JComboBox, Jbutton and actionlistener [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 months ago.
I am working on a school project and I want to add text from a text field through a button to a combo box. I save the Object with its attributes and then I add it to the combo box: in my case cbbkateaus.
When I run the app it doesn't add it to the combo box and I get this error
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at MtVwGui$2.actionPerformed(MtVwGui.java:119)
Followed by further javax.swing... errors but I think the former is the relevant one. I tried it with the String that I have in // but it leads to the same result.
(names of objects might be in German as an FYI)
import java.awt.BorderLayout;
public class MtVwGui extends JFrame {
private JPanel contentPane;
private JTextField txtHersteller;
private JTextField txtModell;
private JTextField txtBaujahr;
private JTextField txtHubraum;
private JTextField txtKategorien;
private ArrayList<Kategorien> kategorienListe;
private ArrayList<Motorraeder> motorraederListe;
private Kategorien neueKategorie;
private Motorraeder neuesMotorrad;
private JComboBox cbbkateaus;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MtVwGui frame = new MtVwGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MtVwGui() {
kategorienListe= new ArrayList<Kategorien>();
motorraederListe= new ArrayList<Motorraeder>();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 888, 501);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lbHersteller = new JLabel("Hersteller:");
lbHersteller.setBounds(21, 95, 46, 14);
contentPane.add(lbHersteller);
txtHersteller = new JTextField();
txtHersteller.setBounds(101, 92, 86, 20);
contentPane.add(txtHersteller);
txtHersteller.setColumns(10);
JLabel lbModell = new JLabel("Modell:");
lbModell.setBounds(21, 128, 46, 14);
contentPane.add(lbModell);
txtModell = new JTextField();
txtModell.setBounds(101, 123, 86, 20);
contentPane.add(txtModell);
txtModell.setColumns(10);
JLabel lbBaujahr = new JLabel("Baujahr:");
lbBaujahr.setBounds(21, 153, 46, 14);
contentPane.add(lbBaujahr);
txtBaujahr = new JTextField();
txtBaujahr.setBounds(101, 154, 86, 20);
contentPane.add(txtBaujahr);
txtBaujahr.setColumns(10);
JLabel lblNewLabel = new JLabel("Hubraum:");
lblNewLabel.setBounds(21, 190, 54, 14);
contentPane.add(lblNewLabel);
txtHubraum = new JTextField();
txtHubraum.setBounds(101, 187, 86, 20);
contentPane.add(txtHubraum);
txtHubraum.setColumns(10);
JButton btnaddMtr = new JButton("Motorrad hinzuf\u00FCgen");
btnaddMtr.setBounds(21, 259, 138, 23);
contentPane.add(btnaddMtr);
txtKategorien = new JTextField();
txtKategorien.setBounds(446, 92, 100, 20);
contentPane.add(txtKategorien);
txtKategorien.setColumns(10);
JButton btnaddKate = new JButton("Kategorie hinzuf\u00FCgen");
btnaddKate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
neueKategorie = new Kategorien(txtKategorien.getText());
//String addValue = txtKategorien.getText();
kategorienListe.add(neueKategorie);
cbbkateaus.addItem(neueKategorie);
System.out.println("add Kategorie wurde gedrückt");
System.out.println(neueKategorie.getBezeichnung());
}
});
btnaddKate.setBounds(594, 91, 138, 23);
contentPane.add(btnaddKate);
JComboBox cbbkateaus = new JComboBox();
cbbkateaus.setModel(new DefaultComboBoxModel(new String[] {"none"}));
cbbkateaus.setBounds(74, 215, 130, 23);
contentPane.add(cbbkateaus);
}
}
The stack trace you posted says it's on line 119, though I'm not sure which line that is. I pasted the entire code into a local editor and see only 117 lines.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at MtVwGui$2.actionPerformed(MtVwGui.java:119)
The stack trace does show that it was thrown by actionPerformed(), which is your code. From there, we can infer that at least one of the following things in the code block below is null – "at least one" because, pedantically, there might be more than one null waiting for you to discover:
txtKategorien
kategorienListe
cbbkateaus
neueKategorie
btnaddKate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
neueKategorie = new Kategorien(txtKategorien.getText());
//String addValue = txtKategorien.getText();
kategorienListe.add(neueKategorie);
cbbkateaus.addItem(neueKategorie);
System.out.println("add Kategorie wurde gedrückt");
System.out.println(neueKategorie.getBezeichnung());
}
});
Using a debugger would be best, but adding these lines at the start of your actionPerformed() method would help you identify the problem:
System.out.println("txtKategorien: " + txtKategorien);
System.out.println("kategorienListe: " + kategorienListe);
System.out.println("cbbkateaus: " + cbbkateaus);
System.out.println("neueKategorie: " + neueKategorie);

How to pass user input from one frame to another?

I'm currently a beginner in programming and I'm kind of having a hard time right now. Currently I'm making a simple shopping lister using java. Before I go to the problem, I would like to share my code first:
This is the main page of my list:
package com.main;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MainPage extends JFrame implements ActionListener{
JTextPane txtpnListName, txtpnTotal, txtpnSubtotal, txtpnShoppingLists;
JTextField txtfNewItem, txtfPrice, txtItemAmount;
JTextArea textItemList, textAmountList, textPriceList;
JButton btnNewButton, btnNewButton_1, btnLogout, btnMakeNewList;
JScrollPane scrollPane1, scrollPane2,scrollPane3;
JTabbedPane tabPane;
public MainPage(){
super("List n\' Go");
setResizable(false);
getContentPane().setBackground(Color.WHITE);
setBounds(100, 100, 600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
tabPane = new JTabbedPane(JTabbedPane.LEFT);
add(tabPane);
txtpnListName = new JTextPane();
txtpnListName.setBackground(Color.WHITE);
txtpnListName.setEditable(false);
txtpnListName.setFont(new Font("Tahoma", Font.BOLD, 30));
txtpnListName.setText("LIST NAME");
txtpnListName.setBounds(175, 25, 175, 38);
getContentPane().add(txtpnListName);
//Buttons
btnNewButton = new JButton("Save");
btnNewButton.setBounds(375, 25, 75, 21);
getContentPane().add(btnNewButton);
btnNewButton_1 = new JButton("Add Item");
btnNewButton_1.setBounds(375, 59, 75, 21);
getContentPane().add(btnNewButton_1);
btnNewButton_1.addActionListener(this);
btnLogout = new JButton("Logout");
btnLogout.setBounds(463, 25, 75, 21);
getContentPane().add(btnLogout);
btnLogout.addActionListener(this);
txtfNewItem = new JTextField();
txtfNewItem.setBackground(Color.WHITE);
txtfNewItem.setEditable(false);
txtfNewItem.setFont(new Font("Tahoma", Font.PLAIN, 16));
txtfNewItem.setText("New Item");
txtfNewItem.setBounds(185, 99, 200, 28);
getContentPane().add(txtfNewItem);
txtfPrice = new JTextField();
txtfPrice.setBackground(Color.WHITE);
txtfPrice.setEditable(false);
txtfPrice.setFont(new Font("Tahoma", Font.PLAIN, 16));
txtfPrice.setText("Price");
txtfPrice.setBounds(490, 99, 75, 28);
getContentPane().add(txtfPrice);
txtItemAmount = new JTextField();
txtItemAmount.setBackground(Color.WHITE);
txtItemAmount.setEditable(false);
txtItemAmount.setFont(new Font("Tahoma", Font.PLAIN, 16));
txtItemAmount.setText("Amount");
txtItemAmount.setBounds(395, 99, 75, 28);
getContentPane().add(txtItemAmount);
//ListBox
scrollPane1 = new JScrollPane();
scrollPane1.setBounds(185, 133, 210, 330);
getContentPane().add(scrollPane1);
scrollPane2 = new JScrollPane();
scrollPane2.setBounds(400, 133, 65, 330);
getContentPane().add(scrollPane2);
scrollPane3 = new JScrollPane();
scrollPane3.setBounds(490, 133, 70, 330);
getContentPane().add(scrollPane3);
textItemList = new JTextArea();
textItemList.setEditable(false);
scrollPane1.setViewportView(textItemList);
textItemList.setBackground(Color.GRAY);
textAmountList = new JTextArea();
textAmountList.setEditable(false);
scrollPane2.setViewportView(textAmountList);
textAmountList.setBackground(Color.GRAY);
textPriceList = new JTextArea();
textPriceList.setEditable(false);
scrollPane3.setViewportView(textPriceList);
textPriceList.setBackground(Color.GRAY);
//Summation
txtpnTotal = new JTextPane();
txtpnTotal.setEditable(false);
txtpnTotal.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtpnTotal.setText("Total no. of Items:");
getContentPane().add(txtpnTotal);
txtpnTotal.setBounds(195, 473, 150, 38);
txtpnSubtotal = new JTextPane();
txtpnSubtotal.setEditable(false);
txtpnSubtotal.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtpnSubtotal.setText("Subtotal:");
txtpnSubtotal.setBounds(360, 473, 85, 67);
getContentPane().add(txtpnSubtotal);
txtpnShoppingLists = new JTextPane();
txtpnShoppingLists.setEditable(false);
txtpnShoppingLists.setFont(new Font("Tahoma", Font.BOLD, 15));
txtpnShoppingLists.setText("Shopping Lists");
txtpnShoppingLists.setBounds(10, 10, 120, 31);
getContentPane().add(txtpnShoppingLists);
//For new List
btnMakeNewList = new JButton("Make New List");
btnMakeNewList.setBounds(10, 519, 120, 21);
getContentPane().add(btnMakeNewList);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent exit){
int reply = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the app?", "Confirm Exit",0);
if(reply == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "Thank your for using List n' Go!", "Goodbye!",1);
System.exit(0);
}
else{
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
});
setSize(600,600);
setVisible(true);
setResizable(false);
}
//for testiong purposes
public static void main (String []args){
MainPage mainpage = new MainPage();
}
//Action Listeners
public void actionPerformed(ActionEvent e) {
//logout Button
if(e.getSource() == btnLogout){
int reply = JOptionPane.showConfirmDialog(null, "Are you sure you want to Logout?", "Confirm Logout?",2);
if( reply == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "You have logged out.", "Logout Success",1);
LoginScreen login = new LoginScreen();
dispose();
}
else{
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
// Make new List Button
}
else if(e.getSource() == btnMakeNewList){
}
// Add item to list Button
else if(e.getSource() == btnNewButton_1){
}
else if (e.getSource() == btnNewButton){
}
}
}
And here is the GUI where I want to ask the user for input:
package com.main;
import javax.swing.*;
import java.awt.event.*;
public class AddToList extends JFrame implements ActionListener{
JLabel itemName, itemAmount, itemPrice, itemTotalPrice;
JTextField jtfItemName, jtfItemAmount, jtfItemPrice, jtfTotalPrice;
JButton addItem, goBack;
public AddToList(){
super("What do you want to add?");
setLayout(null);
itemName = new JLabel("Item Name");
itemAmount = new JLabel("Item Amount");
itemPrice = new JLabel("Item Price");
itemTotalPrice = new JLabel();
jtfItemName = new JTextField();
jtfItemAmount = new JTextField();
jtfItemPrice = new JTextField();
jtfTotalPrice = new JTextField();
addItem = new JButton("Add Item");
goBack = new JButton("Back");
itemName.setBounds(10,10, 70,15);
jtfItemName.setBounds(75,10, 270,20);
itemAmount.setBounds(350,10, 70,15);
jtfItemAmount.setBounds(425,10, 120,20);
itemPrice.setBounds(550,10, 70,15);
jtfItemPrice.setBounds(610,10, 120,20);
addItem.setBounds(250,35, 100,25);
goBack.setBounds(400,35, 100,25);
addItem.addActionListener(this);
goBack.addActionListener(this);
add(itemName);add(jtfItemName);add(itemAmount);
add(jtfItemAmount);add(itemPrice);add(jtfItemPrice);
add(addItem);add(goBack);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent exit){
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
});
setSize(750, 100);
setResizable(false);
setVisible(true);
}
// test Program
public static void main(String []args){
AddToList test = new AddToList();
}
// Action Trigger
public void actionPerformed(ActionEvent e) {
//Add item Confirmation
if(e.getSource() == addItem){
}
// Cancel Add Item
else if(e.getSource() == goBack){
}
}
}
My goal here is after the user clicked the "Add Item" button from the Main page, it will prompt the user to input the product details such as the name, amount, and price on the add Item GUI. it will then take the user input and list it on the main page. After that it will calculate the total amount of items on the list, it's amount, and total price. The problem is that I am currently stuck on how can I pass the user input from the Add Item GUI to the main page. I've been researching but I still couldn't find my way around it. I hope you can help me and any help is much appreciated.
P.S: I'm sorry if you find my code a bit too long because this is what currently I could do with the best of my knowledge and abilities. But don't worry, I know that I shouldn't use setLayout(null) since swing has layout managers that I can use. I am still currently learning more about it so bear with me please.
Usually I have a JFrame holding most of the data. If additional information is required by the application, it will show an input dialog. Most of the time this input is not just a string but some more complex stuff. So here is the pattern I follow:
Create a form derived from JPanel. Add the UI elements you need, and use the bean pattern so the necessary data can be injected/retrieved. Very likely you want to show such input when a button in a pane is pressed, so the ActionListener code can look like this:
FormBean fb = new FormBean();
fb.setData(...); (use setters to display data if required/feasible)
if (JOptionPane.showOptionDialog(this, fb, ...)==JOptionPane.OK_OPTION) {
// user pressed ok, so process the data he entered
fb.getData();
}
The advantage of using JOptionPane.showOptionDialog is that you get a standard modal dialog window without threading issues or the question when to activate your code again.

What do I do wrong and the second button acts weird?

I know the code is bad and easy. I am a starter and need some help. I want to add a second button to my code. I feel like I changed the coordinates of the button so it doesn't "fall" on the first one. Any suggestions? (Also, .this is a bit unknown to me so I just copy - pasted it hoping it doesnt affect the second button. I feel like it has to do with .this and the coordinates of the button I entered).
import java.awt.*;
import java.awt.event.*;
public class CalculatorGUI extends Frame implements ActionListener
{
static Operand op;
TextField display;
Button button0;
Button button1;
public CalculatorGUI(String title, Operand op)
{
super(title);
CalculatorGUI.op = op;
this.setLayout(null);
this.setFont(new Font("TimesRoman", Font.PLAIN, 14));
this.setBackground(Color.blue);
button0 = new Button("0");
button0.setBounds(64, 265, 35, 28);
button0.setFont(new Font("TimesRoman", Font.PLAIN, 14));
button0.setForeground(Color.blue);
button0.setFocusable(false);
button0.addActionListener(this);
this.add(button0);
this.setSize(283,320);
this.setLocation(40,30);
this.setVisible(true);
this.setResizable(false);
button1 = new Button("1");
button1.setBounds(64, 230, 35, 28);
button1.setFont(new Font("TimesRoman", Font.PLAIN, 14));
button1.setForeground(Color.blue);
button1.setFocusable(false);
button1.addActionListener(this);
this.add(button1);
this.setSize(283,320);
this.setLocation(40,30);
this.setVisible(true);
this.setResizable(false);
this.addWindowListener(new CloseWindowAndExit());
display = new TextField("");
display.setEditable(false);
display.setBounds(13, 55, 257, 30);
this.add(display);
}
class CloseWindowAndExit extends WindowAdapter
{
public void windowClosing(WindowEvent closeWindowAndExit)
{
System.exit(0);
}
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button0)
{
display.setText("Button0 is pressed");
CalculatorGUI.op.addDigit('0');
}
}
}
Do not add buttons directly to the main frame. Instead, create another panel and add the buttons to it:
Panel newPanel = new Panel(new GridBagLayout());
Button button0 = new Button("BUTTON_0");
button0.setBounds(10, 265, 30, 30);
button0.setFont(new Font("TimesRoman", Font.PLAIN, 14));
button0.setForeground(Color.blue);
button0.setFocusable(false);
Button button1 = new Button("BUTTON_1");
button1.setBounds(10, 265, 30, 30);
button1.setFont(new Font("TimesRoman", Font.PLAIN, 14));
button1.setForeground(Color.blue);
button1.setFocusable(false);
newPanel.add(button0);
newPanel.add(button1);
this.add(newPanel);

Why isn't the Frame showing?

After implementing the Observer/Observable pattern, I can't really see why the Frame isn't showing when the code is executed.
I've looked over it a million times but can't figure it out.
I just want to know where I've gone wrong and how I can fix, so that the frame is showing.
Apologies for the code dump. Would be very grateful for the assistance.
public class MainGameFrame extends JFrame implements KeyListener,Observer {
private final JLabel lblPythonChallenge = DefaultComponentFactory
.getInstance().createTitle("Code Wars");
protected JTextArea textAreaEditable;
protected JTextArea textAreaQuestion;
protected JTextArea textAreaResult;
protected JTextArea textAreaScore;
protected PrintWriter output; // to write textArea stuff to file
private JTextArea textAreaPreview;
private JLabel lblPreview;
private ServerToClient model;
private Socket sock;
/**
* Create the application.
*/
public MainGameFrame() {
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
try {
sock = new Socket("127.0.0.1", 6789);
model = new ServerToClient(sock);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
initialize();
setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
model.addObserver(this);
getContentPane().setBackground(new Color(153, 204, 102));
setForeground(Color.GREEN);
setBackground(Color.GREEN);
setTitle("Code Wars");
setBounds(100, 100, 762, 511);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
// TextArea 1
textAreaEditable = new JTextArea();
textAreaEditable.setBounds(10, 117, 353, 130);
getContentPane().add(textAreaEditable);
textAreaEditable.setTabSize(2); // fix tab size
// auto-indentation
textAreaEditable.registerKeyboardAction(new IndentNextLine(),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
JComponent.WHEN_FOCUSED);
// add KeyListener
textAreaEditable.addKeyListener(this);
// TextArea 2
textAreaQuestion = new JTextArea();
textAreaQuestion.setBackground(new Color(255, 255, 255));
textAreaQuestion.setBounds(10, 34, 353, 46);
getContentPane().add(textAreaQuestion);
// TextArea 3
textAreaResult = new JTextArea();
textAreaResult.setBounds(10, 357, 713, 104);
getContentPane().add(textAreaResult);
textAreaResult.setEditable(false);
// JTextPane textPane_1 = new JTextPane();
// textPane_1.setBounds(463, 158, 273, 269);
// frmPythonChallenge.getContentPane().add(textPane_1);
// component 4
JButton btnRunCode = new JButton("Run Code");
btnRunCode.setBounds(10, 258, 330, 31);
getContentPane().add(btnRunCode);
btnRunCode.addActionListener(new RunButtonListener());
// TextArea 4
textAreaScore = new JTextArea();
textAreaScore.setBounds(373, 34, 350, 46);
getContentPane().add(textAreaScore);
lblPythonChallenge.setBounds(23, -31, 143, 31);
getContentPane().add(lblPythonChallenge);
JLabel lblEnterCodeIn = DefaultComponentFactory.getInstance()
.createLabel("Enter code in the box below:");
lblEnterCodeIn.setForeground(new Color(0, 100, 0));
lblEnterCodeIn.setFont(new Font("Tahoma", Font.BOLD, 12));
lblEnterCodeIn.setBounds(10, 91, 209, 15);
getContentPane().add(lblEnterCodeIn);
JLabel lblQuestion = DefaultComponentFactory.getInstance().createLabel(
"Question:");
lblQuestion.setForeground(new Color(0, 100, 0));
lblQuestion.setFont(new Font("Tahoma", Font.BOLD, 12));
lblQuestion.setBounds(10, 9, 92, 14);
getContentPane().add(lblQuestion);
JLabel lblScores = DefaultComponentFactory.getInstance().createLabel(
"Scores:");
lblScores.setForeground(new Color(0, 100, 0));
lblScores.setFont(new Font("Tahoma", Font.BOLD, 12));
lblScores.setBounds(373, 9, 92, 14);
getContentPane().add(lblScores);
JLabel lblThisIsThe = DefaultComponentFactory.getInstance()
.createLabel("This is the result from your code!");
lblThisIsThe.setForeground(new Color(0, 100, 0));
lblThisIsThe.setFont(new Font("Tahoma", Font.BOLD, 12));
lblThisIsThe.setBounds(10, 328, 238, 15);
getContentPane().add(lblThisIsThe);
// TextArea 5
textAreaPreview = new JTextArea();
textAreaPreview.setBounds(373, 117, 350, 130);
textAreaPreview.setTabSize(2);
textAreaPreview.setEditable(false);
getContentPane().add(textAreaPreview);
lblPreview = DefaultComponentFactory.getInstance().createLabel(
"Preview");
lblPreview.setForeground(new Color(0, 128, 0));
lblPreview.setFont(new Font("Tahoma", Font.BOLD, 12));
lblPreview.setLabelFor(lblPreview);
lblPreview.setBounds(373, 84, 200, 31);
getContentPane().add(lblPreview);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGameFrame window = new MainGameFrame();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Change your main() method to this:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGameFrame window = new MainGameFrame();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
At the end of the initialize() method, add some code that will make MainGameFrame() visible:
this.setVisible(true);
I also suggest you use a Layout Manager to organize the components. Oracle has some great tutorials on how to use different layouts. How to Use Various Layout Managers

Pressing JButton with the Enter key [duplicate]

This question already has answers here:
Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick
(7 answers)
Closed 8 years ago.
Im doing this program and this frame signs up the new users.
What I want is to be able to fill in each text field with the information and then to press the "Cadastrar" key ("Cadastrar" = "Sign up"), not only with the mouse but also with the "Enter" key.
I tried using a keyListener but it turned out to be a little to confusing to me.
Here's the code:
package grafico;
public class TelaDeCadastro extends JFrame {
private TextField campoConfirmaSenha;
private TextField campoNome;
private TextField campoEmail;
private TextField campoSenha;
private TextField dicaDeSenha;
public static void main(String[] args) {
public TelaDeCadastro() {
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(
TelaDeCadastro.class.getResource("/Files/CashLog.png")));
setTitle("Cadastro");
setPreferredSize(new Dimension(400, 300));
setLocationRelativeTo(null);
JButton botaoCadastrar = new JButton("Cadastrar");
botaoCadastrar.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
});
botaoCadastrar.setBounds(139, 196, 115, 35);
JButton botaoVoltar = new JButton("Voltar");
botaoVoltar.setBounds(10, 231, 90, 30);
JButton botaoSair = new JButton("Sair");
botaoSair.setBounds(294, 231, 90, 30);
ButtonGroup botoesRetorno = new ButtonGroup();
botoesRetorno.add(botaoSair);
botoesRetorno.add(botaoVoltar);
// botão para submeter as informações passadas
botaoCadastrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
});
// botão sair fecha o programa
botaoSair.addActionListener(new ActionListener() {
// botão voltar retorna para a tela de login
botaoVoltar.addActionListener(new ActionListener() {
JPanel container = new JPanel();
container.setLayout(null);
dicaDeSenha = new TextField();
dicaDeSenha.setBounds(109, 159, 265, 22);
container.add(dicaDeSenha);
campoConfirmaSenha = new TextField();
campoConfirmaSenha.setEchoChar('*');
campoConfirmaSenha.setBounds(138, 126, 236, 23);
container.add(campoConfirmaSenha);
campoSenha = new TextField();
campoSenha.setEchoChar('*');
campoSenha.setBounds(109, 93, 265, 23);
container.add(campoSenha);
campoEmail = new TextField();
campoEmail.setBounds(109, 62, 265, 23);
container.add(campoEmail);
campoNome = new TextField();
campoNome.setBounds(109, 31, 265, 23);
container.add(campoNome);
JLabel labelNome = new javax.swing.JLabel("Seu nome:");
labelNome.setBounds(10, 35, 364, 14);
container.add(labelNome);
JLabel labelEmail = new javax.swing.JLabel("Seu Email:");
labelEmail.setBounds(10, 66, 364, 14);
container.add(labelEmail);
JLabel labelSenha = new javax.swing.JLabel("Sua senha:");
labelSenha.setBounds(10, 95, 364, 14);
container.add(labelSenha);
JLabel lblConfirmarSenha = new JLabel("Confirmar senha:");
lblConfirmarSenha.setBounds(10, 126, 122, 15);
container.add(lblConfirmarSenha);
JLabel lblDicaDaSenha = new JLabel("Dica da senha:");
lblDicaDaSenha.setBounds(10, 162, 90, 14);
container.add(lblDicaDaSenha);
container.add(botaoCadastrar);
container.add(botaoVoltar);
container.add(botaoSair);
getContentPane().add(container);
JLabel lblCadastrese = new JLabel("Cadastre-se:");
lblCadastrese.setHorizontalAlignment(SwingConstants.CENTER);
lblCadastrese.setHorizontalTextPosition(SwingConstants.CENTER);
lblCadastrese.setBounds(10, 9, 364, 14);
container.add(lblCadastrese);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon(TelaDeCadastro.class
.getResource("/Files/conta-sem-tarifa.jpg")));
label.setBounds(0, 0, 400, 300);
container.add(label);
pack();
}
public TextField getCampoConfirmaSenha() {
public TextField getCampoNome() {
public TextField getCampoEmail() {
public TextField getCampoSenha() {
public TextField getDicaDeSenha() {
}
Don't use KeyListener (or for that matter MouseListener) with buttons.
Buttons are backed by the ActionListener API which deals with Enter, Space, other platform specific activation key strokes, left mouse clicks and mnemonics automatically...
Take a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details.
You should also have a look at How to Use Root Panes, as JRootPane allows you to define a "default" button which will be actived when the user presses the "activation" key stroke. Just beware, that if the component with focus consumes that event, it won't active the button though
Generally speaking, you should avoid KeyListener where ever possible and favor the key bindings API instead anyway

Categories