Reading text file from a GUI - java

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

Related

component must be showing on the screen to determine its location when changing JCOMBOX

I am receiving this error when i change items in the Jcombobox, nothing breaks it just shows this error, is there anyway to just throw it so it doesn't show up. everything still works fine, but if you wish to have a look at the code. i will post below.
Error message:
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:2056)
at java.awt.Component.getLocationOnScreen(Component.java:2030)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:395)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:393)
at sun.lwawt.macosx.LWCToolkit$CallableWrapper.run(LWCToolkit.java:538)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:301)
And my code which i don't know which section to show so its all their.
import javax.swing.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
public class TouchOn extends JDialog {
private JPanel mainPanel;
public ArrayList Reader(String Txtfile) {
try {
ArrayList<String> Trains = new ArrayList<String>();
int count = 0;
String testing = "";
File file = new File(Txtfile);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
count += count;
if(!line.contains("*")){
Trains.add(line + "\n");
}
stringBuffer.append("\n");
}
fileReader.close();
//Arrays.asList(Trains).stream().forEach(s -> System.out.println(s));
return Trains;
} catch (IOException e) {
e.printStackTrace();
}
//return toString();
return null;
}
public TouchOn()
{
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
public void setPanels()
{
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
JTextField sYear = new JTextField("2015");
String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
JTextField touchOnTimeFieldhour = new JTextField();
JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
apply.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if(belgrave.isSelected()){
String trainline = belgrave.getText();
}
if(glenwaverly.isSelected()){
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10,10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
Don't create multiple JComboBoxes and then swap visibility. Instead use one JComboBox and create multiple combo box models, such as by using DefaultComboBoxModel<String>, and then swap out the model that it holds by using its setModel(...) method. Problem solved.
Note that using a variation on your code -- I'm not able to reproduce your problem:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFoo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGui();
}
});
}
public static void createAndDisplayGui() {
final JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton button = new JButton(new AbstractAction("Press Me") {
#Override
public void actionPerformed(ActionEvent evt) {
TouchOn2 touchOn2 = new TouchOn2(frame);
touchOn2.setVisible(true);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class TouchOn2 extends JDialog {
private JPanel mainPanel;
#SuppressWarnings({ "rawtypes", "unused" })
public ArrayList Reader(String Txtfile) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add("Data String Number " + (i + 1));
}
// return toString();
// !! return null;
return list;
}
public TouchOn2(Window owner) {
super(owner);
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
#SuppressWarnings("unchecked")
public void setPanels() {
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
final JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
final JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
final JTextField sYear = new JTextField("2015");
final String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
final JTextField touchOnTimeFieldhour = new JTextField();
final JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
final JComboBox<String> cb = new JComboBox<>(
stations.toArray(new String[stations.size()]));
final JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
final JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
apply.addActionListener(new ActionListener() {
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent e) {
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy")
.format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if (belgrave.isSelected()) {
// !! ***** note you're shadowing variables here!!!! ****
String trainline = belgrave.getText();
}
if (glenwaverly.isSelected()) {
// !! and here too
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10, 10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}

How to pass an object argument to a method called in actionPerformed?

I am writing a stock control system program for a school project. This is the last thing I need to do, but seeing as I am a relative Java noob, I kindly request your assistance.
I have a DisplayRecord class, which is created by taking String input from a "search" JTextField in the Search class, finding the Object (Product p) it's linked to, and passing it to the displayRecord method. This part works perfectly.
I want to take that Product p and pass it to the EditProduct class or the DeleteRecord class (depending on the JButton pressed) so the user can then edit the Name, Quantity or Cost of that same Product. Here are my DisplayRecord, EditProduct and DeleteRecord classes. I have no idea what to do.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
public class DisplayRecord extends JFrame implements ActionListener {
final private StockList stocks;
final private ArrayList<Product> list;
JFrame showWindow;
private JPanel top, bot;
private JPanel barcodePanel1 = new JPanel();
private JPanel barcodePanel2 = new JPanel();
private JPanel namePanel1 = new JPanel();
private JPanel namePanel2 = new JPanel();
private JPanel descPanel1 = new JPanel();
private JPanel descPanel2 = new JPanel();
private JPanel compPanel1 = new JPanel();
private JPanel compPanel2 = new JPanel();
private JPanel ratingPanel1 = new JPanel();
private JPanel ratingPanel2 = new JPanel();
private JPanel costPanel1 = new JPanel();
private JPanel costPanel2 = new JPanel();
private JPanel quantityPanel1 = new JPanel();
private JPanel quantityPanel2 = new JPanel();
private JLabel barcodeLabel = new JLabel();
private JLabel nameLabel = new JLabel();
private JLabel descLabel = new JLabel();
private JLabel compLabel = new JLabel();
private JLabel ratingLabel = new JLabel();
private JLabel costLabel = new JLabel();
private JLabel quantityLabel = new JLabel();
private GridLayout displayLayout;
JButton edit = new JButton("Edit");
JButton backToMenu = new JButton("Back to Menu");
JButton delete = new JButton("Delete");
public DisplayRecord() {
stocks = new StockList();
list = stocks.getList();
try {
stocks.load();
} catch (IOException ex) {
System.out.println("Cannot load file");
}
}
public void displayRecord(Product p) {
this.setTitle("Displaying one record");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 350));
top = new JPanel();
displayLayout = new GridLayout(7, 2, 2, 2);
top.setLayout(displayLayout);
top.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 5));
bot = new JPanel();
bot.setLayout(new BoxLayout(bot, BoxLayout.LINE_AXIS));
bot.add(Box.createHorizontalGlue());
bot.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 5));
barcodeLabel.setText("Barcode: ");
nameLabel.setText("Name: ");
descLabel.setText("Description: ");
compLabel.setText("Developer: ");
ratingLabel.setText("EU Rating: ");
costLabel.setText("Cost: ");
quantityLabel.setText("Quantity in Stock: ");
JLabel barcodeField = new JLabel(Long.toString(p.getBarcode()));
JLabel nameField = new JLabel(p.getName());
JLabel descField = new JLabel(p.getDesc());
JLabel compField = new JLabel(p.getCompany());
JLabel ratingField = new JLabel(p.getRating());
JLabel costField = new JLabel(Double.toString(p.getCost()));
JLabel quantityField = new JLabel(Integer.toString(p.getQuantity()));
barcodePanel1.add(barcodeLabel);
barcodePanel1.setBorder(BorderFactory.createLineBorder(Color.black));
barcodePanel2.add(barcodeField); barcodePanel2.setBorder(BorderFactory.createLineBorder(Color.black));
namePanel1.add(nameLabel);
namePanel1.setBorder(BorderFactory.createLineBorder(Color.black));
namePanel2.add(nameField);
namePanel2.setBorder(BorderFactory.createLineBorder(Color.black));
descPanel1.add(descLabel);
descPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
descPanel2.add(descField);
descPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
compPanel1.add(compLabel);
compPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
compPanel2.add(compField);
compPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
ratingPanel1.add(ratingLabel);
ratingPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
ratingPanel2.add(ratingField);
ratingPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
costPanel1.add(costLabel);
costPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
costPanel2.add(costField);
costPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
quantityPanel1.add(quantityLabel);
quantityPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
quantityPanel2.add(quantityField);
quantityPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
top.add(barcodePanel1);
top.add(barcodePanel2);
top.add(namePanel1);
top.add(namePanel2);
top.add(descPanel1);
top.add(descPanel2);
top.add(compPanel1);
top.add(compPanel2);
top.add(ratingPanel1);
top.add(ratingPanel2);
top.add(costPanel1);
top.add(costPanel2);
top.add(quantityPanel1);
top.add(quantityPanel2);
edit.addActionListener(this);
delete.addActionListener(this);
backToMenu.addActionListener(this);
bot.add(edit);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(delete);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(backToMenu);
this.add(top);
this.add(bot, BorderLayout.SOUTH);
this.setLocationRelativeTo(null);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) { // here is where I'd LIKE to pass Product p as parameter but obviously that's not a thing
if (e.getSource() == edit) {
// EditProduct ed = new EditProduct(); <- hypothetical!
// ed.editProduct(p);
} else if (e.getSource() == delete) {
// DeleteRecord del = new DeleteRecord(); <- hypothetical!
// del.deleteRecord(p);
} else if (e.getSource() == backToMenu) {
new CreateDisplay();
this.dispose();
}
}
}
My EditProduct class:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class EditProduct extends JFrame implements FocusListener, ActionListener {
final private StockList stocks;
final private ArrayList<Product> list;
JPanel top, bot;
JLabel nameLabel, costLabel, quantityLabel = new JLabel();
JTextField nameField, costField, quantityField = new JTextField();
JButton save, quit = new JButton();
private GridLayout topLayout;
public EditProduct() {
stocks = new StockList();
list = stocks.getList();
}
public void editProduct(Product p) {
this.setTitle("Editing a Product");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 250));
top = new JPanel();
topLayout = new GridLayout(3, 2, 5, 5);
top.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 5));
top.setLayout(topLayout);
bot = new JPanel();
bot.setLayout(new BoxLayout(bot, BoxLayout.LINE_AXIS));
bot.add(Box.createHorizontalGlue());
bot.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 5));
nameLabel.setText("Name: ");
costLabel.setText("Cost: ");
quantityLabel.setText("Quantity: ");
top.add(nameLabel);
top.add(costLabel);
top.add(quantityLabel);
nameField = new JTextField(p.getName());
costField = new JTextField(String.valueOf(p.getCost()));
quantityField = new JTextField(p.getQuantity());
nameField.addFocusListener(this);
costField.addFocusListener(this);
quantityField.addFocusListener(this);
save.setText("Save");
save.addActionListener(this);
quit.setText("Quit");
quit.addActionListener(this);
bot.add(save);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(quit);
this.add(top);
this.add(bot, BorderLayout.SOUTH);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
#Override
public void focusGained(FocusEvent e) {
if (e.getSource() == nameField) {
nameField.setText("");
} else if (e.getSource() == costField) {
costField.setText("");
} else if (e.getSource() == quantityField) {
quantityField.setText("");
}
}
#Override
public void focusLost(FocusEvent fe) {
//do nothing
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == save) {
String newName = nameField.getText();
double newCost = Double.parseDouble(costField.getText());
int newQty = Integer.parseInt(quantityField.getText());
stocks.editProduct(newName, newCost, newQty);
this.dispose();
JOptionPane.showMessageDialog(null, "Changes have been saved!", "Saved!", JOptionPane.PLAIN_MESSAGE);
} else if (e.getSource() == quit) {
}
}
}
Aaand the DeleteRecord class:
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class DeleteRecord {
private StockList stocks;
private ArrayList<Product> list;
public DeleteRecord() {
stocks = new StockList();
list = stocks.getList();
}
public DeleteRecord(Product p) {
String title = "Are you sure you want to delete " + p.getName() + "?";
if (JOptionPane.showConfirmDialog(null, title, "Deleting...", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
stocks.deleteRecord(p);
} else {
new CreateDisplay();
}
}
}
I'm sorry for the massive post and text wall but I honestly have no idea where my problem is or how to work around this problem (and I'm also new to StackOverflow). Can anyone help me?
It seems to me that DisplayRecord can only display one Product at a time. If that is indeed the case, you can store that Product in a field and then access it from actionPerfomed().

Call JOptionPane repaint from internal panel

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

How do I add mnemonics in java swing?

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

Applet not appearing full

I just created an applet
public class HomeApplet extends JApplet {
private static final long serialVersionUID = -7650916407386219367L;
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
// setSize(400, 400);
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
RconSection rconSection = new RconSection();
rconSection.setOpaque(true);
// CommandArea commandArea = new CommandArea();
// commandArea.setOpaque(true);
JTabbedPane tabbedPane = new JTabbedPane();
// tabbedPane.setSize(400, 400);
tabbedPane.addTab("Rcon Details", rconSection);
// tabbedPane.addTab("Commad Area", commandArea);
setContentPane(tabbedPane);
}
}
where the fisrt tab is:
package com.rcon;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.Bean.RconBean;
import com.util.Utility;
public class RconSection extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -9021500288377975786L;
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
// private DynamicTree treePanel;
public RconSection() {
// super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new GridLayout(1,3));
panel1.add(testButton);
panel1.add(clearButton);
add(panel);
add(panel1);
// add(panel, BorderLayout.NORTH);
// add(panel1, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals(TEST_COMMAND)){
String ip = ipText.getText().trim();
if(!Utility.checkIp(ip)){
ipText.requestFocusInWindow();
ipText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Ip!!!");
return;
}
String port = portText.getText().trim();
if(port.equals("") || !Utility.isIntNumber(port)){
portText.requestFocusInWindow();
portText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Port!!!");
return;
}
String pass = rPassText.getText().trim();
if(pass.equals("")){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Enter Rcon Password!!!");
return;
}
RconBean rBean = RconBean.getBean();
rBean.setIp(ip);
rBean.setPassword(pass);
rBean.setPort(Integer.parseInt(port));
if(!Utility.testConnection()){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Rcon!!!");
return;
}else{
JOptionPane.showMessageDialog(this,"Correct Rcon!!!");
return;
}
}
else if(arg0.getActionCommand().equals(CLEAR_COMMAND)){
ipText.setText("");
portText.setText("");
rPassText.setText("");
}
}
}
it appears as
is has cropped some data how to display it full and make the applet non resizable as well. i tried setSize(400, 400); but it didnt helped the inner area remains the same and outer boundaries increases
Here's another variation on your layout. Using #Andrew's tag-in-source method, it's easy to test from the command line:
$ /usr/bin/appletviewer HomeApplet.java
// <applet code='HomeApplet' width='400' height='200'></applet>
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class HomeApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
createGUI();
}
});
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private void createGUI() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Rcon1", new RconSection());
tabbedPane.addTab("Rcon2", new RconSection());
this.add(tabbedPane);
}
private static class RconSection extends JPanel implements ActionListener {
private static final String TEST_COMMAND = "test";
private static final String CLEAR_COMMAND = "clear";
private JTextField ipText = new JTextField();
private JTextField portText = new JTextField();
private JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel buttons = new JPanel(); // default FlowLayout
buttons.add(testButton);
buttons.add(clearButton);
add(panel, BorderLayout.NORTH);
add(buttons, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
}
}
As I mentioned in a comment, this question is really about how to layout components in a container. This example presumes you wish to add the extra space to the text fields and labels. The size of the applet is set in the HTML.
200x130 200x150
/*
<applet
code='FixedSizeLayout'
width='200'
height='150'>
</applet>
*/
import java.awt.*;
import javax.swing.*;
public class FixedSizeLayout extends JApplet {
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initGui();
}
});
}
private void initGui() {
JTabbedPane tb = new JTabbedPane();
tb.addTab("Rcon Details", new RconSection());
setContentPane(tb);
validate();
}
}
class RconSection extends JPanel {
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout(3,3));
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
panel1.add(testButton);
panel1.add(clearButton);
add(panel, BorderLayout.CENTER);
add(panel1, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Container c = new RconSection();
JOptionPane.showMessageDialog(null, c);
}
});
}
}
Size of applet viewer does not depend on your code.
JApplet is not window, so in java code you can't write japplet dimensions. You have to change run settings. I don't know where exactly are in other ide's, but in Eclipse you can change dimensions in Project Properties -> Run/Debug settings -> click on your launch configurations file (for me there were only 1 - main class) -> edit -> Parameters. There you can choose width and height for your applet. save changes and you are good to go

Categories

Resources