How to make JButton reference object when pressed? - java

First off, this is my first post to Stack Overflow so please forgive me if I am not following some of the proper etiquitte. Im trying to make a GUI program that will display different food genres and then when the user presses the genre they want it will show a randomly generated restraunt of that genre. I am fairly new to programming and I am having a hard time figuing out how to make my buttons actually work. I have assigned the Restraunts objects each a value. Mexican will be values 1 and 2. Italian will be values 3 and 4. What Im wanting is when the user selects "Mexican" for the program to generate a random number (the restraunts value attribute) between 1 and 2 and then display that object with all its attributes in the same window. I've been stuck on this part for a bit and any help would be greatly appreciated. Thank you all in advance for your time. The code I have is as follows:
import TrySource.TryWindow;
import TrySource.Restraunts;
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class TrySomethingNew
{
public static void main (String[] args)
{
TryWindow frame = new TryWindow();
frame.setTitle("Try Something New");
frame.setSize(1000,900);
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
package TrySource;
import TrySource.TryWindow.ButtonClicked;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TryWindow extends JFrame
{
JButton jbtMexican = new JButton("Mexican");
JButton jbtItalian = new JButton("Italian");
public TryWindow()
{
super("Try Something New");
add(jbtMexican);
add(jbtItalian);
}//end TryWindow constructor
class ButtonClicked implements MouseListener
{
#Override
public void mouseClicked(MouseEvent e)
{
}
#Override
public void mousePressed(MouseEvent e)
{
}
#Override
public void mouseReleased(MouseEvent e)
{
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
}
}//end class
package TrySource;
public class Restraunts
{
String restrauntName;
String restrauntAddress;
String restrauntPhone;
public Restraunts(String name, String address, String phone, int value)
{
restrauntName = name;
restrauntAddress = address;
restrauntPhone = phone;
}//end constructor
Restraunts joseLocos = new Restraunts("Jose Locos", "853 N Glenstone Ave, Springfield, MO 65802",
"(417) 831-1300", 1);
Restraunts amigos = new Restraunts ("Amigos Mexican Restaurant","2118 S Campbell Ave, Springfield, MO 65807",
"(417) 887-1401", 2);
Restraunts zios = new Restraunts("Zios Italian Kitchen", "1249 E Kingsley St, Springfield, MO 65804",
"(417) 889-1919", 3);
Restraunts bambinos = new Restraunts("Bambinos Cafe", "1141 E Delmar St, Springfield, MO 65807",
"(417) 862-9999", 4);
}//end Restraunts

Add the Restraunts to a List
Group them together (by their type) using a Map
Use Collections.shuffle to randomise the List and select the first one
Take a look at
Collections Trail
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listeners
for more details
Oh, and you might like to gave a look at How to Use CardLayout

Related

how to display string as URI in java

I am a beginner in Java, I am trying to build a chatbot. The query and responses are hard coded in 2D string array chatbot[][].
This is the complete code that I have used, Two objects for JTextArea 'input and dialogue ' has been used. Object input has been attached to JPanel and is used to get the text from the user and then this is searched in the 2D string array.If it is found then the response is thrown from the same array.
Now my requirement is when the response is any URL it should be displayed as a link so that user can directly click and go to the site(http://google.com for the current scenario).Kindly suggest how this can be achieved or any modification in code is required. addText is the method that is defined to add entire conversation to dialogue text area which is non editable.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.lang.Math;
import java.awt.Color;
import java.awt.Toolkit;
public class test implements KeyListener{
JFrame j=new JFrame("Temenos ChatBot");
JPanel p=new JPanel();
JTextArea dialog=new JTextArea(20,50); //it will contain the whole conversation(non editable)
JTextArea input=new JTextArea(1,50); //where we user input our query(editable)
JScrollPane scroll=new JScrollPane(
dialog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
);
String[][] chatbot={
{"hi","hello","hola","ola","howdy"}, //check for query
{"hi","hello","hey"}, //provides output of the query
{"google","provide link for google","www.google.com"}, //Query
{"http://google.com"}, //response
//default
{"we can't find your query",
"(Sorry, we could not understand)"}
};
public static void main(String[]args){
new test();
}
private void icon(){
j.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("dy1MzZ-W.png")));//change the icon, paste the icon in default package
}
public test(){
j.setSize(600,400);
j.setResizable(false);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dialog.setEditable(false);
input.addKeyListener(this);
p.add(scroll);
p.add(input);
p.setBackground(new Color(0,150,255));
j.add(p);
j.setVisible(true);
icon();
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER){
input.setEditable(false);
//-----grab quote-----------
String quote=input.getText(); //takes whatever text user is inputting
input.setText("");
addText("->You:\t"+quote);
quote.trim();
while(
quote.charAt(quote.length()-1)=='!' ||
quote.charAt(quote.length()-1)=='.' ||
quote.charAt(quote.length()-1)=='?'
){
quote=quote.substring(0,quote.length()-1);
}
quote.trim();
byte response=0; //byte is data type that will check for response
/*
0:we're searching through chatBot[][] for matches
1:we didn't find anything
2:we did find something
*/
//-----check for matches----
int j=0;//which group we're checking
while(response==0){
if(inArray(quote.toLowerCase(),chatbot[j*2])){
response=2;
int r=(int)Math.floor(Math.random()*chatbot[(j*2)+1].length);
addText("\n->A.I.sha:\t"+chatbot[(j*2)+1][r]);
}
j++;
if(j*2==chatbot.length-1 && response==0){
response=1;
} //if it has come to end then set response to 1
}
//-----default--------------
if(response==1){
int r=(int)Math.floor(Math.random()*chatbot[chatbot.length-1].length);
addText("\n->A.I.sha:\t"+chatbot[chatbot.length-1][r]);
}
addText("\n");
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER){
input.setEditable(true);
}
}
public void keyTyped(KeyEvent e){}
public void addText(String str){
dialog.setText(dialog.getText()+str);
}//it will add whatever text dialogue box is having
public boolean inArray(String in,String[] str){
boolean match=false;
for(int i=0;i<str.length;i++){
if(str[i].equals(in)){
match=true;
} //Searches for string 'in' in string array,if it finds return true
}
return match;
}
}
If you're making a GUI in swing, you could follow another stack overflow answer, such as this one
How to add hyperlink in JLabel
Or, you could just have java open the browser to that webpage:
// Create Desktop object
Desktop d=Desktop.getDesktop();
// Browse a URL, say google.com
d.browse(new URI("http://google.com"));
You can use the parse static method from Uri
Uri myUri = Uri.parse("http://google.com")

Portrayals not Showing

EDIT: Everything displays correctly when either field or hunterField hold no objects in any location. field and hunterField both exclusively hold objects which extend the same class, so I guess it may have something to do with inheritance...?
I have created a simple Agent-Based Model using MASON. The back-end works find, but when I try displaying my agents only "wall" agents are displayed. (Wall Portrayal) My code is below... Any idea?
package sim.app.celai;
import java.awt.Color;
import javax.swing.JFrame;
import sim.app.tutorial3.Tutorial3WithUI;
import sim.display.Controller;
import sim.display.Display2D;
import sim.display.GUIState;
import sim.portrayal.grid.SparseGridPortrayal2D;
import sim.util.Bag;
public class FieldWithGUI extends GUIState {
public Display2D display;
public JFrame frame;
SparseGridPortrayal2D hunterPortrayal = new SparseGridPortrayal2D();
SparseGridPortrayal2D wallPortrayal = new SparseGridPortrayal2D();
SparseGridPortrayal2D childPortrayal = new SparseGridPortrayal2D();
public FieldWithGUI() {
super(new Field(System.currentTimeMillis()));
}
public void setupPortrayals() {
childPortrayal.setField(((Field) state).field);
hunterPortrayal.setField(((Field) state).hunterField);
wallPortrayal.setField(((Field) state).wallField);
childPortrayal.setPortrayalForAll(new sim.portrayal.simple.OvalPortrayal2D(Color.blue));
hunterPortrayal.setPortrayalForAll(new sim.portrayal.simple.OvalPortrayal2D(Color.red));
wallPortrayal.setPortrayalForAll(new sim.portrayal.simple.OvalPortrayal2D(Color.green));
display.reset();
display.repaint();
}
public void quit()
{
super.quit();
if (frame!=null) frame.dispose();
frame = null; // let gc
display = null; // let gc
}
public static void main(String[] args)
{
new FieldWithGUI().createController();
}
public void start()
{
super.start();
// set up our portrayals
setupPortrayals();
}
public void init(Controller c)
{
super.init(c);
// Make the Display2D. We'll have it display stuff later.
display = new Display2D(400,400,this); // at 400x400, we've got 4x4 per array position
frame = display.createFrame();
c.registerFrame(frame); // register the frame so it appears in the "Display" list
frame.setVisible(true);
// specify the backdrop color -- what gets painted behind the displays
display.setBackdrop(Color.black);
// attach the portrayals
display.attach(childPortrayal, "children");
display.attach(hunterPortrayal, "hunter");
display.attach(wallPortrayal, "wall");
}
}

Java basic GUI program errors

In my online Java class, I need to write a program that counts the number of mouse clicks on a button within a frame. Here is my code:
import java.awt.*;
import java.awt.event.*;
public class option1 extends Frame {
option1() {
setTitle("Final Project Option 1");
setSize(300,300);
show();
}
public static void main(String[] args) {
option1 test = new option1();
int a = 0;
String s1 = "" + a;
Frame objFrame;
Button objButton1;
Label objLabel1;
objFrame = new option1();
objButton1 = new Button("Button");
objLabel1 = new Label();
objLabel1.setBounds(150,220,50,30);
objButton1.setBounds(40,35,50,50);
objLabel1.setText(s1);
objButton1.addMouseListener(new MyMouseListener()); //line 29
objFrame.add(objLabel1);
objFrame.add(objButton1);
}
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
a++; //line 36
}
}
}
When compiling, I get two errors. One error is on line 29, which is "non-static variable this cannot be referenced from a static context", and the other is on line 36, which is "cannot find symbol".
So, what exactly am I doing wrong? I would appreciate responders telling exactly what I need to do to fix the problem, and avoiding using technical terms since I'm rather new to programming.
I see two issues, namely your inner class should be static (to use it without an instance of option1 which should probably be Option1 to fit with Java naming conventions) and you need to define and initialize a. Something like
public static class MyMouseListener extends MouseAdapter {
int a = 0; //<-- add this.
public void mouseClicked(MouseEvent me) {
a++;
}
}
Also, I suggest you consider using the more modern JFrame instead of the older Frame.
Edit
You'll need to save a reference to your MouseListener like
MyMouseListener mml = new MyMouseListener();
objButton1.addMouseListener(mml);
Then you can get it the a like
System.out.println(mml.a);
Finally, your original approach of "" + a would be "0".
Generally, as soon as you possibly can, get out of the main method into a non-static context...
public class option1 extends Frame {
private int a = 0;
private Label objLabel1;
option1() {
setTitle("Final Project Option 1");
setSize(300,300);
Button objButton1;
objButton1 = new Button("Button");
objLabel1 = new Label();
objLabel1.setBounds(150,220,50,30);
objButton1.setBounds(40,35,50,50);
objLabel1.setText(Integer.toString(a));
objButton1.addMouseListener(new MyMouseListener()); //line 29
add(objLabel1);
add(objButton1);
show();
}
public static void main(String[] args) {
option1 test = new option1();
}
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
a++; //line 36
objLabel1.setText(Integer.toString(a));
}
}
}
Generally speaking, AWT is out-of-date (by some 15 years) and you really should be trying to use Swing or JavaFX instead.
Buttons should use ActionListener, as a mouse is not the only way a button might be triggered
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
I just tried to make your code working. But there is some issues regarding the standard Java coding. But you should consider previous answers concerning the coding style.
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class Main {
public static void main(String[] args) {
final Frame mainFrame = new OptionOne();
Button button = new Button("Button");
final Label label = new Label();
label.setBounds(150, 220, 50, 30);
label.setText("0");
button.setBounds(40, 35, 50, 50);
label.addPropertyChangeListener(label.getText(), new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
mainFrame.addNotify();
}
});
button.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
int value = Integer.parseInt(label.getText());
label.setText(String.valueOf(value + 1));
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
mainFrame.add(label);
mainFrame.add(button);
}
}
class OptionOne extends Frame {
OptionOne() {
setTitle("Final Project Option 1");
setSize(300, 300);
show();
}
}

Drag objects from JList, with ghost image effect

I have added to one of the JLists in my java program a Drag and Drop transfer handler.
I added a method to this JList so as to have a nice ghost image effect of the selected values I am dragging. This effect works just fine until I add the transfer handler :
In that case, this method :
myList.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent evt) {
System.out.println("Dragging");
}
});
from :
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.io.IOException;
import java.util.ArrayList;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataHandler;
import javax.swing.*;
class ListExample extends JFrame
{
private JPanel topPanel;
private JList myList;
public ListExample()
{
setSize(300, 100 );
topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
String listData[] =
{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
};
myList = new JList(listData);
myList.setDragEnabled(true);
ListItemTransferHandler handler = new ListItemTransferHandler();
myList.setTransferHandler(handler);
topPanel.add( myList, BorderLayout.CENTER );
myList.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent evt) {
System.out.println("Dragging");
}
});
}
public static void main( String args[] )
{
ListExample mainFrame = new ListExample();
mainFrame.setVisible(true );
}
class ListItemTransferHandler extends TransferHandler {
private final DataFlavor localObjectFlavor;
private Object[] transferedObjects = null;
public ListItemTransferHandler() {
localObjectFlavor = new ActivationDataFlavor(Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items");
}
private JList source = null;
#SuppressWarnings("deprecation")
#Override protected Transferable createTransferable(JComponent c) {
source = (JList) c;
transferedObjects = source.getSelectedValues();
return new DataHandler(transferedObjects, localObjectFlavor.getMimeType());
}
#Override public boolean canImport(TransferSupport info) {
return true;
}
#Override public int getSourceActions(JComponent c) {
return MOVE; //TransferHandler.COPY_OR_MOVE;
}
}
}
gets called once or twice as I begin to drag, but as soon as I get a few pixels away, the source selection changes colour and my dragmouse listener is no longer called, and the ghost image stays nearby the source of the dragged object.
However, I can still drag my selected cells and drop them where I want. It's just that the ghost image doesn't follow all the way.
I am obviously missing something important here but since it is a rather specific problem I couldn't find help anywhere, so suggestions would be appreciated.
DragGestureListener taks precedence on MouseMotionListener when a Drag-n-Drop process is started. This you've got to implement such a DragGestureListener.
See here for a good working example.
Java drag and drop custom cursor

How can I convert a swing JTextField component in to an object of a type that extends it

I have an application using a third party package that has a factory that returns to me JTextField objects that are then added to a GUI. This makes up about 10% of the JTextFields used.
I can't change the third party package but have a requirement to add right click (cut, copy and paste) options in to all ofthe fields.
Now I have a RightClickTextField that extends JTextField and has all the functionality built in to it, this serves to solve my issue for 90% of the application.
However for the 10% that's using the third party package to get JTextFields I cannot think of a solution that will allow me to declare the fields as RightClickTextFields yet use the factory I have to get back the Boxes. I know I cannot cast the result as the objects returned are not of a type that high up in the hierarchy, and a copy constructor won't work since I cannot copy every property being set by the factory, but I don't know of a way to upcast the JTextField in to my type. Is there one?
Rather than subclassing or trying to cast it, can you put your right-click functionality into its own class which implements the MouseInputListener interface, and simply add an instance of your right-click handler to the JTextField objects in question?
Maybe use the Decorator Pattern. This way you can stop using RightClickTextField at all - start using RightClickTextFieldDecorator and supply it either with your own JTextFields or the ones you get from 3rd party thingy.
Thanks for all the comments. I think the actual answer to my question is:
You can't.
Whilst all of the suggestions are valid, I knew it was possible to do all those things, I just wanted to know if I could do it my way first.
My solution (based on feedback here and my own preference) was to create this class below, and manage and expose a single instance of it from a singleton.
I'd appreciate thoughts on this solution?
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.text.JTextComponent;
public class CopyPasteTextComponentPopoupMenu extends JPopupMenu implements
ActionListener {
private JTextComponent lastInvoker;
private JMenuItem cutMenuItem;
private JMenuItem copyMenuItem;
private JMenuItem pasteMenuItem;
private Map<JTextComponent, JTCProperties> managedComponents;
private MouseListener heyListen;
public CopyPasteTextComponentPopoupMenu() {
super();
init();
}
public CopyPasteTextComponentPopoupMenu(String label) {
super(label);
init();
}
#Override
public void show(Component invoker, int x, int y) {
JTCProperties props = managedComponents.get(invoker);
if(props!=null) {
this.lastInvoker = (JTextComponent) invoker;
setEnabled(props);
super.show(invoker, x, y);
} else {
this.lastInvoker = null;
}
}
public void manageTextComponent(JTextComponent jtc, boolean canCut,
boolean canCopy, boolean canPaste) {
jtc.addMouseListener(heyListen);
JTCProperties props = new JTCProperties(canCut,canCopy,canPaste);
managedComponents.put(jtc,props);
}
public void dispose() {
for (JTextComponent component : managedComponents.keySet()) {
component.removeMouseListener(heyListen);
managedComponents.remove(component);
}
}
#Override
public void actionPerformed(ActionEvent e) {
if (lastInvoker != null) {
if (e.getSource() == cutMenuItem) {
lastInvoker.cut();
} else if (e.getSource() == copyMenuItem) {
lastInvoker.copy();
} else if (e.getSource() == pasteMenuItem) {
lastInvoker.paste();
}
}
}
private void setEnabled(JTCProperties props) {
cutMenuItem.setEnabled(props.canCut);
copyMenuItem.setEnabled(props.canCopy);
pasteMenuItem.setEnabled(props.canPaste);
}
private void init() {
this.managedComponents = new HashMap<JTextComponent, JTCProperties>();
this.setPreferredSize(new Dimension(100, 70));
cutMenuItem = new JMenuItem("Cut");
copyMenuItem = new JMenuItem("Copy");
pasteMenuItem = new JMenuItem("Paste");
cutMenuItem.addActionListener(this);
copyMenuItem.addActionListener(this);
pasteMenuItem.addActionListener(this);
this.add(cutMenuItem);
this.add(copyMenuItem);
this.add(pasteMenuItem);
heyListen = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
show(e.getComponent(), e.getX(), e.getY());
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
show(e.getComponent(), e.getX(), e.getY());
}
}
};
}
private class JTCProperties {
public boolean canCut, canCopy, canPaste;
public JTCProperties(boolean canCut, boolean canCopy, boolean canPaste) {
this.canCut = canCut;
this.canCopy = canCopy;
this.canPaste = canPaste;
}
}
}

Categories

Resources