So I have a greeting program with 3 JTextfields and 3 JLabels next to them and I want to add mnemonics, which I believe is the little underline underneath one of the letters in the JLabel next to the JTextField. When the user presses Alt+underlined key, then the cursor will go to the JTextfield next to it. Here is my code so that just shows the simple greeting without mnemonics
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GreetingApp extends JFrame {
private static final long serialVersionUID = 1L;
private final JTextField firstNameField,middleNameField,lastNameField;
private final JButton greetingButton;
public GreetingApp() {
super("Greetings");
this.firstNameField = new JTextField(8);
this.middleNameField = new JTextField(8);
this.lastNameField = new JTextField(8);
this.greetingButton = new JButton("Get Greeting");
greetingButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent ae){
showGreeting();
}
});
final Container mainPanel = getContentPane();
mainPanel.setLayout(new BorderLayout());
final JPanel inputPanel = new JPanel();
final JPanel buttonPanel = new JPanel();
inputPanel.setLayout(new GridLayout(3,3,3,5));
buttonPanel.setLayout(new FlowLayout());
JSeparator sep = new JSeparator();
inputPanel.add(new JLabel("First Name: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(firstNameField);
inputPanel.add(new JLabel("MI: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(middleNameField);
inputPanel.add(new JLabel("Last Name: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(lastNameField);
mainPanel.add(inputPanel,BorderLayout.PAGE_START);
//buttonPanel.add(sep,BorderLayout.PAGE_START);
mainPanel.add(sep,BorderLayout.CENTER);
buttonPanel.add(greetingButton);
mainPanel.add(buttonPanel,BorderLayout.PAGE_END);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private String getFullName() throws IllegalStateException{
if(firstNameField.getText().trim().length() == 0){
throw new IllegalArgumentException("First name cannot be blank");
}
if(middleNameField.getText().trim().length() > 1){
throw new IllegalArgumentException("Middle intial cannot be greater than 1 letter");
}
if(lastNameField.getText().trim().length() == 0){
throw new IllegalArgumentException("Last name cannot be blank");
}
if(middleNameField.getText().trim().length() ==0){
return "Greetings, "+this.firstNameField.getText()+" "+ this.middleNameField.getText() +this.lastNameField.getText()+"!";
}
return "Greetings, "+this.firstNameField.getText()+" "+ this.middleNameField.getText()+"."+this.lastNameField.getText()+"!";
}
private void showGreeting(){
try{
String message = getFullName();
JOptionPane.showMessageDialog(this, message);
}catch(final IllegalArgumentException iae){
JOptionPane.showMessageDialog(this,
iae.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
try{
for(LookAndFeelInfo info:UIManager.getInstalledLookAndFeels()){
if("Nimbus".equals(info.getName())){
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}catch(Exception e){
e.getStackTrace();
}
}
}
If your JLabel is called label and your JTextField is called textField:
label.setDisplayedMnemonic(KeyEvent.VK_N); //replace .VK_N with the appropriate key
will place the mnemonic on the label, and:
label.setLabelFor(textField);
will associate that label (and its mnemonic) with the appropriate text field
Related
I'm new to java and for some reason I don't know any other way to transfer the data from another frame after pressing submit. For example, it will show the output frame the label and textfield that the user wrote in the first frame like this "Name: "user's name". If you do know please post the code I should put, thank you!
package eventdriven;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDriven extends JFrame {
JPanel items = new JPanel();
JLabel fName = new JLabel("First Name: ");
JLabel lName = new JLabel("Last Name: ");
JLabel mName = new JLabel("Middle Name: ");
JLabel mNum = new JLabel("Mobile Number: ");
JLabel eAdd = new JLabel("Email Address: ");
JTextField fname = new JTextField(15);
JTextField lname = new JTextField(15);
JTextField mname = new JTextField(15);
JTextField mnum = new JTextField(15);
JTextField eadd = new JTextField(15);
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear All");
JButton okay = new JButton("Okay");
JTextArea infos;
JFrame output;
public EventDriven()
{
this.setTitle("INPUT");
this.setResizable(false);
this.setSize(230, 300);
this.setLocation(300, 300);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(fName);
this.add(fname);
this.add(lName);
this.add(lname);
this.add(mName);
this.add(mname);
this.add(mNum);
this.add(mnum);
this.add(eAdd);
this.add(eadd);
submit.addActionListener(new btnSubmit());
this.add(submit);
clear.addActionListener(new btnClearAll());
this.add(clear);
okay.addActionListener(new btnOkay());
this.add(items);
this.setVisible(true);
}
class btnSubmit implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submit)
{
submit.setEnabled(false);
output = new JFrame("OUTPUT");
output.show();
output.setSize(300,280);
output.setTitle("OUTPUT");
output.add(okay);
output.setLayout(new FlowLayout(FlowLayout.CENTER));
}
}
}
class btnClearAll implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == clear)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
class btnOkay implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == okay)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
public static void main(String[] args)
{
EventDriven window = new EventDriven();
}
}
It's not clear what problem you are having displaying a value from one field in another frame. But here's an example of doing that (with fields reduced to just one for demonstration):
public class EventDriven extends JFrame {
private final JTextField nameField = new JTextField(15);
private final JButton submit = new JButton("Submit");
private final JButton clear = new JButton("Clear All");
public EventDriven() {
setTitle("Input");
setLayout(new FlowLayout(FlowLayout.CENTER));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Name: "));
add(nameField);
submit.addActionListener(this::showOutput);
add(submit);
clear.addActionListener(this::clearInput);
add(clear);
pack();
}
private void showOutput(ActionEvent ev) {
submit.setEnabled(false);
JDialog output = new JDialog(EventDriven.this, "Output", true);
output.add(new Label("Name: " + nameField.getText()), BorderLayout.CENTER);
JButton okButton = new JButton("OK");
output.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(bv -> output.setVisible(false));
output.pack();
output.setVisible(true);
}
private void clearInput(ActionEvent ev) {
nameField.setText(null);
submit.setEnabled(true);
}
public static void main(String[] args) {
EventDriven window = new EventDriven();
window.setVisible(true);
}
}
You will also see that I've simplified your action listeners to demonstrate an easier way to respond to user driven event.s
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am getting an error when im trying to write a code to automatically select a tab from tabbed pane when condition is true, but im getting an error with null pointer exception in while im trying to execute the code after compiling it!!
The problem is in the loadData(); method on setSelectedTab();
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
public class GUI extends JFrame implements ActionListener{
private static final long serialVersionUID = 1;
ArrayList<Ship> shiplist= new ArrayList<Ship>();
private int shipcount = 0;
private int index = 0;
private Ship shipob;
private JTextField ShipYear;
private JTextField ShipName;
private JTextField CrewSize;
private JTextField ShipType;
private JTextField NoOfPass;
private JTextField NoOfCabins;
private JTextField PerFull;
private JTextField CabinRate;
private JTextField SizeCat;
private JTextField PerFilled;
private JTextField LiquidType;
private JTextField Capacity;
private ObjectInputStream inStream;
private ObjectOutputStream outStream;
private JTabbedPane tab;
private CruiseShip cruiseShip;
private DryCargoShip dryShip;
private LiquidCargoShip liquidShip;
JLabel message=new JLabel();
public GUI()
{
setSize(2000,300);
setTitle("Ship Data");
Container content= getContentPane();
content.setBackground(Color.GRAY);
content.setLayout(new BorderLayout());
JMenuBar menu=new JMenuBar();
JMenuItem menue= new JMenuItem("Exit");
menue.addActionListener(this);
menu.add(menue);
setJMenuBar(menu);
this.addWindowListener(new WindowDestroyer());
JPanel panel1= new JPanel();
panel1.setBackground(Color.YELLOW);
panel1.setLayout(new GridLayout(2,2));
panel1.add(new JLabel("Ship Name:"));
ShipName= new JTextField(50);
panel1.add(ShipName);
panel1.add(new JLabel("Ship Year:"));
ShipYear= new JTextField(50);
panel1.add(ShipYear);
panel1.add(new JLabel("Crew Size:"));
CrewSize= new JTextField(50);
panel1.add(CrewSize);
panel1.add(new JLabel("Ship Type:"));
ShipType= new JTextField(50);
panel1.add(ShipType);
content.add(panel1, BorderLayout.NORTH);
JPanel panel2= new JPanel();
panel2.setLayout(new BorderLayout());
JPanel panel3= new JPanel();
panel3.setBackground(Color.CYAN);
panel3.setLayout(new FlowLayout());
JButton Button1= new JButton("Next");
Button1.addActionListener(this);
panel3.add(Button1);
JButton Button2= new JButton("Previous");
Button2.addActionListener(this);
panel3.add(Button2);
panel2.add(panel3,BorderLayout.WEST);
panel2.add(message,BorderLayout.EAST);
JTabbedPane tab=new JTabbedPane();
content.add(panel2, BorderLayout.SOUTH);
JPanel cs= new JPanel();
//JPanel z= new JPanel();
cs.setBackground(Color.ORANGE);
cs.setLayout(new GridLayout(2,2));
cs.add(new JLabel("No of Passenger: "));
NoOfPass= new JTextField(25);
cs.add(NoOfPass);
cs.add(new JLabel("No of Cabins: "));
NoOfCabins= new JTextField(25);
cs.add(NoOfCabins);
cs.add(new JLabel("Percentage Full: "));
PerFull= new JTextField(25);
cs.add(PerFull);
cs.add(new JLabel("Cabin Rate: "));
CabinRate= new JTextField(25);
cs.add(CabinRate);
tab.addTab("Cruise Ship", cs);
JPanel ds= new JPanel();
//JPanel x= new JPanel();
ds.setBackground(Color.ORANGE);
ds.setLayout(new GridLayout(1,2));
ds.add(new JLabel("Size Category : "));
SizeCat= new JTextField(25);
ds.add(SizeCat);
ds.add(new JLabel("Percentage Filled : "));
PerFilled= new JTextField(25);
ds.add(PerFilled);
tab.addTab("Dry Cargo Ship", ds);
JPanel ls= new JPanel();
//JPanel y= new JPanel();
ls.setBackground(Color.ORANGE);
ls.setLayout(new GridLayout(1,2));
ls.add(new JLabel("Liquid Type : "));
LiquidType= new JTextField(25);
ls.add(LiquidType);
ls.add(new JLabel("Capacity : "));
Capacity= new JTextField(25);
ls.add(Capacity);
tab.addTab("Liquid Cargo Ship", ls);
content.add(tab,BorderLayout.CENTER);
}
public static void main(String[] args)
{
GUI Gui = new GUI();
Gui.readData();
Gui.loadData();
Gui.index = 0;
Gui.met();
//Gui.shipcount= shiplist.size();
Gui.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Container container = getContentPane();
String string = e.getActionCommand();
if (string.equals("Next"))
{
nextShip();
}
else if (string.equals("Previous"))
{
previousShip();
}
else if (string.equals("Exit"))
{
writeData();
System.exit(0);
}
else
{
System.out.println("Error");
}
}
public void readData()
{
inStream=null;
try
{
inStream= new ObjectInputStream(new FileInputStream("shipdata.dat"));
try {
this.shipcount = 0;
do {
shiplist.add((Ship)inStream.readObject());
shipcount++;
} while (true);
}
catch (EOFException obj1)
{
System.out.println("Entered EOF");
}
catch (ClassNotFoundException obj2)
{
System.out.println("Class Error: " + obj2.getMessage());
}
this.inStream.close();
}
catch (FileNotFoundException obj3)
{
System.out.println("File Error: " + obj3.getMessage());
}
catch (IOException obj4)
{
System.out.println("IO Error in read file data: " + obj4.getMessage());
}
}
public void met()
{
shipcount= shiplist.size();
}
public void loadData() {
shipob = shiplist.get(index);
ShipName.setText(shipob.getShipName());
ShipYear.setText(shipob.getYear());
String a=""+shipob.getCrewSize();
CrewSize.setText(a);
ShipType.setText(shipob.getShipType());
if (shipob.getShipType().equals("Cruise Ship"))
{
System.out.println("In Cruise ship");
cruiseShip = (CruiseShip)shipob;
String b=""+cruiseShip.getCabinRate();
CabinRate.setText(b);
NoOfPass.setText(Integer.toString(cruiseShip.getNoOfPass()));
NoOfCabins.setText(Integer.toString(cruiseShip.getNoOfCabins()));
PerFull.setText(Double.toString(cruiseShip.getPerFull() * 100.0));
tab.setSelectedIndex(0); // ERROR IN SELECT INDEX - NULL POINTER EXCEPTION
}
else if (shipob.getShipType().equals("Dry Cargo Ship"))
{
System.out.println("In Dry ship");
dryShip = (DryCargoShip)shipob;
SizeCat.setText(dryShip.getSize());
String c=" "+dryShip.getPerFilled()*100.0;
PerFilled.setText(c);
try{
tab.setSelectedIndex(1);}
catch(Exception e){
System.out.println(e);
}
}
else if (shipob.getShipType().equals("Liquid Cargo Ship"))
{
System.out.println("In LC ship");
liquidShip = (LiquidCargoShip)shipob;
LiquidType.setText(liquidShip.getLiqType());
Capacity.setText(Integer.toString(liquidShip.getCapacity()));
tab.setSelectedIndex(2);
}
}
public void nextShip() {
if (index == shipcount - 1) {
message.setText("Already at last record ");
}
else {
message.setText("");
index++;
loadData();
}
}
public void previousShip() {
if (index == 0)
{
message.setText("Already at first record ");
}
else
{
message.setText("");
index--;
loadData();
}
}
public void writeData()
{
try {
outStream = new ObjectOutputStream(new FileOutputStream("shipdata.dat", false));
for (Ship ship : shiplist)
{
outStream.writeObject(ship);
}
outStream.flush();
outStream.close();
}
catch (IOException obj1) {
System.out.println("IO Error in writing the data: " + obj1.getMessage());
}
}
}
In the constructor you are initializing a local JTabbedPane and not the one that is declared in the class and accessed in the method loadData.
Please initialize the variable tab in a proper way, i.e.
this.tab=new JTabbedPane();
instead of
JTabbedPane tab=new JTabbedPane();
what I am trying to do is compare two inputs from TextFields within a JFrame using an ActionListener. If the two inputs are equal and the user hits the button, a MessageDialog will pop up and say "equal". If they are not equal, a MessageDialog will pop up and say "not equal". I have the frame and ActionListener running, I just do not know how to take the inputs from the TextFields and compare them.
For example, if the user enters something like this,
Equal TextFields, this will pop up, Equal Message
Here is my Main Class:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here is my ActionListener Class:
class tfListener implements ActionListener
{
private final JTextField tf3;
public tfListener(JTextField nameTF)
{
tf3 = nameTF;
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("abc"))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
EDIT: ok than try to change the constructor in your ActionListener Class to
public tfListener(JTextField tf1, JTextField tf2){
{
Hi :) just don't overthink and you should be fine. The simple way would be to implement the ActionListener directly to your Main Class like this:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
final JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
final JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
{
class tfListener implements ActionListener
{
private final String tf1text;
private final String tf2text;
public tfListener(JTextField tf1, JTextField tf2)
{
tf1text = new String(tf1.getText());
tf1text = new String(tf2.getText());
}
#Override
public void actionPerformed(ActionEvent e)
{
if(tf1text.equal(tf2text))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
}
tf1.toString();
Shows you some information from the JTextField.
use another methods to get your input from the field. I mean it's the method:
tfi.getText();
Better look in a JTextField javadoc
To be honest with you, I don't think you need two classes; one for implementing the GUI and one for handling the ActionListener when you can have everything in one class like the class below
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
public class LabFiveOne implements ActionListener
{
private JFrame frame;
private JPanel nPanel, sPanel;
private JTextField tf1, tf2;
private JButton chEq;
public static void main(String[] args)
{
new LabFiveOne();
}
public LabFiveOne(){
frame = new JFrame("String Equality Program");
tf1 = new JTextField(10);
tf2 = new JTextField(10);
chEq = new JButton("Check Equality");
chEq.addActionListener(this);
nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = e.getActionCommand();
if(action.equals("Check Equality")){
String number1 = tf1.getText();
String number2 = tf2.getText();
int num1 = Integer.valueOf(number1);
int num2 = Integer.valueOf(number2);
if(num1 == num2){
JOptionPane.showMessageDialog(null, "Equal");
}
else{
JOptionPane.showMessageDialog(null, "Not Equal");
}
}
}
}
I have everything declared globally so that the ActionPerformed method will have access the values in the Textfields.
I have a GUI that verifies a username and password. The other part of the assignment is to read from a file that contains a username and a password and checks to see if it matches what the user put in the text field. If it does match then it will hide the Login page and another page will appear with a "Welcome" message. I have zero experience with text files, where do I put that block of code? I assume it would go in the ActionListener method and not the main method but i'm just lost. I just need a little push in the right direction. Here is what I have so far. Any help would be greatly appreciated. Thanks!
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
/**
*/
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
listener = new ClickListener();
}
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
}
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}
import javax.swing.*;
import java.awt.*;
/**
*/
public class PassWordFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new PassWordFrame();
frame.setTitle("Password Verification");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
First of all you initialize the listener (listener = new ClickListener()) after the call to #createComponents() method so this means you will add a null listener to the login button. So your constructor should look like this:
public PassWordFrame() {
listener = new ClickListener();
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
Then, because you want to change the GUI with a welcome message, you should use a SwingWorker, a class designed to perform GUI-interaction tasks in a background thread. In the javadoc you can find nice examples, but here is also a good tutorial: Worker Threads and SwingWorker.
Below i write you only the listener implementation (using a swing worker):
class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
new SwingWorker<Boolean, Void>() {
#Override
protected Boolean doInBackground() throws Exception {
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
BufferedReader reader = new BufferedReader(new FileReader(userFile));
String user;
String pass;
try {
user = reader.readLine();
pass = reader.readLine();
}
catch (IOException e) {
//
// in case something is wrong with the file or his contents
// consider login failed
user = null;
pass = null;
//
// log the exception
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// ignore, nothing to do any more
}
}
if (usertext.getText().equals(user) && passtext.getText().equals(pass)) {
return true;
} else {
return false;
}
}
#Override
protected void done() {
boolean match;
try {
match = get();
}
//
// this is a learning example so
// mark as not matching
// and print exception to the standard error stream
catch (InterruptedException | ExecutionException e) {
match = false;
e.printStackTrace();
}
if (match) {
// show another page with a "Welcome" message
}
}
}.execute();
}
}
Another tip: don't add components to a JFrame, so replace this:
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
with:
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(panel1, BorderLayout.NORTH);
contentPane.add(panel2, BorderLayout.WEST);
contentPane.add(panel3, BorderLayout.CENTER);
contentPane.add(panel4, BorderLayout.SOUTH);
setContentPane(contentPane);
assume there is a textfile named password.txt in g driver and it contain usename and password separate by # symbol.
like following
password#123
example code
package homework;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
String info = ReadFile();
System.out.println(info);
String[] split = info.split("#");
String uname=split[0];
String pass =split[1];
if(usertext.getText().equals(uname) && passtext.getText().equals(pass)){
instruct.setText("access granted");
}else{
instruct.setText("access denided");
}
}
});
}
private static String ReadFile(){
String line=null;
String text="";
try{
FileReader filereader=new FileReader(new File("G:\\password.txt"));
//FileReader filereader=new FileReader(new File(path));
BufferedReader bf=new BufferedReader(filereader);
while((line=bf.readLine()) !=null){
text=text+line;
}
bf.close();
}catch(Exception e){
e.printStackTrace();
}
return text;
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}
I have form with combo box. Depends of selected item at this combo box, some fields at form hides and some appears. But size of dialog not auto resized for repainted JPanel of the form. How to fix this?
Sscce.java:
import javax.swing.*;
public class Sscce extends JFrame {
Sscce() {
setTitle("Sscce");
// Sets the behavior for when the window is closed
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().add(new MainPanel());
pack();
}
public static void main(String[] args) {
Sscce application = new Sscce();
application.setVisible(true);
}
}
MainPanel.java:
import javax.swing.*;
public class MainPanel extends JPanel {
public MainPanel() {
final DeviceForm form = new DeviceForm();
JOptionPane.showConfirmDialog(null, form, "Add new device", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
}
}
DeviceForm.java:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class DeviceForm extends JPanel implements ActionListener {
private LinkedHashMap<String, JComponent> fields = new LinkedHashMap<String, JComponent>();
private HashMap<String, JPanel> borders = new HashMap<String, JPanel>();
public DeviceForm() {
String[] versions = {String.valueOf(1), String.valueOf(2),
String.valueOf(3)};
JComboBox versionList = new JComboBox(versions);
versionList.addActionListener(this);
versionList.setSelectedIndex(0);
fields.put("Version: ", versionList);
JTextField textField = new JTextField();
fields.put("Community: ", textField);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
for (Map.Entry<String, JComponent> entry : fields.entrySet()) {
JPanel borderPanel = new JPanel(new java.awt.BorderLayout());
borderPanel.setBorder(new javax.swing.border.TitledBorder(entry.getKey()));
borderPanel.add(entry.getValue(), java.awt.BorderLayout.CENTER);
add(borderPanel);
borders.put(entry.getKey(), borderPanel);
}
}
/**
* Repaint form fields for chosen version of SNMP
* #param e
*/
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
int version = Integer.parseInt((String)cb.getSelectedItem());
if (version == 1) { // hide username and password, show community
JComponent field = borders.get("Username: ");
if (field != null)
remove(field);
field = borders.get("Password: ");
if (field != null)
remove(field);
field = borders.get("Community: ");
if (field != null)
add(field);
}
else if(version == 3) { // hide community, show username and password
JComponent field = borders.get("Community: ");
if (field != null)
remove(field);
field = borders.get("Username: ");
if (field == null)
addField("Username: ");
else
add(field);
field = borders.get("Password: ");
if (field == null)
addField("Password: ");
else
add(field);
}
validate();
repaint();
}
private void addField(String title) {
// Create field
JTextField textField = new JTextField();
fields.put(title, textField);
// Border created field
JPanel borderPanel = new JPanel(new java.awt.BorderLayout());
borderPanel.setBorder(new javax.swing.border.TitledBorder(title));
borderPanel.add(textField, java.awt.BorderLayout.CENTER);
add(borderPanel);
borders.put(title, borderPanel);
}
}
The solution is for you to use a CardLayout.
e.g.,
import java.awt.CardLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class Sscce2 extends JPanel {
private static final String COMMUNITY = "Community";
private static final String PASSWORD = "Password";
private static final String BLANK = "Blank";
private static final String[] VERSIONS = {COMMUNITY, PASSWORD, BLANK};
CardLayout cardLayout = new CardLayout();
JPanel cardHolderPanel = new JPanel(cardLayout);
JComboBox combobox = new JComboBox(VERSIONS);
private JPasswordField passwordField = new JPasswordField(15);
private JTextField communityTextField = new JTextField(15);
public Sscce2() {
cardHolderPanel.add(createCommunityPanel(), COMMUNITY);
cardHolderPanel.add(createPasswordPanel(), PASSWORD);
cardHolderPanel.add(new JLabel(), BLANK);
JPanel comboPanel = new JPanel();
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.PAGE_AXIS));
comboPanel.setBorder(BorderFactory.createTitledBorder("Version:"));
comboPanel.add(combobox);
setLayout(new GridLayout(0, 1));
add(comboPanel);
add(cardHolderPanel);
combobox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String selection = combobox.getSelectedItem().toString();
cardLayout.show(cardHolderPanel, selection);
}
});
}
public String getCommunityText() {
return communityTextField.getText();
}
public char[] getPassword() {
return passwordField.getPassword();
}
private JPanel createCommunityPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBorder(BorderFactory.createTitledBorder(COMMUNITY));
panel.add(communityTextField);
return panel;
}
private JPanel createPasswordPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBorder(BorderFactory.createTitledBorder(PASSWORD));
panel.add(passwordField);
return panel;
}
private static void createAndShowGui() {
Sscce2 sscce2 = new Sscce2();
JOptionPane.showMessageDialog(null, sscce2, "SSCCE 2", JOptionPane.PLAIN_MESSAGE);
System.out.println("Community text: " + sscce2.getCommunityText());
System.out.println("Password: " + new String(sscce2.getPassword())); // *** never do this!
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}