I have a JComboBox with 12 different selections, and depending on what is selected I want the question (JLabel) to change matching the selection. I've tried an if statement to see what is selected and if it matches what should be selected, then the question changes accordingly, but the JLabel never really changes under an circumstance.
Code
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Window extends JFrame{
private static final long serialVersionUID = 1L;
public Window(){
super("Area Finder v1.0");
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getClassLoader().getResource("images/areafinder.png"));
} catch (IOException e) {
e.printStackTrace();
}
super.setIconImage(image);
setSize(400, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel Instr = new JLabel("What would kind of area would you like to find?");
String[] areaChoices = {"Circle", "Square", "Rectangle", "Triangle", "Trapezoid", "Parallelogram", "Hexagon", "Rhombus", "Pentagon", "Polygon", "Ellipse", "Sector"};
final JComboBox<?> choiceBox = new JComboBox(areaChoices);
final Object isSelected = choiceBox.getSelectedItem();
choiceBox.setToolTipText("Select which one you want to find the area of!");
choiceBox.setSelectedIndex(0);
final JLabel q = new JLabel("");
final JTextField inputFromUser = new JTextField("");
JButton findArea = new JButton("Find Area");
/* Question Changer*/
/*End of Question Changer*/
findArea.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
if(isSelected == "Circle"){
double radius = Double.parseDouble(inputFromUser.getText());
double area = 3.14 * (radius * radius);
JOptionPane.showMessageDialog(null, "Your Area is " + area);
}else if(isSelected == "Square"){
}
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15,15,15,15);
panel.add(Instr);
panel.add(choiceBox);
panel.add(findArea);
panel.add(q);
panel.add(inputFromUser);
add(panel);
}
}
EDIT: So I did a few tests with System.out.println(); and I figured out it's calling all the items at once, but the one that's selected is being called first.
Example:
choiceBox.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getItem() == "Circle"){
System.out.println("Circle selected");
}else if(e.getItem() == "Square"){
System.out.println("Square selected");
}
}
});
Prints out "Circle Selected Square Selected" if you select circle, but "Square Selected Circle Selected" if you select Square.
Add an ItemListener to the JComboBox to react when the selection changes.
Also, when you do this:
Object isSelected = choiceBox.getSelectedItem();
... you are just getting the selected value at that time; you aren't magically binding the isSelected variable to update whenever the combobox updates. You need to call getSelectedItem() again if you want the new value.
try adding an action listener to the JComboBox
choiceBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//put the code here
}
});
Change the text of the JLabel
label.setText("Changed text");
Tell the container to relayout.
frame.invalidate();
frame.repaint();
This makes sure that the frame is redrawn to show the changed label. To know when the combo box has changed it's selection, add an ActionListener like this.
combo.addActionListener (new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
label.setText(combo.getText());
frame.invalidate();
}
});
Related
Im using blue j for a project which is a java framework (not through my choice)
I cant get it to print out what seat they have chosen because it always selects the 1st value A1.
Its a seating plan that displays and image and a combo box in which you can select your seat for exmaple A1 and upon the button click save it prints out the seat you have chosen in a dialog box.
Help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SeatingChart extends JFrame
{
private JLabel infoLabel;
// Get the list of field names, used for ordering.
String[] ordering =
{"A1","A2","A3","A4",
"B1","B2","B3","B4",
"C1","C2","C3","C4","D1","D2","D3","D4"};
String chosenSeat;
String ticket= "1" ;
int ticketValue = Integer.parseInt(ticket);
/**
* Main method for starting the system from a command line.
*/
public static void main(String[] args)
{
SeatingChart gui = new SeatingChart();
}
/**
* Create a visual aspect and display its GUI on screen.
*/
public SeatingChart()
{
super("Choose Your seats");
makeFrame();
}
/**
* Quit function: quit the application.
*/
private void quit()
{
System.exit(0);
}
private void play()
{
JFrame frames = new JFrame("Sample frame");
frames.setSize(400, 400);
frames.setVisible(false);
frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(frames, "You have chosen the seat " +chosenSeat);
}
/**
* Create the complete application GUI.
*/
public void makeFrame ()
{
// the following makes sure that our application exits when
// the user closes its window
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) getContentPane();
contentPane.setBorder(new EmptyBorder(6, 10, 10, 10));
makeMenuBar(); //calls the menu bar method
// Create the center with image
JPanel centerPane = new JPanel();
{
centerPane.setLayout(new BorderLayout(8, 8));
JLabel image = new JLabel(new ImageIcon("SeatingChart.jpg"));
image.setSize (20,20);//dont work
centerPane.add(image, BorderLayout.NORTH);
centerPane.setBackground(Color.WHITE);
infoLabel = new JLabel("Please use the chart to select where you would like to sit and save it. Do this for how many tickets you have");
infoLabel.setHorizontalAlignment(SwingConstants.CENTER);
centerPane.add(infoLabel, BorderLayout.CENTER);
}
contentPane.add(centerPane, BorderLayout.EAST);
JPanel leftPane = new JPanel();
{
leftPane.setLayout(new BorderLayout(8, 8));
// Set up components for ordering the list
JPanel orderingPanel = new JPanel();
orderingPanel.setLayout(new BorderLayout());
orderingPanel.add(new JLabel("Choose your seat:"), BorderLayout.NORTH);
// Create the combo box.
JComboBox formatList = new JComboBox(ordering);
orderingPanel.add(formatList, BorderLayout.CENTER);
leftPane.add(orderingPanel, BorderLayout.NORTH);
formatList.setSelectedIndex(0);
chosenSeat = formatList.getSelectedItem().toString();
//formatList.removeItemAt(formatList.getSelectedIndex());
}
contentPane.add(leftPane, BorderLayout.CENTER);
JPanel toolbar = new JPanel();
{
toolbar.setLayout(new GridLayout(1, 0));
JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
play();
}
});
toolbar.add(button);
button = new JButton("Next");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// This button would allow the use to go to the next step
}
});
toolbar.add(button);
}
contentPane.add(toolbar, BorderLayout.SOUTH);
// building is done - arrange the components
pack();
// place this frame at the center of the screen and show
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(d.width/2 - getWidth()/2, d.height/2 - getHeight()/2);
setVisible(true);
}
/**
* Create the main frame's menu bar.
*/
private void makeMenuBar()
{
final int SHORTCUT_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu menu;
JMenuItem item;
// create the File menu
menu = new JMenu("File");
menubar.add(menu);
item = new JMenuItem("Quit");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
quit();
}
});
menu.add(item);
}
}
You set the chosenSeat field immediately after creating the formatList combo box. At that moment, the user has not even had a chance to pick a seat and seat A1 is selected by default. If you set chosenSeat in the play method, it should reflect the seat picked by your user.
I think the new JFrame in the play method - as already mentioned by mKorbel - is not needed, since you can use the application frame (this) as the parent component for the call to the JOptionPane.showMessageDialog method:
private void play() {
// todo: frames is not needed.
//JFrame frames = new JFrame("Sample frame");
//frames.setSize(400, 400);
//frames.setVisible(false);
//frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chosenSeat = formatList.getSelectedItem().toString();
// todo: use the application frame as the parent.
//JOptionPane.showMessageDialog(frames, "You have chosen the seat " + chosenSeat);
JOptionPane.showMessageDialog(this, "You have chosen the seat " + chosenSeat);
}
I'm trying to use the JButton count to count the number of characters entered into the JTextField t. I'm new to Java and GUIs but here's my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 extends Frame implements ActionListener{
TextField t;
Button count;
int a;
Choice choice;
public GUI1(){
this.t = new TextField("", 30);
this.count = new Button("count");
this.count.addActionListener(this);
JTextField x = new JTextField();
x.setEditable(false);
this.setTitle("Character count");
this.setLayout(new FlowLayout());
this.add(x);
this.add(t);
this.add(count);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()== this.count)
t.setText(choice.getSelectedItem()+ " " +a);
}
I'm also trying to enter the value in another uneditable JTextField x. Any help is appreciated.
Add this to your code
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
a = t.getText().length();
}
});
OR
You can use lambda expression like this
count.addActionListener(e -> a = t.getText().length());
For More
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
You need to add a listener
TextField t = new TextField();
Button b = new Button("Count");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
}
});
You can read more about here
http://www.tutorialspoint.com/awt/awt_button.htm
First of all, I recommend you not to use AWT elements, since it brings tons of problems and it has little to no support, instead you can try using Swing components which are a replacement/fix for AWT. You can read more about here. You might also want to read AWT vs Swing (Pros and Cons).
Now going into your problem:
You should avoid extending from JFrame, I might recommend you to create a new JFrame object instead. Here's the reason to why. That being said, you can also remove all your this.t and other calls with this.
I'm glad you're using a Layout Manager!
And now to count the number of characters on your JTextField and set text to your other JTextField you should use this code:
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
Also I fixed your code, I changed AWT elements to Swing ones and added number of cols to your second JTextField so it would appear.
So, here's a running example that I made from your code (And removed Choice choice line since you didn't posted that code):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 {
JTextField t;
JButton count;
int a;
JFrame frame;
public GUI1(){
frame = new JFrame();
t = new JTextField("", 15);
count = new JButton("count");
JTextField x = new JTextField("", 15);
x.setEditable(false);
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
frame.setTitle("Character count");
frame.setLayout(new FlowLayout());
frame.add(x);
frame.add(t);
frame.add(count);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main (String args[]) {
new GUI1();
}
}
When you click on a button you should
String str = t.getText(); // get string from jtextfield
To save the text from the texfield. Then you can use something like:
a = str..length(); // get length of string
x.setText(str + " " + a); //set it to the field
To set it to the JTextField.
How would one bind the "Enter" key on a keyboard to press a JButton? Currently trying to figure this out but have no idea on what to do.
Here is my code for reference. What it's supposed to do is create a guessing game (which it does) but I want to add the ability to press enter to click the "Enter" button (jButtonEnter in this case).
package day21;
import java.awt.*;
import java.awt.event.*;
//import java.applet.*;
import javax.swing.*;
//import javax.swing.border.*;
public class Day21 extends JApplet implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
//All important Variables
JTextArea outTextArea = new JTextArea(10,20);
JScrollPane scroller = new JScrollPane(outTextArea);
static int GuessMe = (int) Math.ceil(Math.random()*1000);//randomizes the number
JPanel jPanelTop = new JPanel();
JPanel jPanelMid = new JPanel();
JPanel jPanelLow = new JPanel();
JLabel jLabelTop = new JLabel("Guess a number between 1 and 1000");
static JTextField jTextFieldInput = new JTextField("Guess Here",25);
JButton jButtonEnter = new JButton("Enter");
JButton jButtonReset = new JButton("Reset");
JButton jButtonClose = new JButton("Close");
public void init(){
this.getContentPane().setBackground(Color.white);
this.setSize(new Dimension(400, 120));
//Top Panel
jPanelTop.setBackground(Color.cyan);
jPanelTop.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelTop.setPreferredSize(new Dimension(14, 40));
jPanelTop.setToolTipText("Top Panel");
this.getContentPane().add(jPanelTop, BorderLayout.NORTH);
jPanelTop.add(jLabelTop);
//Middle Panel
jPanelMid.setBackground(Color.orange);
jPanelMid.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelMid.setPreferredSize(new Dimension(14, 40));
jPanelMid.setToolTipText("Center Panel");
this.getContentPane().add(jPanelMid, BorderLayout.CENTER);
jPanelMid.add(jTextFieldInput);
jPanelMid.add(jButtonEnter);
jButtonEnter.addActionListener(this);
//Lower Panel
jPanelLow.setBackground(Color.black);
jPanelLow.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelLow.setPreferredSize(new Dimension(14, 40));
jPanelLow.setToolTipText("Lower Panel");
this.getContentPane().add(jPanelLow, BorderLayout.SOUTH);
jPanelLow.add(jButtonReset);
jPanelLow.add(jButtonClose);
jButtonClose.addActionListener(this);
jButtonReset.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
double input = 0;
boolean Error = false;
String ErrorMSG = "Error: Please Enter a Number";
try{
input = Double.parseDouble(jTextFieldInput.getText().trim());;
}
catch(NumberFormatException n){
Error = true;
}
if(Error){
JOptionPane.showMessageDialog(rootPane, ErrorMSG); //If variable entered is not a number
}
String correctAnswer = "Hooray! You guessed Correctly! \n Press Reset to play again";
String tooHigh = input + " is too high";
String tooLow = input + " is too low";
if(!Error){
if(e.getSource() == jButtonEnter){
if (input == GuessMe){
jPanelLow.setBackground(Color.green);
JOptionPane.showMessageDialog(rootPane, correctAnswer);
}
if (input > GuessMe){
jPanelLow.setBackground(Color.red);
JOptionPane.showMessageDialog(rootPane, tooHigh);
}
if (input < GuessMe){
jPanelLow.setBackground(Color.red);
JOptionPane.showMessageDialog(rootPane, tooLow);
}
}
}
if(e.getSource() == jButtonReset){
Day21.reset(); //runs the reset() method which resets the window back to it's normal state
}
if(e.getSource() == jButtonClose){
System.exit(1); //exits the program
}
}
public static void reset(){
GuessMe = (int) Math.ceil(Math.random()*1000);//randomizes the number
jTextFieldInput.setText("Guess Here");
}
}
Check out Enter Key and Button for a discussion on this topic and a couple of solutions depending on your exact requirement:
use the root pane to set a default button
use the UIManager to have focus follow the button
use Key Bindings to invoke the default Action
Define a method - processEnterButton() and put all the necessary logic there. Call the method from actionPerformed() if the button was clicked. Also define key binding for the ENTER key and call the processEnterButton() from the binding as well.
I'm doing a small program with Java GUI
here is mu code:
// DebugFourteen3
// User selects pizza topping and sees price
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//use correct spelling of class name
public class DebugFourteen3 extends JFrame
{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public DebugFourteen3()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
itemStateChanged(this);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent[] list)
{
Object source = list.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
the compiler gets me error on line 35, it says itemStateChanged() should receive a argument which type is ItemEvent[] but I'm passing "this"(the class it self)
can anyone explain how the itemStateChanged works with the JComboBox?
thanks
You have to add the listener on the combo box instead of calling the itemStateChanged method directly. Adding the listener will enable the callbacks when the click event happens, and jvm will call the itemStateChanged method automatically as combo box is registered for the event. Replace this line
itemStateChanged(this);
with
pizzaBox.addItemListener(this);
At first, you need to implements ItemListener with JFrame. Than add following line with pizzaBox, this will notify overrided public void itemStateChanged(ItemEvent ev) method ItemListener.
pizzaBox.addItemListener(this);
For details, see this tutorial.
Problem :
1.you are not registering itemListener for JComboBox
2.itemStateChanged event takes ItemEvent as argument not ItemEvent[] array
1.Replace this :
itemStateChanged(this);
with this:
pizzaBox.addItemListener(this);
2.Replace This:
public void itemStateChanged(ItemEvent[] list)
With this:
public void itemStateChanged(ItemEvent list)
Complete Code:
// DebugFourteen3
// User selects pizza topping and sees price
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//use correct spelling of class name
public class DebugFourteen3 extends JFrame
{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public DebugFourteen3()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
pizzaBox.addItemListener(this);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent list)
{
Object source = list.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
Here this i.e DebugFourteen3 is not a type ItemEvent. Thats why
itemStateChanged(ItemEvent[] list)
gives error.
If you want to handle itemStateChanged then you need to implement ItemLisntener and add actionListner to it as
pizzaBox.addItemListener(this);
also add Handler method of ItemLisntener as
public void itemStateChanged(....)
{
//Handling Code goes here
}
Or you can implement ActionListner also
For more information on how to use combobox you can visit here
I have in my app a chat component which has a JTextArea on it.
Now, how can I add an ActionListener-like event for a specific text (like student://xxxx)?
So when I click on that text (student://xxxx) something will happen.
Thank you.
Here try this small program, try to click at the start of student://, that will pop up a message Dialog
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAreaExample extends JFrame
{
private JTextArea tarea = new JTextArea(10, 10);
private JTextField tfield = new JTextField(10);
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tarea.setText("Hello there\n");
tarea.append("Hello student://");
JScrollPane scroll = new JScrollPane(tarea);
tfield.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tarea.append(tfield.getText() + "\n");
}
});
tarea.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
int x = me.getX();
int y = me.getY();
System.out.println("X : " + x);
System.out.println("Y : " + y);
int startOffset = tarea.viewToModel(new Point(x, y));
System.out.println("Start Offset : " + startOffset);
String text = tarea.getText();
int searchLocation = text.indexOf("student://", startOffset);
System.out.println("Search Location : " + searchLocation);
if (searchLocation == startOffset)
JOptionPane.showMessageDialog(TextAreaExample.this, "BINGO you found me.");
}
});
getContentPane().add(scroll, BorderLayout.CENTER);
getContentPane().add(tfield, BorderLayout.PAGE_END);
pack();
setLocationByPlatform(true);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextAreaExample().createAndDisplayGUI();
}
});
}
}
No, don't even consider this since ActionListeners are for JButtons or anything else derived from AbstractButton but not for JTextComponents (except for JTextFields). Perhaps you want a MouseListener.
Having said this, perhaps you'll be better off with two text components, a JTextArea to display all responses, including the user's, and right below this in a BorderLayout.SOUTH type of position, a JTextField to allow the user to enter text into the chat. Then give that JTextField an ActionListener (this is legal) so that "enter" will actuate the listener.
Edit 1
You state:
Well I have that jtextfield , the text in it is being sent to the server and server sends the message to all clients which appears in the JTextArea. But my problem is here: I want to popup a window when someone clicks on a student://id text .
Yeah, looking at your comments, my vote is for you to display the chats not in a JTextArea but rather in a JList, one with a SelectionListener. You can then respond easily to mouse click events, and will more easily get useful information from the "line" clicked on (if you fill the JList with smart objects). You will need to write a custom cell renderer that allows multiple lines of text to be displayed, probably one that shows a JTextArea, but the tutorial on JLists will get you started on this.
Is hitting ENTER instead of mouse-click ok?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StudentID extends JFrame implements ActionListener
{
private static final String progname = "StudentID 0.1";
private JTextField student;
private JTextArea feedback;
private JButton exit;
public StudentID ()
{
super (progname);
JPanel mainpanel = new JPanel ();
mainpanel.setLayout (new BorderLayout ());
this.getContentPane ().add (mainpanel);
student = new JTextField ("student://");
exit = new JButton ("exit");
student.addActionListener (this);
exit.addActionListener (this);
feedback = new JTextArea ();
mainpanel.add (student, BorderLayout.NORTH);
mainpanel.add (feedback, BorderLayout.CENTER);
mainpanel.add (exit, BorderLayout.SOUTH);
setSize (400, 400);
setLocation (100, 100);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
}
public void actionPerformed (final ActionEvent e)
{
SwingWorker worker = new SwingWorker ()
{
protected String doInBackground () throws InterruptedException
{
String cmd = e.getActionCommand ();
if (cmd.equals ("exit"))
{
System.exit (0);
}
else if (cmd.matches ("student://[0-9]+"))
{
feedback.setText ("student found: " + cmd.replaceAll ("student://([0-9]+)", "$1"));
}
else
{
feedback.setText ("cmd: " + cmd);
}
return "done";
}
protected void done ()
{
feedback.setText (feedback.getText () + "\ndone");
}
};
worker.execute ();
}
public static void main (final String args[])
{
Runnable runner = new Runnable ()
{
public void run ()
{
new StudentID ();
}
};
EventQueue.invokeLater (runner);
}
}