I want to create this GUI Layout with java Swing - java

enter code here
public class NWAHome {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public NWAHome(){
prepareGUI();
}
public static void main(String[] args){
NWAHome swingMenuDemo = new NWAHome();
swingMenuDemo.showMenuDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Produkt anlegen");
mainFrame.setSize(400,400);
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
mainFrame.getContentPane().setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("128px"),
ColumnSpec.decode("128px"),
ColumnSpec.decode("128px"),},
new RowSpec[] {
RowSpec.decode("113px"),
RowSpec.decode("113px"),
RowSpec.decode("113px"),}));
mainFrame.getContentPane().add(headerLabel, "1, 1, fill, fill");
mainFrame.getContentPane().add(controlPanel, "3, 1, 1, 2, fill, fill");
controlPanel.setLayout(new MigLayout("", "[][]", "[][][][][]"));
JButton btnNewButton_1 = new JButton("Projekt anzeigen");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
controlPanel.add(btnNewButton_1, "flowy,cell 1 0");
JButton button_1 = new JButton("Projekt anlegen");
controlPanel.add(button_1, "cell 1 0");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
JButton button = new JButton("Projekt ändern");
controlPanel.add(button, "cell 1 1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
JButton button_2 = new JButton("Projekt löschen");
controlPanel.add(button_2, "flowy,cell 1 2");
JButton btnNewButton = new JButton("Projekt kopieren");
controlPanel.add(btnNewButton, "cell 1 2");
JButton button_3 = new JButton("Projekt archivieren");
controlPanel.add(button_3, "cell 1 3");
JButton button_4 = new JButton("Projekt importieren");
controlPanel.add(button_4, "cell 1 4");
mainFrame.getContentPane().add(statusLabel, "1, 2, fill, fill");
mainFrame.setVisible(true);
}
private void showMenuDemo(){
//create a menu bar
final JMenuBar menuBar = new JMenuBar();
//create menus
JMenu fileMenu = new JMenu("Projekt");
JMenu editMenu = new JMenu("Produkt");
final JMenu aboutMenu = new JMenu("Kriterien");
final JMenu linkMenu = new JMenu("Bewertung");
//create menu items
JMenuItem newMenuItem = new JMenuItem("Anlegen");
newMenuItem.setMnemonic(KeyEvent.VK_N);
newMenuItem.setActionCommand("New");
JMenuItem openMenuItem = new JMenuItem("Anzeigen");
openMenuItem.setActionCommand("Anzeigen");
JMenuItem saveMenuItem = new JMenuItem("Ändern");
saveMenuItem.setActionCommand("Ändern");
JMenuItem cutMenuItem = new JMenuItem("Löschen");
cutMenuItem.setActionCommand("Löschen");
JMenuItem copyMenuItem = new JMenuItem("Kopieren");
copyMenuItem.setActionCommand("Kopieren");
JMenuItem archivierenMenuItem = new JMenuItem("Archivieren");
archivierenMenuItem.setActionCommand("Archivieren");
JMenuItem importierenMenuItem = new JMenuItem("Importieren");
importierenMenuItem.setActionCommand("importieren");
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.setActionCommand("Exit");
MenuItemListener menuItemListener = new MenuItemListener();
newMenuItem.addActionListener(menuItemListener);
openMenuItem.addActionListener(menuItemListener);
saveMenuItem.addActionListener(menuItemListener);
exitMenuItem.addActionListener(menuItemListener);
cutMenuItem.addActionListener(menuItemListener);
copyMenuItem.addActionListener(menuItemListener);
importierenMenuItem.addActionListener(menuItemListener);
final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem("Show About", true);
showWindowMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(showWindowMenu.getState()){
menuBar.add(aboutMenu);
}else{
menuBar.remove(aboutMenu);
}
}
});
final JRadioButtonMenuItem showLinksMenu =
new JRadioButtonMenuItem("Show Links", true);
showLinksMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(menuBar.getMenu(3)!= null){
menuBar.remove(linkMenu);
mainFrame.repaint();
}else{
menuBar.add(linkMenu);
mainFrame.repaint();
}
}
});
//add menu items to menus
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(showWindowMenu);
fileMenu.addSeparator();
fileMenu.add(showLinksMenu);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add( importierenMenuItem);
//add menu to menubar
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(aboutMenu);
menuBar.add(linkMenu);
//add menubar to the frame
mainFrame.setJMenuBar(menuBar);
mainFrame.setVisible(true);
}
class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
statusLabel.setText(e.getActionCommand()
+ " JMenuItem clicked.");
}
}
}
Please can someone help me. I want to create this database GUI Layout so that when i click on enter button a new row appers but i don't kwow how to do it. I'm a new Java user and i'm trying to improve my Skills.
Thank you

I will provide assistance rather than providing code here what iam saying is a very basic one
1.first create a textfield and a button as
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
2.get entered text in textfield as testField.getText()
3.Assign this value to some variable say data
4.on button click insert retrieve data from text field as
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String data = testField.getText();
// .... do some operation on value ...
}
})
5.In action event use code to insert data into database using query
insert into createdtablename values('data');
here createdtablename is name of your created table
Hope my assistance guide you in right path how to do so.

Related

Loading images via JFileChooser

3 Classes - GUI, ImageLoader and Wizard
GUI is the main frame whereas Wizard is just a popup that changes settings and imageloader is image handler
What I want is to load image from wizard to Jlabel on my main GUI but I have no idea where to start and never had experience with loading images onto GUI. Searching for answer on here didn't really help, it just create more confusion for me. I would appreciate if you also can add explanations as well.
GUI -
public class GUI extends JPanel{
//variables
JFrame frame = new JFrame("All-in-one Application");
JMenuBar menuBar;
JMenu file, edit, help, about;
JMenuItem settings, startWizard, exit, save, load, readme;
JLabel imgLabel;
private Wizard wiz;
public void topMenuBar(){
//creating the menubar
menuBar = new JMenuBar();
//Menu
file = new JMenu("File");
edit = new JMenu("Edit");
help = new JMenu("Help");
about = new JMenu("About");
//MenuItems
startWizard = new JMenuItem("Start Wizard");
//listener for wizard
Wizard wiz = new Wizard();
// GUIListener gListener = new GUIListener();
startWizard.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
wiz.startWizardd();
}
});
settings = new JMenuItem("Settings");
readme = new JMenuItem("Read Me");
exit = new JMenuItem("Exit");
save = new JMenuItem("Save");
load = new JMenuItem("Load");
//jbutton
// test = new JButton("Test");
//adding MenuItems to the Menu
/**file**/
file.add(startWizard);
file.add(new JSeparator());
file.add(save);
file.add(load);
file.add(new JSeparator());
file.add(exit);
//end file
//edit
edit.add(settings);
//help
help.add(readme);
//about
//Adding Menu to the menu bar
menuBar.add(file);
menuBar.add(edit);
menuBar.add(help);
menuBar.add(about);
//exit action listener
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
}
public void mainPanel(){
FlowLayout main = new FlowLayout();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(main);
//jlabel
imgLabel = new JLabel("img");
mainPanel.add(imgLabel);
frame.add(mainPanel, BorderLayout.CENTER);
}
//intiate GUI
public void intGUI(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300,0);
frame.setSize(1400,1000);
topMenuBar();
mainPanel();
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
}
Wizard:
public class Wizard extends JPanel{
//variables
private ImageLoader imgload = new ImageLoader(this);
private JButton applyButton, nextButton, backButton, cancelButton, openMapButton;
JDialog wizDialog;
JFrame wizFrame;
JLabel siteNameLabel, siteMapLabel, AisleNumLabel, laneNumLabel, label;
JTextField siteNameField, aisleNumField, laneNumField;
private JTextField mapURLField = new JTextField(20);
JFileChooser chooser;
private File file;
String fileName;
BufferedImage img; // private JPanel addInfoPanel, controlPanel;
public void startWizardd(){
System.out.println("Starting Wizard....");
wizardGUI();
}
public void wizardCmpt()
{
//setting the panel up with gridlayout settings
FlowLayout map = new FlowLayout();
JPanel mapPanel = new JPanel();
mapPanel.setLayout(map);
FlowLayout grid = new FlowLayout();
JPanel addInfoPanel = new JPanel();
addInfoPanel.setLayout(grid);
FlowLayout controls = new FlowLayout();
JPanel controlPanel = new JPanel();
controlPanel.setLayout(controls);
//buttons
JButton openMapButton = new JButton("Load Map");
openMapButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
imgload.fileChooser();
}
});
JButton applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton nextButton = new JButton("Next");
JButton backButton = new JButton("Back");
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
wizFrame.setVisible(false);
wizFrame.dispose();
}
});
//jlabels
JLabel siteNameLabel = new JLabel("Site Name :");
JLabel siteMapLabel = new JLabel("Site Map :");
JLabel AisleNumLabel = new JLabel("Number of Aisles :");
JLabel laneNumLabel = new JLabel("Number of Lanes :");
//jtextfield
JTextField siteNameField = new JTextField(5);
JTextField aisleNumField = new JTextField(5);
JTextField laneNumField = new JTextField(5);
//adding to GUI
addInfoPanel.add(siteNameLabel);
addInfoPanel.add(siteNameField);
addInfoPanel.add(AisleNumLabel);
addInfoPanel.add(aisleNumField);
addInfoPanel.add(laneNumLabel);
addInfoPanel.add(laneNumField);
mapPanel.add(siteMapLabel);
mapPanel.add(mapURLField);
mapPanel.add(openMapButton);
controlPanel.add(applyButton);
// controlPanel.add(nextButton);
// controlPanel.add(backButton);
controlPanel.add(cancelButton);
wizFrame.add(addInfoPanel, BorderLayout.NORTH);
wizFrame.add(mapPanel, BorderLayout.CENTER);
wizFrame.add(controlPanel, BorderLayout.SOUTH);
}
public void setMapUrlField(String text){
mapURLField.setText(text);
}
public File getFile(){
return file;
}
private void wizardGUI(){
System.out.println("it's loading");
wizFrame = new JFrame("Wizard Operation");
wizFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
wizFrame.setSize(600,600);
wizardCmpt();
wizFrame.pack();
wizFrame.setVisible(true); } }
Image Loader:
public class ImageLoader{
private JLabel label;
JFileChooser chooser;
File file;
private BufferedImage img;
private Wizard wiz;
public ImageLoader(Wizard wiz){
this.wiz = wiz;
}
public File fileChooser(){
File file = null;
JFileChooser fileChooser = new JFileChooser();
FileFilter imageFilter = new FileNameExtensionFilter("Image files ", ImageIO.getReaderFileSuffixes());
fileChooser.setFileFilter(imageFilter);
int retValue = fileChooser.showOpenDialog(wiz);
if(retValue == JFileChooser.APPROVE_OPTION){
file = fileChooser.getSelectedFile();
wiz.setMapUrlField(file.getAbsolutePath());
}else{
wiz.setMapUrlField("");
}
return file;
}
}

How would I fill my TextFields after I select an item from JList

i'm having some trouble with a homework problem, and still trying to wrap my head around GUI logically. I have created all my text fields (contactType, name, address, city, state, etc...) and have created an actionListener to populate my JList with names when I click open from the JMenu. I'm running into trouble filling in the appropriate text fields when I select the name from the list. I tried to just print out to console to see if it would print out at least the name, but that's not even working. Any help would be great, thanks.
Here's some of my code so far:
public class AddressBookGUI extends JFrame
{
private final int WIDTH = 450;
private final int HEIGHT = 300;
private JLabel currentlySelected;
private JTextField contactTypeTextField;
private JTextField nameTextField;
private JTextField streetAddressTextField;
private JTextField cityTextField;
private JTextField stateTextField;
private JTextField zipTextField;
private JTextField phoneTextField;
private JTextField emailTextField;
private JTextField photoTextField;
private JList nameList ;
private DefaultListModel model;
private JTextArea statusTextArea;
private AddressBook addressBook;
private JButton addButton;
private JButton editButton;
private JButton sortByZipButton;
private JMenuItem addItem;
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem exitItem;
private JMenuItem editContactItem;
private JMenuItem aboutItem;
private JMenuItem deleteItem;
private JComboBox<String> jComboStates;
private JComboBox <Enum> jComboContactType;
private String [] readStates()
{
ArrayList<String> array = new ArrayList<>();
try
{
FileInputStream fStream = new FileInputStream ("States.txt");
BufferedReader buffer = new BufferedReader (new InputStreamReader (fStream));
String strLine;
while ((strLine = buffer.readLine()) != null)
{
String line = buffer.readLine();
String [] state = line.split ("\n");
array.add(strLine);
}
buffer.close();
}
catch (Exception e)
{
}
return array.toArray(new String[array.size()]);
}
private ArrayList<String> readContacts()
{
File cFile = new File ("Contacts.txt");
BufferedReader buffer = null;
ArrayList <String> contact = new ArrayList<String>();
try
{
buffer = new BufferedReader (new FileReader (cFile));
String text;
String sep;
while ((sep = buffer.readLine()) != null)
{
String [] name = sep.split (",");
text = name[1];
contact.add(text);
}
}
catch (FileNotFoundException e)
{
System.out.print ("error");
}
catch (IOException k)
{
System.out.print ("error);
}
return contact;
}
{
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu ("File");
openItem = new JMenuItem ("Open...");
fileMenu.add (openItem);
fileMenu.addSeparator();
saveItem = new JMenuItem ("Save...");
fileMenu.add (saveItem);
fileMenu.addSeparator();
exitItem = new JMenuItem ("Exit");
fileMenu.add (exitItem);
JMenu editMenu = new JMenu ("Edit");
editContactItem = new JMenuItem ("Edit Contact");
editMenu.add (editContactItem);
addItem = new JMenuItem ("Add Contact");
editMenu.add (addItem);
deleteItem = new JMenuItem ("Delete Contact");
editMenu.add (deleteItem);
JMenu helpMenu = new JMenu ("Help");
aboutItem = new JMenuItem ("About");
helpMenu.add(aboutItem);
menuBar.add (fileMenu);
menuBar.add (editMenu);
menuBar.add (helpMenu);
setJMenuBar (menuBar);
//code that creates new text fields for all attributes
//code that sets textfields to uneditable
JPanel topPanel = new JPanel()
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.add (currentlySelected, BorderLayout.CENTER);
leftPanel.add (new JScrollPane(), BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
JPanel infoPanel = new JPanel (new BorderLayout());
GridLayout layout = new GridLayout (9,1);
JPanel labelsPanel = new JPanel (layout);
JPanel valuesPanel = new JPanel (layout);
// code that added lables and values to panel
infoPanel.add (labelsPanel, BorderLayout.WEST);
infoPanel.add (valuesPanel, BorderLayout.CENTER);
centerPanel.add (infoPanel);
setLayout (new BorderLayout());
add (topPanel, BorderLayout.NORTH);
add (leftPanel, BorderLayout.WEST);
add (centerPanel, BorderLayout.CENTER);
addressBook = new AddressBook();
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
openItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
readContacts();
for (String name :readContacts())
{
model.addElement(name);
}
nameList = new JList (model);
add(nameList);
nameList.setVisibleRowCount(10);
nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
nameList.setFixedCellHeight (20);
nameList.setFixedCellWidth (130);
JPanel left = new JPanel(new BorderLayout());
left.add (new JScrollPane(nameList), BorderLayout.NORTH);
add (left, BorderLayout.WEST);
nameList.setBorder (BorderFactory.createLineBorder(Color.BLACK,1));
}
});
editContactItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
nameTextField.setEditable (true);
streetAddressTextField.setEditable (true);
cityTextField.setEditable (true);
jComboStates.setEditable (true);
zipTextField.setEditable (true);
phoneTextField.setEditable (true);
emailTextField.setEditable (true);
photoTextField.setEditable (true);
}
});
saveItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
addressBook.Save ( );
}
});
nameList = new JList ();
nameList.addListSelectionListener (new ListSelectionListener()
{
public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting ( ) == false)
{
List <String> string = nameList.getSelectedValuesList();
System.out.print (string);
}
}
});
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = nameList.locationToIndex(e.getPoint());
System.out.println("Double clicked on Item " + index);
}
}
};
nameList.addMouseListener(mouseListener);
}
I tried cut out some of the tedious code to keep it short. If I could get a skeleton or a nudge in the right direction, it would be a great help.
So i've changed it up a bit, once I select open, it populates the JList with the names, then when I double click on a name it only fills the nameTextField, addressTextField, and cityTextField all with the name of the contact I selected
ex) Name: Zoidberg, Address: Zoidberg, City: Zoidberg
here's my code:
openItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
readContacts();
for (String name :readContacts())
{
model.addElement(name);
}
nameList = new JList (model);
add(nameList);
nameList.setVisibleRowCount(10);
nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
nameList.setFixedCellHeight (20);
nameList.setFixedCellWidth (130);
JPanel left = new JPanel(new BorderLayout());
left.add (new JScrollPane(nameList), BorderLayout.NORTH);
add (left, BorderLayout.WEST);
nameList.setBorder (BorderFactory.createLineBorder(Color.BLACK,1));
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = nameList.locationToIndex(e.getPoint());
if (nameList.getModel().getElementAt(index) != null && nameList.getModel().getElementAt(index) instanceof String)
{
nameTextField.setText((String) nameList.getModel().getElementAt (index));
streetAddressTextField.setText((String) nameList.getModel().getElementAt (index));
cityTextField.setText((String) nameList.getModel().getElementAt (index));
stateTextField.setText((String) nameList.getModel().getElementAt (index));
zipTextField.setText((String) nameList.getModel().getElementAt (index));
phoneTextField.setText((String) nameList.getModel().getElementAt (index));
emailTextField.setText((String) nameList.getModel().getElementAt (index));
photoTextField.setText((String) nameList.getModel().getElementAt (index));
}
}
}
};
nameList.addMouseListener(mouseListener);
nameList = new JList (model);
You add data to the JList with the above code.
But then later you do:
nameList = new JList ();
nameList.addListSelectionListener (new ListSelectionListener()
{
public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting ( ) == false)
{
List <String> string = nameList.getSelectedValuesList();
System.out.print (string);
}
}
});
Which creates an empty List and adds a ListSelectionListener to this list. This serves no purpose since the JList is empty and is not visible on the GUI anyway.
Add the ListSelectListener to the JList when you create the JList and add data to it:
nameList = new JList (model);
nameList.addListSelectionListener(...);
I second all that Rob Camick writes. Also, you're only adding name Strings to your list and not complete Address objects, and so key information is lost. To gain it, make your JList a list of Address objects, give it a custom cell renderer that shows only the name, but this will allow your selected object to have all the data that you need.

Find and Replace not working Java Swing

I'm making a simple text editor in Java and for some reason my find and replace actions won't work, i made two separate frames, one for the find action, and the other to open up another frame with 2 jtextfields for find and replace. i have in my actionperformed
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
and in my findFrame i have the action that should be carried out when the user clicks on the JMenuItem called "Find".
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
In my Replace frame where i want the user to find a word and replace it, anything you type into the find textfield and click the find button, it finds the first 3 characters on the text field, and the replace action just doesn't work at all,
here is my replace frame
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
the find and replace are two separate JMenuItems, when the user clicks on Find it opens up findframe and when they click on "replace" it opens up the replace frame which has a find textfield and a replace textfield.
here is the whole runnable code :
//Programmer Aly Badran – Project 10
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.DefaultEditorKit.CutAction;
class saveFrame extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel labelpanel = new JPanel();
JButton savebutton = new JButton("Save");
JButton dontsave = new JButton("Dont Save");
JLabel savelabel = new JLabel("Are you sure you want to close"?);
public saveFrame(){
setSize(400,100);
setLocation(500, 300);
setTitle("Saving...");
labelpanel.add(savelabel);
panel.add(savebutton);
panel.add(dontsave);
Container cpane = getContentPane();
cpane.add(panel, "South");
cpane.add(labelpanel, "Center");
setVisible(true);
savebutton.addActionListener(this);
dontsave.addActionListener(this);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if(source == savebutton){
System.exit(0);
}
else if(source == dontsave){
System.exit(0);
}
}
}
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
class MenuFrame extends JFrame implements ActionListener, MouseListener{
static JTextArea textarea = new JTextArea();
static JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenuItem copy = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cut = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem Paste = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenuItem copyAction = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cutAction = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem pasteAction = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenu search = new JMenu("Search");
JMenuItem open = new JMenuItem("Open");
JMenuItem close = new JMenuItem("Close");
JMenuItem quit = new JMenuItem("Quit");
JMenuItem find = new JMenuItem("Find");
JMenuItem replace = new JMenuItem("Replace");
JMenu font = new JMenu("Font");
JCheckBoxMenuItem bold = new JCheckBoxMenuItem("Bold");
JCheckBoxMenuItem italic = new JCheckBoxMenuItem("Italic");
JPopupMenu popup;
public MenuFrame(){
Container cpane = getContentPane();
cpane.add(textarea);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenheight = d.height;
int screenwidth = d.width;
setSize(screenwidth, screenheight);
JPanel panel = new JPanel();
ImageIcon closeicon = new ImageIcon("bin/close.png");
ImageIcon openicon = new ImageIcon("bin/open.png");
ImageIcon quiticon = new ImageIcon("bin/quit.jpeg");
ImageIcon findicon = new ImageIcon("bin/find.png");
ImageIcon replaceicon = new ImageIcon("bin/replace.png");
ImageIcon boldicon = new ImageIcon("bin/bold.png");
ImageIcon italicicon = new ImageIcon("bin/italic.png");
ImageIcon copyicon = new ImageIcon("bin/copy.png");
ImageIcon cuticon = new ImageIcon("bin/cut.png");
ImageIcon pasteicon = new ImageIcon("bin/paste.png");
Border matte = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK);
Border etched = BorderFactory.createEtchedBorder();
popup = new JPopupMenu();
copy.setText("Copy");
cut.setText("Cut");
Paste.setText("Paste");
copy.setIcon(copyicon);
cut.setIcon(cuticon);
Paste.setIcon(pasteicon);
copyAction.setText("Copy");
cutAction.setText("Cut");
pasteAction.setText("Paste");
copyAction.setIcon(copyicon);
cutAction.setIcon(cuticon);
pasteAction.setIcon(pasteicon);
popup.add(cut);
popup.addSeparator();
popup.add(copy);
popup.addSeparator();
popup.add(Paste);
popup.addSeparator();
popup.add(find);
popup.addSeparator();
popup.add(replace);
edit.add(cutAction);
edit.addSeparator();
edit.add(copyAction);
edit.addSeparator();
edit.add(pasteAction);
find.setIcon(findicon);
replace.setIcon(replaceicon);
close.setIcon(closeicon);
menubar = new JMenuBar();
textarea = new JTextArea("He has achieved success.", d.width, d.height);
JScrollPane scroll = new JScrollPane(textarea);
cpane.add(scroll);
open = new JMenuItem("Open", openicon);
close = new JMenuItem("Close", closeicon);
quit = new JMenuItem("Quit", quiticon);
find = new JMenuItem("Find", findicon);
replace = new JMenuItem("Replace", replaceicon);
bold = new JCheckBoxMenuItem("Bold", boldicon);
italic = new JCheckBoxMenuItem("Italic", italicicon);
textarea.setLineWrap(true);
file.add(open);
file.addSeparator();
file.add(close);
file.addSeparator();
file.add(quit);
menubar.add(file);
menubar.add(edit);
menubar.add(search);
menubar.add(font);
search.add(find);
search.addSeparator();
search.add(replace);
font.add(bold);
font.addSeparator();
font.add(italic);
copy.setEnabled(false);
cut.setEnabled(false);
Paste.setEnabled(false);
find.addActionListener(this);
italic.addActionListener(this);
bold.addActionListener(this);
quit.addActionListener(this);
close.addActionListener(this);
find.addActionListener(this);
replace.addActionListener(this);
cut.addActionListener(this);
copy.addActionListener(this);
Paste.addActionListener(this);
cut.addMouseListener(this);
textarea.addMouseListener(this);
copy.addMouseListener(this);
Paste.addMouseListener(this);
textarea.setComponentPopupMenu(popup);
file.setBackground(Color.BLACK);
edit.setBackground(Color.BLACK);
search.setBackground(Color.BLACK);
font.setBackground(Color.BLACK);
panel.add(menubar);
menubar.setBorder(matte);
menubar.setBackground(Color.BLACK);
textarea.setBorder(etched);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
String command = evt.getActionCommand();
String s = textarea.getSelectedText();
Font f = new Font("Italic", Font.ITALIC, 13);
Font f2 = new Font("Bold", Font.BOLD, 13);
if(italic.isSelected()){
textarea.setFont(f);
}
if(bold.isSelected()){
textarea.setFont(f2);
}
if(bold.isSelected() && italic.isSelected()){
textarea.setFont(f);
textarea.setFont(f2);
}
if(command.equals("Quit"))
System.exit(0);
if(command.equals("Close")){
JFrame frame = new saveFrame();
frame.setVisible(true);
}
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
if(command.equals("Replace")){
JFrame frame2 = new replaceFrame();
frame2.setVisible(true);
}
}
public void mouseClicked(MouseEvent e) {
boolean s = textarea.getSelectedText() != null;
if(s){
copy.setEnabled(true);
cut.setEnabled(true);
Paste.setEnabled(true);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
}
public class Menus {
public static void main(String [] args){
JFrame frame = new MenuFrame();
frame.setJMenuBar(MenuFrame.menubar);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Your basic problem comes down to the fact that the "selection" highlight won't be painted while the JTextArea doesn't have focus, I know, awesome.
However, you could use a Highlighter instead, for example...
if (source == find) {
try {
DefaultHighlighter.DefaultHighlightPainter highlighter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor("TextArea.selectionBackground"));
MenuFrame.textarea.getHighlighter().addHighlight(n, n + search.length(), highlighter);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
Which will paint a "highlight" over the specified area.
You may want to have a look at this for away to remove it
This and this may also be of interest
In your replace method, you are using the text of the find JButton instead of the findtext JTextField
//String search = find.getText();
String search = findtext.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
Your codes also a mess (sorry, took me a while to navigate it).
For example, you're adding a ActionListener twice to the find menu item and probably some others, which caused to find windows to appear.
I'd avoid using Toolkit#getScreenSize(); in connection with JFrame#setSize, a better solution would be to use JFrame#setExtendedState and pass it JFrame#MAXIMIZED_BOTH, as this will also take into consideration the other UI assets that the OS may have fixed on the screen (like docks and task bars).
You really should be using dialogs instead of JFrames for your "short term input" mechanisms
Your also recreating a bunch of stuff you've already created, for example...
static JTextArea textarea = new JTextArea();
//...
textarea = new JTextArea("He has achieved success.", d.width, d.height);
What's worse, is you add the original instance of the textarea to the frame BEFORE you create the new one, which runs the risk of not knowing which component you are actually dealing with...which is just compounded by the fact that you're using a static reference to it so other classes can access it, which they shouldn't be allowed to do...
In replaceFrame, you are taking text to search from the find field (button), but you should take it from findtext (you are always searching for text "Find").
This is one of the reasons why code duplication is bad - you should extract the finding logic to one place and reuse it in both classes.

How to go back to my login screen?

My program is written in Java using Eclipse and what my program does is first you have to login your username and password to the server and once that is verified, then you go to a new page (frame) where I have a JMenuBar, JMenu, and JMenuItem. The JMenuItem that I am working on is called "Logout" under the JMenu Exit, when you click on logout at the moment, it closes the screen. What I want to happen is to redirect me back to the login page. I've tried many functions, but none of them worked. I would appreciate the help.
Here is my program:
public class ScanTest2 extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private static LoginDialog loginDialog;
public ScanTest2() {
loginDialog = new LoginDialog(this, true);
loginDialog.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
// create new frame for new page
JFrame frame = new ScanTest2();
//create a Menu bar
JMenuBar menuBar = new JMenuBar();
frame.getContentPane().setBackground(Color.BLUE);
try {
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/home/a002384/logo2.bmp")))));
} catch (IOException e) {
e.printStackTrace();
}
frame.setTitle("Scan Gun Information");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
// create Menus
JMenu databaseMenu = new JMenu("Database");
JMenu ticketMenu = new JMenu("Tickets");
JMenu inquiriesMenu = new JMenu("Inquiries");
JMenu reportsMenu = new JMenu("Reports");
JMenu exitMenu = new JMenu("Exit");
// create Menu Items
JMenuItem lotMenuItem = new JMenuItem("Lots");
lotMenuItem.setMnemonic(KeyEvent.VK_L);
lotMenuItem.setActionCommand("Lots");
JMenuItem gunMenuItem = new JMenuItem("Guns");
gunMenuItem.setMnemonic(KeyEvent.VK_G);
gunMenuItem.setActionCommand("Guns");
JMenuItem batteryMenuItem = new JMenuItem("Batteries");
batteryMenuItem.setMnemonic(KeyEvent.VK_B);
batteryMenuItem.setActionCommand("Batteries");
JMenuItem logoutMenuItem = new JMenuItem("Logout");
logoutMenuItem.setMnemonic(KeyEvent.VK_L);
logoutMenuItem.setActionCommand("Logout");
MenuItemListener menuItemListener = new MenuItemListener();
lotMenuItem.addActionListener(menuItemListener);
gunMenuItem.addActionListener(menuItemListener);
batteryMenuItem.addActionListener(menuItemListener);
logoutMenuItem.addActionListener(menuItemListener);
// add Menu Items to Menus
databaseMenu.add(lotMenuItem);
databaseMenu.add(gunMenuItem);
databaseMenu.add(batteryMenuItem);
exitMenu.add(logoutMenuItem);
// add menu to MenuBar
menuBar.add(databaseMenu);
menuBar.add(ticketMenu);
menuBar.add(inquiriesMenu);
menuBar.add(reportsMenu);
menuBar.add(exitMenu);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
} // end of run method
class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Logout"))
System.exit(0);
// go back to login screen
}
}
}); // end of Runnable
}// end of Main
}
class LoginDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
private final JLabel loginlbl = new JLabel("Username");
private final JLabel Passwordlbl = new JLabel("Password");
private final JTextField loginName = new JTextField(15);
private final JPasswordField loginPassword = new JPasswordField();
private final JButton loginButton = new JButton("Login");
private final JButton cancelButton = new JButton("Cancel");
private final JLabel Status = new JLabel(" ");
private String username;
private String password;
private int m_errCounter = 0;
public static final int MAX_LOGIN_ATTEMPTS = 3;
public LoginDialog() {
this(null, true);
}
public LoginDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(loginlbl);
p3.add(Passwordlbl);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(loginName);
p4.add(loginPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(loginButton);
p2.add(cancelButton);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(Status, BorderLayout.NORTH);
Status.setForeground(Color.RED);
Status.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
loginPassword.enableInputMethods(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UniJava uJava = new UniJava();
try {
username = loginName.getText();
password = new String (loginPassword.getPassword());
if (username == " " && password == " ")
{
Status.setText("Invalid username or password!");
}
else
{
UniSession session = uJava.openSession();
session.setHostName("docdbtst.starcalif.com");
session.setUserName(username);
session.setPassword(password);
session.setAccountPath("/mnt/data1/DD");
session.connect();
parent.setVisible(true);
setVisible(false);
}
} catch (UniSessionException e1) {
if (++m_errCounter > MAX_LOGIN_ATTEMPTS)
{
JOptionPane.showMessageDialog(LoginDialog.this,
"All Login attempts failed!",
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
else
{
Status.setText("Invalid Login! Cannot Connect!");
loginName.setText("");
loginPassword.setText("");
}
e1.printStackTrace();
}
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
System.exit() everything will be cleaned up
JFrame.dispose() vs System.exit()
logoutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
f.dispose();
// northInformation.removeAll();
// init();
LoginWindow login = new LoginWindow();
}
});

Creating an ActionListener to search through TextArea of NotepadGUI using MVC

Here is the VIEW of my notepad application. I need to create a controller that searches through the textarea in the centerPanel. I have a JButton defined, as well as a textfield, and want the user to be able to type text into the field and press the button to highlight the searched text. I have all my ActionListeners defined in a new class.
public NotepadView() {
super();
//WINDOW
setSize (750,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Chad's Notepad");
setLocationRelativeTo(null);
setBackground(Color.BLACK);
//CENTER PANEL
centerPanel = new JPanel();
centerPanel.setLayout(new FlowLayout());
textArea = new JTextArea();
centerPanel.add(textArea);
add(centerPanel, BorderLayout.CENTER);
scrollPaneText = new JScrollPane(textArea);
add(scrollPaneText);
textArea.setLineWrap(true);
textArea.setFont(new Font("Garamond", Font.PLAIN, 18));
//BOTTOM PANEL
bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(1,2));
setButton = new JButton("Find");
textField = new JTextField("EnterText");
bottomPanel.add(setButton);
bottomPanel.add(textField);
add(bottomPanel, BorderLayout.SOUTH);
//MENU BAR
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
newItem = new JMenuItem("New");
openItem = new JMenuItem("Open");
saveItem = new JMenuItem("Save");
closeItem = new JMenuItem("Close");
menuBar.add(fileMenu);
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(closeItem);
setJMenuBar(menuBar);
newItem.addActionListener(new NewMenuCommand(textArea));
openItem.addActionListener(new OpenMenuCommand(textArea));
closeItem.addActionListener(new QuitMenuCommand());
saveItem.addActionListener(new SaveMenuCommand(textArea));
}
}
//ActionListener new class for Button
public class ButtonCommand implements ActionListener {
private JTextArea textArea;
private String hText;
int ind = 0;
private String findString;
public ButtonCommand (JTextArea ta){
textArea = ta;
}
public void actionPerformed (ActionEvent e){
hText = textArea.getText();
findString=JOptionPane.showInputDialog(null,"Find what","Find",JOptionPane.INFORMATION_MESSAGE);
ind = hText.indexOf(findString,0);
textArea.setCaretPosition(ind);
textArea.setSelectionStart(ind);
int a = ind+findString.length();
textArea.setSelectionEnd(a);
}
}

Categories