This question already has answers here:
how to change UI depending on combo box selection
(1 answer)
Positioning component inside card layout
(1 answer)
Closed 5 years ago.
I am trying to change between card panels using the Jcombobox "Expenses". Can someone tell me what I'm doing wrong? I get the panels to appear properly, but when I see the Expenses j tabbed pane, the first card is shown. Once I try to switch between them, the console gets filled with errors. I noticed that all cards are showing at the same time, but they are overlapping.
1)How do I get only one card (panels) showing at once?
2)How do I get the JComboBox to switch between cards(panels)?
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.JList;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
public class LanaFrame extends JFrame implements ItemListener{
private JPanel contentPane, cards;
private JList driverlist;
private JComboBox expenses;
final static String FUEL= "Fuel";
final static String TOLL= "Toll";
final static String REPAIR="Repair";
private static String[] comboboxitems= {FUEL,TOLL,REPAIR};
private JTextField textFieldFirstName;
private JTextField textFieldLastName;
private JTextField textFieldTruckNumber;
private JTextField textFieldTrailerNumber;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LanaFrame frame = new LanaFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LanaFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 500);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(5, 5, 775, 480);
contentPane.add(tabbedPane);
//Drivers Panel
JPanel Drivers = new JPanel();
tabbedPane.addTab("Drivers", null, Drivers, null);
Drivers.setLayout(null);
driverlist= new JList(comboboxitems);
driverlist.setBackground(Color.WHITE);
driverlist.setVisibleRowCount(4);
driverlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Drivers.add(driverlist);
driverlist.setBounds(482,6,266,211);
JButton btnAddDriver = new JButton("Add Driver");
btnAddDriver.setBounds(5, 285, 117, 29);
Drivers.add(btnAddDriver);
JTextArea driverArea = new JTextArea();
driverArea.setBackground(Color.LIGHT_GRAY);
driverArea.setBounds(482, 217, 266, 211);
Drivers.add(driverArea);
driverArea.setEditable(false);
JTextPane txtpnFirstName = new JTextPane();
txtpnFirstName.setText("First name");
txtpnFirstName.setBounds(5, 20, 140, 15);
Drivers.add(txtpnFirstName);
txtpnFirstName.setEditable(false);
textFieldFirstName = new JTextField();
textFieldFirstName.setBounds(5, 40, 140, 30);
Drivers.add(textFieldFirstName);
textFieldFirstName.setColumns(10);
JTextPane txtpnLastName = new JTextPane();
txtpnLastName.setText("Last Name");
txtpnLastName.setBounds(5, 75, 140, 15);
Drivers.add(txtpnLastName);
txtpnLastName.setEditable(false);
textFieldLastName = new JTextField();
textFieldLastName.setBounds(5, 95, 140, 30);
Drivers.add(textFieldLastName);
textFieldLastName.setColumns(10);
JTextPane txtpnTruckNumber = new JTextPane();
txtpnTruckNumber.setText("Truck Number");
txtpnTruckNumber.setBounds(5, 130, 140, 15);
Drivers.add(txtpnTruckNumber);
txtpnTruckNumber.setEditable(false);
textFieldTruckNumber = new JTextField();
textFieldTruckNumber.setBounds(5, 150, 140, 30);
Drivers.add(textFieldTruckNumber);
textFieldTruckNumber.setColumns(10);
JTextPane txtpnTrailerNumber = new JTextPane();
txtpnTrailerNumber.setText("Trailer Number");
txtpnTrailerNumber.setBounds(5, 185, 140, 15);
Drivers.add(txtpnTrailerNumber);
txtpnTrailerNumber.setEditable(false);
textFieldTrailerNumber = new JTextField();
textFieldTrailerNumber.setBounds(5, 205, 140, 30);
Drivers.add(textFieldTrailerNumber);
textFieldTrailerNumber.setColumns(10);
JButton btnDeleteDriver = new JButton("Delete Driver");
btnDeleteDriver.setBounds(359, 185, 117, 29);
Drivers.add(btnDeleteDriver);
//New Expenses Panel
JPanel NewExpense = new JPanel();
tabbedPane.addTab("New Expense", null, NewExpense, null);
//adds types of expenses to jcombo
expenses = new JComboBox(comboboxitems);
expenses.setBounds(257, 5, 236, 30);
expenses.setEditable(false);
expenses.addItemListener(this);
NewExpense.setLayout(null);
NewExpense.add(expenses);
//create panels for each combo option
JPanel fuel = new JPanel();
fuel.setBounds(0, 0, 743, 399);
fuel.setBackground(Color.BLUE);
JPanel toll = new JPanel();
toll.setBounds(0, 0, 743, 399);
toll.setBackground(Color.RED);
JPanel repair = new JPanel();
repair.setBounds(0, 0, 743, 399);
repair.setBackground(Color.BLACK);
//Assigns Panels to combo options
cards = new JPanel(new CardLayout());
cards.setBounds(5, 29, 743, 399);
cards.setLayout(null);
cards.add(fuel, FUEL);
cards.add(toll, TOLL);
cards.add(repair, REPAIR);
NewExpense.add(cards);
JPanel Income = new JPanel();
tabbedPane.addTab("Income", null, Income, null);
Income.setLayout(null);
JPanel Results = new JPanel();
tabbedPane.addTab("Result", null, Results, null);
Results.setLayout(null);
}
#Override
public void itemStateChanged(ItemEvent e) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)e.getItem());
}
}
cards = new JPanel(new CardLayout());
cards.setBounds(5, 29, 743, 399);
cards.setLayout(null); // ???!!!
Seriously? You're setting the cards layout to CardLayout, and then immediatly setting it again to null. And then you get a NullPointerException when you try to use the cards "layout" -- no surprise!
Related
Hi I'm trying to display an ArrayList of Objects on a Jlist. While displaying the ArrayList, I'm trying to be able to add or delete objects to the ArrayList through the GUI.
1) How can I display the ArrayList objects on the Jlist? 2)How can I delete an object by selecting it on the JList?
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.JList;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
public class DriverFrame extends JFrame implements ItemListener{
private JPanel contentPane;
private JList driverlist;
private ArrayList drivers= new ArrayList<Driver>();
JTextField textFieldFirstName;
JTextField textFieldLastName;
JTextField textFieldTruckNumber;
JTextField textFieldTrailerNumber;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_7;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DriverFrame frame = new DriverFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DriverFrame() {
Driver guy1= new Driver("Jeff","Blank","4125","1234",1400);
Driver guy2= new Driver("Marcus","Geralds","0093","1203",1800);
Driver guy3= new Driver("Steve","Wemmings","2010","2046",2100);
Driver guy4= new Driver("Kyle","Patricks","8427","5625",900);
Driver guy5= new Driver("Ficel","Metter","9124","4536",5500);
setBackground(Color.WHITE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
setResizable(false);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBackground(Color.WHITE);
tabbedPane.setBounds(5, 5, 495, 480);
contentPane.add(tabbedPane);
//Drivers TabbedPan ********
JPanel Drivers = new JPanel();
Drivers.setBackground(Color.WHITE);
tabbedPane.addTab("Drivers", null, Drivers, null);
Drivers.setLayout(null);
//List to display drivers
JList<Object> driverlist = new JList<>(drivers.toArray(new String[0]));
driverlist.setBackground(Color.WHITE);
driverlist.setVisibleRowCount(8);
driverlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Drivers.add(driverlist);
driverlist.setBounds(221,6,247,234);
JTextPane txtpnFirstName = new JTextPane();
txtpnFirstName.setText("First name");
txtpnFirstName.setBounds(5, 20, 140, 15);
Drivers.add(txtpnFirstName);
txtpnFirstName.setEditable(false);
textFieldFirstName = new JTextField();
textFieldFirstName.setBounds(5, 40, 140, 30);
Drivers.add(textFieldFirstName);
textFieldFirstName.setColumns(10);
JTextPane txtpnLastName = new JTextPane();
txtpnLastName.setText("Last Name");
txtpnLastName.setBounds(5, 75, 140, 15);
Drivers.add(txtpnLastName);
txtpnLastName.setEditable(false);
textFieldLastName = new JTextField();
textFieldLastName.setBounds(5, 95, 140, 30);
Drivers.add(textFieldLastName);
textFieldLastName.setColumns(10);
JTextPane txtpnTruckNumber = new JTextPane();
txtpnTruckNumber.setText("Truck Number");
txtpnTruckNumber.setBounds(5, 130, 140, 15);
Drivers.add(txtpnTruckNumber);
txtpnTruckNumber.setEditable(false);
textFieldTruckNumber = new JTextField();
textFieldTruckNumber.setBounds(5, 150, 140, 30);
Drivers.add(textFieldTruckNumber);
textFieldTruckNumber.setColumns(10);
JTextPane txtpnTrailerNumber = new JTextPane();
txtpnTrailerNumber.setText("Trailer Number");
txtpnTrailerNumber.setBounds(5, 185, 140, 15);
Drivers.add(txtpnTrailerNumber);
txtpnTrailerNumber.setEditable(false);
textFieldTrailerNumber = new JTextField();
textFieldTrailerNumber.setBounds(5, 205, 140, 30);
Drivers.add(textFieldTrailerNumber);
textFieldTrailerNumber.setColumns(10);
JButton btnAddDriver = new JButton("Add Driver");
btnAddDriver.setBounds(5, 285, 117, 29);
Drivers.add(btnAddDriver);
JButton btnNewButton = new JButton("Delete Driver");
btnNewButton.setBounds(302, 285, 117, 29);
Drivers.add(btnNewButton);
btnAddDriver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Driver blah = new Driver();
blah.setFirst(textFieldFirstName.getText());
blah.setLast(textFieldLastName.getText());
blah.setTnum(textFieldTruckNumber.getText());
blah.setTrailer(textFieldTrailerNumber.getText());
drivers.add(blah);
System.out.println(blah.printDriver());
System.out.println(drivers.size());
//drivers.remove(example);
}
});
//End of DriversPane******
//New Expenses Tab*****
JPanel NewExpense = new JPanel();
tabbedPane.addTab("New Expense", null, NewExpense, null);
JButton buttontest = new JButton();
NewExpense.add(buttontest);
//End of New Expense Tab****
//Income Tab****
JPanel Income = new JPanel();
Income.setBackground(Color.WHITE);
tabbedPane.addTab("Income", null, Income, null);
Income.setLayout(null);
JComboBox comboBox_3 = new JComboBox();
comboBox_3.setBounds(6, 70, 138, 27);
Income.add(comboBox_3);
JTextPane txtpnDriver_3 = new JTextPane();
txtpnDriver_3.setText("Driver:");
txtpnDriver_3.setBounds(6, 42, 42, 16);
Income.add(txtpnDriver_3);
JTextPane txtpnLoadLocationstate = new JTextPane();
txtpnLoadLocationstate.setText("Load Location(State): ");
txtpnLoadLocationstate.setBounds(6, 161, 138, 16);
Income.add(txtpnLoadLocationstate);
textField_6 = new JTextField();
textField_6.setBounds(6, 205, 130, 26);
Income.add(textField_6);
textField_6.setColumns(10);
JTextPane txtpnLoadAmount = new JTextPane();
txtpnLoadAmount.setText("Load Amount $$:");
txtpnLoadAmount.setBounds(6, 299, 108, 16);
Income.add(txtpnLoadAmount);
textField_7 = new JTextField();
textField_7.setBounds(6, 339, 130, 26);
Income.add(textField_7);
textField_7.setColumns(10);
//End of Income Tab****
//Results Tab***
JPanel Results = new JPanel();
Results.setBackground(Color.WHITE);
tabbedPane.addTab("Result", null, Results, null);
Results.setLayout(null);
JComboBox comboBox_4 = new JComboBox();
comboBox_4.setBounds(6, 69, 140, 27);
Results.add(comboBox_4);
JTextPane txtpnDriver_4 = new JTextPane();
txtpnDriver_4.setText("Driver:");
txtpnDriver_4.setBounds(6, 42, 140, 16);
Results.add(txtpnDriver_4);
JTextArea txtrHowMuchTo = new JTextArea();
txtrHowMuchTo.setText("How much to pay driver. How much are the expenses of the driver");
txtrHowMuchTo.setBounds(6, 124, 234, 304);
Results.add(txtrHowMuchTo);
JTextPane txtpnDriverInformation = new JTextPane();
txtpnDriverInformation.setText("Driver Information");
txtpnDriverInformation.setBounds(16, 108, 140, 16);
Results.add(txtpnDriverInformation);
JTextPane txtpnCompanyInfo = new JTextPane();
txtpnCompanyInfo.setText("Company Info:");
txtpnCompanyInfo.setBounds(414, 80, 178, 16);
Results.add(txtpnCompanyInfo);
JTextArea txtrIncome = new JTextArea();
txtrIncome.setText("Income Expenses");
txtrIncome.setBounds(390, 124, 294, 304);
Results.add(txtrIncome);
//End of Results Tab****
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
}
}
I'll try to explain the problem as best i can.
Basically what I have is a system that takes in customer data (Customer is an object) and then adds it to an array. I have that working no problems. What I'm trying to get working is that I also have an option that should enable the user to edit a customers details. The way I'm trying to implement this is; in a separate GUI, I have a comboBox which will be populated with all of the customers first names that are currently in the arrayList. This also works.
Here is my problem - what I want to happen is that when one of the customers first names is chosen from the comboBox, it should find that object, and then fill out the JTextFields with its respective data, e.g. that customers first name should pop into the first name textField and his second name into the second name TextField etc..
I cant figure out this problem so any help is appreciated!
This is only one of a few classes, the rest of which work.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.MaskFormatter;
import javax.swing.JLabel;
import java.awt.SystemColor;
import java.text.ParseException;
import java.util.ArrayList;
import java.awt.Font;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.UIManager;
import java.awt.GridLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
public class editCustomers extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
ArrayList<Customers> customerList;
private MaskFormatter mask = null;
/**
* Create the frame.
*/
public editCustomers(ArrayList<Customers> aList) {
customerList = aList;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 600);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(6, 0, 0, 0));
JPanel panel_12 = new JPanel();
panel.add(panel_12);
panel_12.setLayout(new BorderLayout(0, 0));
JLabel lblSelectACustomer = new JLabel("Select a Customer to Edit");
panel_12.add(lblSelectACustomer, BorderLayout.WEST);
JComboBox comboBox = new JComboBox();
//comboBox.setModel(new DefaultComboBoxModel());
for (Customers temp : customerList) {
comboBox.addItem(temp.getfName());
}
panel_12.add(comboBox, BorderLayout.EAST);
JPanel panel_3 = new JPanel();
panel.add(panel_3);
panel_3.setLayout(new BorderLayout(0, 0));
JLabel lbl1 = new JLabel("Edit Customers First Name");
lbl1.setVerticalAlignment(SwingConstants.TOP);
Dimension d = lbl1.getPreferredSize();
lbl1.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_3.add(lbl1, BorderLayout.WEST);
JPanel panel_8 = new JPanel();
panel_3.add(panel_8, BorderLayout.CENTER);
textField = new JTextField();
panel_8.add(textField);
textField.setColumns(30);
JPanel panel_4 = new JPanel();
panel.add(panel_4);
panel_4.setLayout(new BorderLayout(0, 0));
JLabel lbl2 = new JLabel("Edit Customers Second Name");
lbl2.setVerticalAlignment(SwingConstants.TOP);
lbl2.getPreferredSize();
lbl2.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_4.add(lbl2, BorderLayout.WEST);
JPanel panel_9 = new JPanel();
panel_4.add(panel_9, BorderLayout.CENTER);
textField_1 = new JTextField();
panel_9.add(textField_1);
textField_1.setColumns(30);
JPanel panel_5 = new JPanel();
panel.add(panel_5);
panel_5.setLayout(new BorderLayout(0, 0));
JLabel lbl3 = new JLabel("Edit Customers Address");
lbl3.setVerticalAlignment(SwingConstants.TOP);
lbl3.getPreferredSize();
lbl3.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_5.add(lbl3, BorderLayout.WEST);
JPanel panel_10 = new JPanel();
panel_5.add(panel_10, BorderLayout.CENTER);
textField_2 = new JTextField();
panel_10.add(textField_2);
textField_2.setColumns(30);
JPanel panel_6 = new JPanel();
panel.add(panel_6);
panel_6.setLayout(new BorderLayout(0, 0));
JLabel lbl4 = new JLabel("Edit Customers Date of Birth");
lbl4.setVerticalAlignment(SwingConstants.TOP);
lbl4.getPreferredSize();
lbl4.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_6.add(lbl4, BorderLayout.WEST);
JPanel panel_11 = new JPanel();
panel_6.add(panel_11, BorderLayout.CENTER);
textField_3 = new JTextField();
try {
mask = new MaskFormatter("##/##/####");
mask.setPlaceholderCharacter(' ');
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField textField_3 = new JFormattedTextField(mask);
textField_3.setText("dd/mm/yyyy");
panel_11.add(textField_3);
textField_3.setColumns(30);
JPanel panel_2 = new JPanel();
panel.add(panel_2);
panel_2.setLayout(new BorderLayout(0, 0));
JPanel panel_7 = new JPanel();
panel_2.add(panel_7, BorderLayout.CENTER);
JButton btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_7.add(btnConfirm);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panel_7.add(btnCancel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(SystemColor.activeCaption);
contentPane.add(panel_1, BorderLayout.NORTH);
JLabel lblEditACurrent = new JLabel("Edit a Current Customer");
lblEditACurrent.setForeground(Color.BLACK);
lblEditACurrent.setFont(new Font("Arial", Font.PLAIN, 19));
lblEditACurrent.setBackground(UIManager.getColor("InternalFrame.activeTitleBackground"));
panel_1.add(lblEditACurrent);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
editCustomers frame = new editCustomers(new ArrayList<Customers>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
You can try something like this ....
Change line 63 - 67 as following. Put the customers into the combobox instead of just names.
JComboBox<Customer> comboBox = new JComboBox<>();
//comboBox.setModel(new DefaultComboBoxModel());
for (Customers temp : customerList) {
comboBox.addItem(temp);
}
Then implement an ActionListener for the combobox as following.
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Customer customer = comboBox.getSelectedItem();
// Use the above customer object's fields to populate your text fields
}
});
Like the title said, the hearder name is just not showing up. i tried many options like using a JScrollPane. and fallowed many guide on this forum but no help. I really wanted to get resolve problem by myself but i have tried everything and out of option.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.ScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
public class Adminpage extends JPanel {
private JFrame frame;
static String ID[]={"name","Username","Password"};
static DefaultTableModel model;
private JTextField NametextField;
private JTextField UsertextField;
private JTextField PasstextField;
private JTable table;
private JScrollPane scroll;
/**
* Create the panel.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 497, 545);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblAdminstratorPortal = new JLabel("Adminstrator Portal");
lblAdminstratorPortal.setFont(new Font("Tahoma", Font.BOLD, 20));
lblAdminstratorPortal.setBounds(109, 26, 218, 25);
frame.getContentPane().add(lblAdminstratorPortal);
JButton btnNewButton = new JButton("Add Librarian");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//model= (DefaultTableModel)table.getModel();
//model.addColumn("name");
//model.addColumn("Username");
//model.addColumn("Password");
model.addRow(new Object[]{NametextField.getText(),UsertextField.getText(),PasstextField.getText()});
}
});
btnNewButton.setBounds(10, 62, 108, 35);
frame.getContentPane().add(btnNewButton);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDelete.setBounds(130, 62, 108, 35);
frame.getContentPane().add(btnDelete);
JButton btnViewLibrarian = new JButton("View Librarian");
btnViewLibrarian.setBounds(245, 62, 108, 35);
frame.getContentPane().add(btnViewLibrarian);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
}
});
btnLogout.setBounds(363, 62, 108, 35);
frame.getContentPane().add(btnLogout);
//model= (DefaultTableModel)table.getModel();
JLabel lblName = new JLabel("Name");
lblName.setBounds(21, 144, 60, 14);
frame.getContentPane().add(lblName);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(21, 195, 60, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(21, 250, 60, 14);
frame.getContentPane().add(lblPassword);
NametextField = new JTextField();
NametextField.setBounds(119, 141, 119, 20);
frame.getContentPane().add(NametextField);
NametextField.setColumns(10);
UsertextField = new JTextField();
UsertextField.setColumns(10);
UsertextField.setBounds(119, 192, 119, 20);
frame.getContentPane().add(UsertextField);
PasstextField = new JTextField();
PasstextField.setColumns(10);
PasstextField.setBounds(119, 247, 119, 20);
frame.getContentPane().add(PasstextField);
table = new JTable();
table.setBounds(10, 304, 461, 189);
frame.getContentPane().add(table);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Adminpage() {
database();
setLayout(null);
initialize();
model= (DefaultTableModel)table.getModel();
model.addColumn("name");
model.addColumn("Username");
model.addColumn("Password");
}
public void database(){
try {
Class.forName("sun.jdbc.odbc.JdbsOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Games");
Statement st = con.createStatement();
String getquery = ("Select* from Games");
ResultSet rs= st.executeQuery(getquery);
while(rs.next()){
System.out.println(rs.getString(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
You're adding the JTable directly to the GUI. Instead, yes you need to embed the JTable into the viewport of a JScrollPane and then add the JScrollPane to the GUI.
For example:
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
// table.setBounds(10, 304, 461, 189);
scrollPane.setBounds(10, 304, 461, 189); // This is bad, but will leave for now
// frame.getContentPane().add(table);
frame.getContentPane().add(scrollPane);
Also, you're harming your GUI by using null layouts and absolute positioning, as this can interfere with a component's ability to show itself fully and correctly, to achieve its own preferred size. Much better is to learn and use the layout managers.
For instance, when I run your program on my platform, I see:
Note how the buttons do not show their full texts due to their not being allowed to achieve their preferred sizes.
For example, using BoxLayout with some nested JPanels, one using GridLayout(1, 0, 5, 0) for one row, variable number of columns, and a 5 point horizontal gap between components, and another nested JPanel using GridBagLayout, for placement of JTextFields and JLabels, and some "wrapper" JPanels using default FlowLayout to center components within them...
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AdminPage2 extends JPanel {
private static final long serialVersionUID = 1L;
public static final String TITLE = "Administrator Portal";
private static final Font TITLE_FONT = new Font("Tahoma", Font.BOLD, 20);
private static final String[] COL_NAMES = {"Name", "User Name", "Password"};
private int txtFieldCols = 20;
private JTextField nameField = new JTextField(txtFieldCols);
private JTextField userNameField = new JTextField(txtFieldCols);
private JPasswordField passwordField = new JPasswordField(txtFieldCols);
private DefaultTableModel tableModel = new DefaultTableModel(COL_NAMES, 0);
private JTable table = new JTable(tableModel);
private JScrollPane tableScrollPane = new JScrollPane(table);
public AdminPage2() {
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(TITLE_FONT);
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
// of course you'd add ActionListeners or Actions to your buttons
buttonPanel.add(new JButton("Add Library"));
buttonPanel.add(new JButton("Delete"));
buttonPanel.add(new JButton("View Library"));
buttonPanel.add(new JButton("Logout"));
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
JPanel wrapTfPanel = new JPanel();
wrapTfPanel.add(textFieldPanel);
Dimension scrollPanePrefSz = tableScrollPane.getPreferredSize();
int w = scrollPanePrefSz.width;
int h = scrollPanePrefSz.height / 2;
scrollPanePrefSz = new Dimension(w, h);
tableScrollPane.setPreferredSize(scrollPanePrefSz);
// put together main JPanel components
int ebGap = 4;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(Box.createVerticalStrut(5));
add(titlePanel);
add(Box.createVerticalStrut(5));
add(buttonPanel);
add(Box.createVerticalStrut(5));
add(wrapTfPanel);
add(Box.createVerticalStrut(5));
add(tableScrollPane);
}
// create constraints to use when adding component to GridBagLayout
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
int in = 10;
int leftIn = x == 0 ? 4 * in : in;
gbc.insets = new Insets(in, leftIn, in, in);
return gbc;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
AdminPage2 mainPanel = new AdminPage2();
JFrame frame = new JFrame("Administrator Page");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Which displays as:
Regarding your questions:
but new question why give the scrollpane a bound instead of the table itself
The JScrollPane holds the JTable within it, and so if you use null layouts (which you shouldn't), and you're adding this JTable-containing JScrollPane to the GUI, you must set its bounds. Much better though is to use layout managers as I've outlined above. It makes it much easier to modify the GUI later and to debug it now.
and why adding the scrollpane into the panel instead of the table.
Because that's how JScrollPanes work. They don't add scrollbars to a component but rather nest the component itself, here the JTable, within the JScrollPane's viewport. Please read the JScrollPane Tutorial (see link) to see the details on this.
A further note on the power of layout managers. Say you want to add a new JLabel / JTextField combination, one that accepts a password hint, and say the JTextField's name is passwordHint. If you were using null layouts and absolute positioning, you'd have to set the bounds of your new JLabel and JTextField, but you'd also have to change the bounds of all components below and to the right of it, and would have to re-set the size of the GUI manually. If your GUI is very complex, this can lead to bugs and a lot of frustration.
If you used the layout managers above however, all you'd need to do would be to add two lines of code to the textFieldPanel JPanel creational code as shown below with the obvious comments:
// original textFieldPanel creational code
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
// !! ****** these lines added ******
textFieldPanel.add(new JLabel("Password Hint:"), createGbc(0, 3));
textFieldPanel.add(passwordHint, createGbc(1, 3));
This results in a perfect placement of the new components without adversely affecting the old:
I don't understand why the last part doesn't add to my interface. I tried different approaches, but none of them seems to work. I can't add 1024 labels to my panel this way. Did I do something wrong, or is there an alternative to this?
Can tell me what could be wrong with the code? Thanks!
Full code here:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.border.LineBorder;
public class CacheGUI extends JFrame {
private static final int LEN = 1024;
private static final long serialVersionUID = 1L;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CacheGUI frame = new CacheGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public CacheGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 500);
getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Lista de referinte", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(6, 16, 124, 364);
getContentPane().add(panel);
panel.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 16, 108, 340);
panel.add(scrollPane);
JTextPane txtpnDasd = new JTextPane();
txtpnDasd.setToolTipText("Lista curenta de adrese");
txtpnDasd.setEnabled(false);
txtpnDasd.setEditable(false);
scrollPane.setViewportView(txtpnDasd);
txtpnDasd.setText("<generate first>");
JButton btnGenerate = new JButton("GENERATE");
btnGenerate.setToolTipText("Incepe generarea listei de adrese.");
btnGenerate.setBounds(6, 422, 124, 23);
getContentPane().add(btnGenerate);
JButton btnStart = new JButton("START");
btnStart.setToolTipText("Ruleaza simularea");
btnStart.setBounds(550, 422, 124, 23);
getContentPane().add(btnStart);
JLabel lblBlockSize = new JLabel("Block size:");
lblBlockSize.setFont(new Font("Tahoma", Font.BOLD, 12));
lblBlockSize.setBounds(6, 394, 85, 14);
getContentPane().add(lblBlockSize);
textField = new JTextField();
textField.setToolTipText("");
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setText("4");
textField.setBounds(79, 391, 51, 20);
getContentPane().add(textField);
textField.setColumns(10);
int blocksize = Integer.parseInt(textField.getText());
int nrofblocks = LEN/blocksize; // LEN is 1024
JPanel block_panel = new JPanel();
block_panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
block_panel.setBounds(140, 16, 534, 398);
getContentPane().add(block_panel);
block_panel.setLayout(new GridLayout(blocksize,nrofblocks,2,0));
// THIS IS THE PART THAT DOES NOT ADD TO THE PANEL I CREATED BEFORE --->
JLabel[] lbl=new JLabel[LEN];
for(int i=0;i<LEN;i++)
{
lbl[i]=new JLabel("TEST");
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
block_panel.add(lbl[i]); // i want to create yellow blocks inside my panel as labels to modyfy the color afterwards
}//<----
}
}
The issue is the ridiculous number of labels you have; they're there.
Set the bounds of the block panel to something larger, reduce LEN, etc. and you'll see them.
First things first: Your labels won't have a yellow background color. JLabels are not opaque by default. Setting it to true will show the yellow background as before:
lbl[i].setOpaque(true);
The second thing is the sheer number of labels you have. Reduce the number to 100 say, and you'll see you labels.
for(int i=0;i<100;i++)
{
lbl[i]=new JLabel("TEST");
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
lbl[i].setOpaque(true);
block_panel.add(lbl[i]);
}
Use a JScrollPane, set opaque, grid layout 1.rows, 2.columns, set fixed size for label,
use BorderFactory.
JPanel block_panel = new JPanel();
block_panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING,
TitledBorder.TOP, null, null));
block_panel.setBounds(140, 16, 534, 398);
JScrollPane block_scrollpane = new JScrollPane(block_panel);
block_scrollpane.setBounds(140, 16, 534, 398);
getContentPane().add(block_scrollpane);
//block_panel.setLayout(new GridLayout(blocksize, nrofblocks, 2, 0));
block_panel.setLayout(new GridLayout(nrofblocks, blocksize, 2, 0));
// THIS IS THE PART THAT DOES NOT ADD TO THE PANEL I CREATED BEFORE --->
JLabel[] lbl = new JLabel[LEN];
Dimension lblSize = new Dimension(85, 16);
for (int i = 0; i < LEN; i++) {
lbl[i] = new JLabel("TEST" + i);
lbl[i].setOpaque(true);
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1, true));
lbl[i].setPreferredSize(lblSize);
lbl[i].setMinimumSize(lblSize);
block_panel.add(lbl[i]); // i want to create yellow blocks
// inside my panel as labels to modyfy the color afterwards
}//<----
What I am trying to do is this,
when I enter the details it will validate if the textFiled is empty when a button is pressed, if it is empty it will display a message saying that.
Then it will move to the next textFile similar to many web based registration forms,
what I am trying to find out is why wont the message change?
Pasting this code into an ecilpse file and running it should display the simple frame and what I am trying to do.
The message displays on the bottom of the frame when the firstname field is empty,
can anyone explain why it doesn't show the next message when the firstname field containes text and the middlename contains no text?
Most of the logic is at the bottom of the code.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.JPanel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class start {
private JFrame frame;
private JTextField tfFirstname;
private JTextField tfMiddlenames;
private JTextField tfSurname;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
start window = new start();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public start() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 505, 429);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final JPanel panelClientNew = new JPanel();
panelClientNew.setBackground(new Color(0, 102, 255));
panelClientNew.setBounds(10, 11, 469, 299);
frame.getContentPane().add(panelClientNew);
panelClientNew.setLayout(null);
JLabel lblFirstname = new JLabel("Firstname :");
lblFirstname.setHorizontalAlignment(SwingConstants.RIGHT);
lblFirstname.setVerticalAlignment(SwingConstants.BOTTOM);
lblFirstname.setForeground(new Color(255, 255, 255));
lblFirstname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblFirstname.setBounds(10, 16, 163, 14);
panelClientNew.add(lblFirstname);
tfFirstname = new JTextField();
tfFirstname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfFirstname.setBounds(177, 10, 282, 27);
panelClientNew.add(tfFirstname);
tfFirstname.setColumns(10);
JLabel lblMiddlenames = new JLabel("Middlenames :");
lblMiddlenames.setHorizontalAlignment(SwingConstants.RIGHT);
lblMiddlenames.setForeground(new Color(255, 255, 255));
lblMiddlenames.setFont(new Font("Tahoma", Font.BOLD, 13));
lblMiddlenames.setBounds(10, 47, 163, 14);
panelClientNew.add(lblMiddlenames);
tfMiddlenames = new JTextField();
tfMiddlenames.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfMiddlenames.setBounds(177, 41, 282, 27);
panelClientNew.add(tfMiddlenames);
tfMiddlenames.setColumns(10);
JLabel lblSurname = new JLabel("Surname :");
lblSurname.setHorizontalAlignment(SwingConstants.RIGHT);
lblSurname.setForeground(new Color(255, 255, 255));
lblSurname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblSurname.setBounds(10, 78, 163, 14);
panelClientNew.add(lblSurname);
tfSurname = new JTextField();
tfSurname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfSurname.setBounds(177, 72, 282, 27);
panelClientNew.add(tfSurname);
tfSurname.setColumns(10);
JButton btnAdd = new JButton("Add");
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
/*
*
*
*
*I am trying to create a message that validates on certain circumstances
*
*
*
*/
if(tfFirstname.getText().equals(null) || tfFirstname.getText().equals("") || tfFirstname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Firstname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfMiddlenames.getText().equals(null) || tfMiddlenames.getText().equals("") || tfMiddlenames.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Middlenames :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfSurname.getText().equals(null) || tfSurname.getText().equals("") || tfSurname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Surname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else {
//Validation has passed
}
}
});
btnAdd.setBounds(370, 265, 89, 23);
panelClientNew.add(btnAdd);
}
}
I recommend that you use an InputVerifier as this will verify that the contents of the JTextField are correct (any way that you wish to define this) before allowing you to even leave the JTextField. Now it won't stop you from pressing other JButtons and whatnot, so you'll need to take other precautions if you have a submit button. An example of a simple InputVerifier that checks to see if the JTextField is empty is shown below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(true);
JPanel namePanel = new JPanel();
namePanel.add(new JLabel("Name:"));
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
add(warningLabel, BorderLayout.SOUTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty");
warningLabel.setBackground(WARNING_COLOR);
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
have look at DocumentListener,
on start_up to enable only first JTextField, if any (up to you) character was typed into first JTextField, then enable second JTextField, and so on...,
if you want to filtering, change or replace output came from keyboard the to use DocumentFilter
change background for example to Color.red (from DocumentListeners events), in the case that one of JTextFields contains incorect lenght, data e.g.
agree with HFOE about LayoutManagers