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;
}
}
Related
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.
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.
The button "closebutton" does not respond. I'm very new to java and I know the error has something to do with actionpreformed in the nested if. I've set up a test to see if words will print the the console when closebutton is pressed. They don't. Any help is appreciated
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class myGuiTester implements ActionListener
{
JPanel pane = new JPanel();
JPanel mainPanel = new JPanel();
JFrame MenuFrame = new JFrame("Main Menu");
JFrame Instructions = new JFrame("Instructions");
JFrame game = new JFrame("Game");
JPanel gamepan = new JPanel();
JFrame inst = new JFrame("Instructions");
JPanel instpan = new JPanel(new FlowLayout());
JButton playButton = new JButton("Play");
JButton instButton = new JButton("Instructions");
JButton exitButton = new JButton("Exit");
JButton closebutton = new JButton("Close");
public static void main(String[] args)
{
new myGuiTester ();
}
public myGuiTester ()
{
MenuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inst.setVisible(false);
game.setVisible(false);
JLabel title = new JLabel(" Slot Machine");
JLabel blank = new JLabel("");
JLabel blank1 = new JLabel("");
JLabel blank2 = new JLabel("");
JLabel blank3 = new JLabel("");
playButton.addActionListener(this);
instButton.addActionListener(this);
JLabel game1 = new JLabel("Test");
JLabel inst1 = new JLabel();
exitButton.addActionListener(this);
closebutton.addActionListener(this);
pane.setLayout(new GridLayout(9,1));
pane.add(blank);
pane.add(title);
pane.add(blank1);
pane.add(playButton);
pane.add(blank2);
pane.add(instButton);
pane.add(blank3);
pane.add(exitButton);
mainPanel.add(pane);
MenuFrame.setContentPane(mainPanel);
MenuFrame.setSize(500,400);
MenuFrame.setVisible(true);
//Game Panel
game.setContentPane(gamepan);
game.setSize(500,400);
game1.setText("Game goes here");
gamepan.add(game1);
//Instructions Panel
inst.setContentPane(instpan);
inst.setSize(500,300);
inst1.setText("Instructions go here.");
instpan.add(inst1);
instpan.add(closebutton);
}
//ActionListener
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals("Play"))
{
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setVisible(true);
MenuFrame.setVisible(false);
System.out.print("test play");
}
else if (e.getActionCommand().equals("Instructions"))
{
inst.setVisible(true);
//suspected error
if (e.getActionCommand().equals("Close"))
{
System.out.print("Test inst");
inst.setVisible(false);
}
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
}
You must handle "Close" in the elseif- statement but not inside "Instructions. I should be its own block like:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Play")) {
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setVisible(true);
MenuFrame.setVisible(false);
System.out.print("test play");
} else if (e.getActionCommand().equals("Instructions")) {
inst.setVisible(true);
// suspected error
}else if (e.getActionCommand().equals("Close")) {
System.out.print("Test inst");
inst.setVisible(false);
} else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
When you check which button is called you are comparing the ActionCommand of the Event with the label of the button, which are not the same thing :
e.getActionCommand().equals("Close")
What you should do is checking if the button IS the source of the event
e.getSource() == closeButton
I'm trying to update a JTable that pulls in data from an ArrayList. I have two frames in my program. The first frame is a JTable (AbstractTableModel) that displays the contents of the ArrayList. I click the "New" button on that frame to bring up the second window, which lets me add to the aforementioned ArrayList. When I click my "Save" button, the second window closes and the first is supposed to refresh with the new row. I don't have any syntactical errors in my code, and it looks conceptually right. I think the first place to start troubleshooting would be in the NoteCntl class. I'm under the impression that getNoteTableUI() should update the view with the new data when it's called, but I'm stumped as to what's going on. I'm new to the concept of Model View Controller, but I'd like to follow that as closely as possible.
Here is the Controller class:
public class NoteCntl {
private NoteTableModel theNoteTableModel = new NoteTableModel();;
private NoteTableUI theNoteTableUI;
private NoteDetailUI theNoteDetailUI;
public NoteCntl(){
theNoteTableUI = new NoteTableUI(this);
}
public NoteTableModel getNoteTableModel(){
return theNoteTableModel;
}
public void getNoteDetailUI(Note theNote){
if (theNoteDetailUI == null || theNote == null){
theNoteDetailUI = new NoteDetailUI(this,theNote);
}
else{
theNoteDetailUI.setVisible(true);
}
}
public NoteTableUI getNoteTableUI(){
theNoteTableModel.fireTableDataChanged(); //why doesn't this do anything?
theNoteTableUI.setVisible(true);
return theNoteTableUI;
}
public void deleteNote(int noteToDelete){
theNoteTableModel.removeRow(noteToDelete);
}
}
The First UI (Table):
public class NoteTableUI extends JFrame{
NoteTableModel noteModel;
NoteCntl theNoteCntl;
JPanel buttonPanel;
JPanel tablePanel;
JTable theNoteTable;
JScrollPane theScrollPane;
JButton backButton;
JButton deleteButton;
JButton editButton;
JButton newButton;
public NoteTableUI(NoteCntl theParentNoteCntl){
theNoteCntl = theParentNoteCntl;
this.initComponents();
this.setSize(400, 500);
this.setLocationRelativeTo(null);
this.setTitle("NoteTableUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
buttonPanel = new JPanel();
tablePanel = new JPanel();
backButton = new JButton("Back");
newButton = new JButton("New");
newButton.addActionListener(new newButtonListener());
editButton = new JButton("Edit");
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new deleteButtonListener());
noteModel = theNoteCntl.getNoteTableModel();
theNoteTable = new JTable(theNoteCntl.getNoteTableModel());
theScrollPane = new JScrollPane(theNoteTable);
theNoteTable.setFillsViewportHeight(true);
tablePanel.add(theScrollPane);
buttonPanel.add(backButton);
buttonPanel.add(deleteButton);
buttonPanel.add(editButton);
buttonPanel.add(newButton);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(tablePanel, BorderLayout.CENTER);
}
public class deleteButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int selectedRow = theNoteTable.getSelectedRow();
if (selectedRow == -1){
System.out.println("No row selected");
}
else{
noteModel.removeRow(selectedRow);
}
revalidate();
repaint();
}
}
public class newButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
NoteTableUI.this.setVisible(false);
NoteTableUI.this.theNoteCntl.getNoteDetailUI(null);
/*
NoteDetailCntl theNoteDetailCntl = new NoteDetailCntl();
lastRow++;
long newRow = lastRow;
noteModel.addRow(newRow, 0, "", "");
revalidate();
repaint();
*/
}
}
The 2nd UI (Detail editor)
public class NoteDetailUI extends JFrame{
private final int FRAME_WIDTH = 700;
private final int FRAME_HEIGHT = 500;
private final int FIELD_WIDTH = 10;
JButton saveButton;
JButton backButton;
JTextField idField;
JTextField dateField;
JTextField nameField;
JTextField descriptionField;
JTextArea noteDetail;
JLabel idLabel;
JLabel dateLabel;
JLabel nameLabel;
JLabel descriptionLabel;
JPanel buttonPanel;
JPanel textFieldPanel;
JPanel textAreaPanel;
JPanel mainPanel;
NoteTableModel theNoteTableModel;
NoteDetailCntl theNoteDetailCntl;
NoteCntl theNoteCntl;
Note theCurrentNote;
public NoteDetailUI(){
this.initComponents();
this.setSize(FRAME_WIDTH,FRAME_HEIGHT);
this.setLocationRelativeTo(null);
this.setTitle("NoteDetailUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public NoteDetailUI(NoteCntl parentNoteCntl, Note theSelectedNote){
theNoteCntl = parentNoteCntl;
theCurrentNote = theSelectedNote;
this.initComponents();
this.setSize(400,500);
this.setLocationRelativeTo(null);
this.setTitle("Note");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
saveButton = new JButton("Save");
saveButton.addActionListener(new saveButtonListener());
backButton = new JButton("Back");
backButton.addActionListener(new backButtonListener());
idField = new JTextField(FIELD_WIDTH);
theNoteTableModel = new NoteTableModel();
idField.setText("10");
idField.setEditable(false);
dateField = new JTextField(FIELD_WIDTH);
dateField.setText("20131108");
nameField = new JTextField(FIELD_WIDTH);
nameField.setText("Untitled");
descriptionField = new JTextField(FIELD_WIDTH);
descriptionField.setText("not described");
idLabel = new JLabel("ID");
dateLabel = new JLabel("Date");
nameLabel = new JLabel("Name");
descriptionLabel = new JLabel("Description");
noteDetail = new JTextArea(25,60);
buttonPanel = new JPanel();
textFieldPanel = new JPanel();
textAreaPanel = new JPanel();
mainPanel = new JPanel(new BorderLayout());
buttonPanel.add(backButton);
buttonPanel.add(saveButton);
textFieldPanel.add(idLabel);
textFieldPanel.add(idField);
textFieldPanel.add(dateLabel);
textFieldPanel.add(dateField);
textFieldPanel.add(nameLabel);
textFieldPanel.add(nameField);
textFieldPanel.add(descriptionLabel);
textFieldPanel.add(descriptionField);
textAreaPanel.add(noteDetail);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.add(textAreaPanel, BorderLayout.CENTER);
add(mainPanel);
}
public ArrayList<String> getNoteDetails(){
ArrayList<String> newData = new ArrayList<String>();
newData.add(idField.getText());
newData.add(dateField.getText());
newData.add(nameField.getText());
newData.add(descriptionField.getText());
return newData;
}
public class saveButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
/*
* Access the noteTableData array in NoteTableModel
* Add the newData fields in order
*/
if(theCurrentNote == null){
int newNoteNumber = Integer.parseInt(NoteDetailUI.this.idField.getText());
int newNoteDate = Integer.parseInt(NoteDetailUI.this.dateField.getText());
String newNoteName = NoteDetailUI.this.nameField.getText();
String newNoteDescription = NoteDetailUI.this.descriptionField.getText();
NoteDetailUI.this.theCurrentNote = new EssayNote(newNoteNumber,newNoteDate,newNoteName,newNoteDescription);
NoteDetailUI.this.setVisible(false);
NoteDetailUI.this.dispose();
NoteDetailUI.this.theNoteCntl.getNoteTableUI();
}
else{
//if it's a current Note
}
//Refresh the JTable
}
}
public class backButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
}
}
Thanks for all the help. I can provide the other classes if you want to just run the program and see what's happening, but I suspect it's either a problem with the fireTableDataChanged() call in the controller class or a problem with updating the contents of the ArrayList in the SaveButtonListener.
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);
}
}