My JTextArea has text appended to it then it is updated with
jTexaArea.update(jTextArea.getGraphics());
But while appending I cannot select or edit text nor scroll.
NetBeans system output allows for these features, how do I include them in my program?
While appending text if it is triggered by a JButton click event, the UI becomes unresponsive till the event is finished. This is because the event dispatch thread waits for the event to get finished before proceeding with next event.
If your requirement is to work on Text Area when an event is getting processed you can choose following approaches:
Using SwingWorker
Implementing Lazy appending of text in JTextArea
Following is a sample lazy appending example:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import java.awt.Font;
import javax.swing.JScrollPane;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.List;
import javax.swing.Timer;
import javax.swing.text.DefaultCaret;
public class LazyAppender extends JFrame implements ActionListener {
/**
* Demonstrates two different ways of appending text into TextArea
*/
private static final long serialVersionUID = 1L;
JTextArea textArea1;
JTextArea textArea2;
public LazyAppender() {
initUI();
}
public final void initUI() {
GridLayout experimentLayout = new GridLayout(2,2);
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(experimentLayout);
//Button 1
JButton button1 = new JButton("Button 1");
button1.setToolTipText("Append JtextArea1 without using Swing Timer");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
textArea1.append(getText());
textArea1.update(textArea1.getGraphics());
}
});
//Button 2
JButton button2 = new JButton("Button 2");
button2.setToolTipText("Lazy Append JtextArea2 using Swing Timer");
Timer timer2 = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
textArea2.append(getText());
}
});
timer2.setRepeats(false); //Execute only once
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//Start timer, this will release the button immediately
timer2.start();
}
});
//TextArea 1
textArea1 = new JTextArea("This is an editable JtextArea1. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea1.setFont(new Font("Serif", Font.ITALIC, 16));
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
//ScrollPane 1
JScrollPane areaScrollPane1 = new JScrollPane(textArea1);
areaScrollPane1.setViewportView(textArea1);
//TextArea 2
textArea2 = new JTextArea("This is an editable JtextArea2. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea2.setFont(new Font("Serif", Font.ITALIC, 16));
textArea2.setLineWrap(true);
textArea2.setWrapStyleWord(true);
//ScrollPane 2
JScrollPane areaScrollPane2 = new JScrollPane(textArea2);
areaScrollPane2.setViewportView(textArea2);
//Add Components into Panel
panel.add(button1);
panel.add(button2);
panel.add(areaScrollPane1);
panel.add(areaScrollPane2);
setTitle("Text Area Append Verify");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
}
public String getText(){
String stringToAppend = "This is your life. Do what you want and do it often." +
"If you don't like something, change it." +
"If you don't like your job, quit." +
"If you don't have enough time, stop watching TV." +
"If you are looking for the love of your life, stop; "+
"they will be waiting "+
"for you when you start doing things you love." +
"Stop over-analysing, life is simple." +
"All emotions are beautiful." +
"When you eat, appreciate every last bite." +
"Life is simple." +
"Open your heart, mind and arms to new things and people, "+
"we are united in our differences." +
"Ask the next person you see what their passion is and "+
"share your inspiring dream with them." +
"Travel often; getting lost will help you find yourself." +
"Some opportunities only come once, seize them." +
"Life is about the people you meet and the things you create "+
"with them, so go out and start creating." +
"Life is short, live your dream and wear your passion." +
"~ Holstee Manifesto, The Wedding Day ";
//Simulated delay
long start = new Date().getTime();
while(new Date().getTime() - start < 1000L){}
return stringToAppend;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
LazyAppender ex = new LazyAppender();
ex.setVisible(true);
}
});
}
}
Also, check this question JTextArea thread safe? for an in-depth discussion on whether its safe to JTextArea in multi-threaded environments.
Related
This question already has answers here:
How to use KeyListener with JFrame?
(4 answers)
Closed 4 years ago.
This is my Full code. It will help you understand.
I try to make what changes state when i clicking Button or pressing keyboard. when I pressing ENTER it changes START to STOP(or STOP to START). And when I clicked button START state changes to start. And when I clicked button STOP, state changes to STOP. I add System.out.println() for checking my code working correctly.
First time It works correctly . I can change state by pressing keyboard(ENTER)(I can see "Now Start" or "Now Stop")
But KeyListener(ENTER) doesn't work after click Button.
I don't know why... pleas help me.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ServerClass3 extends JFrame
{
String SS = "Now Stop";
public ServerClass3()
{
JButton btn_start = new JButton("Start");
JButton btn_stop = new JButton("Stop");
JButton btn_quit = new JButton("quit");
btn_start.setLocation(20, 20);
btn_start.setSize(100, 40);
btn_stop.setLocation(140, 20);
btn_stop.setSize(100, 40);
btn_quit.setLocation(260, 20);
btn_quit.setSize(100, 40);
btn_start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SS = "Now Start";
System.out.println("ss is " + SS);
}
});
btn_stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SS = "Now Stop";
System.out.println("ss is " + SS);
}
});
btn_quit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SS = "quit";
System.out.println("ss is " + SS);
}
});
KeyPanel p = new KeyPanel();
setContentPane(p);
p.add(btn_start);
p.add(btn_stop);
p.add(btn_quit);
setSize(300, 300);
setVisible(true);
p.requestFocus();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class KeyPanel extends JPanel
{
public KeyPanel()
{
this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
if (SS.equals("Now Stop"))
{
SS = "Now Start";
System.out.println(SS);
}
else
{
SS = "Now Stop";
System.out.println(SS);
}
}
}
});
}
}
public static void main(String[] args)
{
new ServerClass3();
}
}
This happens because after pressing one of the buttons, the focus is on the buttons. Because of this, the buttons soak up all events and none go through to your KeyPanel. You know this is true, because when starting the program and pressing spacebar, nothing happens. But as soon as you press a button, when pressing spacebar it executes the actionPerformed event of this button.
To fix this, set all buttons to not be focusable with the setFocusable function:
button.setFocusable(false);
This way, no matter what or where you click on the window, the buttons never get focused and all events get registered by the KeyPanel.
I am trying to finish this program to:
1st: Request user to enter a cellphone number in JOptionPane window
2nd: Show message "click OK to track the GPS coordinates of (input)
3rd: AFTER user clicks OK the splash screen should pop up.
4th: Splash screen should finish completely and after that the JOptionPane window should show the message "The address located within GPS coordinates is:" plus whatever fake address I enter in.
Right now the splash screen runs during everything else and is all out of order. I want the splash screen to execute after "OK" is clicked and then finish and proceed with the final JOptionPane message. Any help is greatly appreciated!! FYI-This program is intended as a fake gag joke.
public class SplashScreen extends JWindow {
static boolean isRegistered;
private static JProgressBar progressBar = new JProgressBar();
private static SplashScreen execute;
private static int count;
private static Timer timer1;
public SplashScreen() {
Container container = getContentPane();
container.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new javax.swing.border.EtchedBorder());
panel.setBackground(Color.green);
panel.setBounds(10, 10, 348, 150);
panel.setLayout(null);
container.add(panel);
JLabel label = new JLabel("Tracking target GPS coordinates...");
label.setFont(new Font("Verdana", Font.BOLD, 14));
label.setBounds(15, 25, 280, 30);
panel.add(label);
progressBar.setMaximum(50);
progressBar.setBounds(55, 180, 250, 15);
container.add(progressBar);
loadProgressBar();
setSize(370, 215);
setLocationRelativeTo(null);
setVisible(true);
}
private void loadProgressBar() {
ActionListener al = new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
count++;
progressBar.setValue(count);
System.out.println(count);
if (count == 300) {
createFrame();
execute.setVisible(false);
timer1.stop();
}
}
private void createFrame() throws HeadlessException {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
};
timer1 = new Timer(50, al);
timer1.start();
}
public static void main(String[] args) {
execute = new SplashScreen();
String targetCell = JOptionPane.showInputDialog(null, "Enter "
+ "target cellphone number: ");
JOptionPane.showMessageDialog(null, "Click OK to "
+ "track the GPS coordinates of " + targetCell + "...");
JOptionPane.showMessageDialog(null, "The address located within "
+ "GPS coordinates is: " /** + "random fake address") **/);
}
};
The order in which you do things is very important. If you look at your code, the SplashScreen makes the window visible when it's created, which is a bad idea and which you've suddenly discovered.
First, you need to change the order in which you do things, for example...
String targetCell = JOptionPane.showInputDialog(null, "Enter "
+ "target cellphone number: ");
JOptionPane.showMessageDialog(null, "Click OK to "
+ "track the GPS coordinates of " + targetCell + "...");
// Show and wait for splash screen to complete
JOptionPane.showMessageDialog(null, "The address located within "
+ "GPS coordinates is: " /**
* + "random fake address") *
*/
);
You would also need someway to have your splash screen provide event notification of when it had completed it's task, as JWindow is none blocking.
A simpler solution would be to display the splash screen within a modal JDialog, this would block the execution of the code at the point the splash screen was made visible, allowing you to "wait" until it had finished.
As a general rule of thumb, you should avoid extending from top level containers like JWindow, instead prefer something like JPanel, this provides you with the flexibility to display the component in any container you want.
It's also not the responsibility of the splash screen to launch the next window, it's only responsibility is to show the progress of it's activity (and possibly return the results of it's calculations)
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
String targetCell = JOptionPane.showInputDialog(null, "Enter "
+ "target cellphone number: ");
JOptionPane.showMessageDialog(null, "Click OK to "
+ "track the GPS coordinates of " + targetCell + "...");
SplashPane.showSplashScreen();
JOptionPane.showMessageDialog(null, "The address located within "
+ "GPS coordinates is: " /**
* + "random fake address") *
*/
);
}
});
}
public static class SplashPane extends JPanel {
private JProgressBar progressBar = new JProgressBar();
private Timer timer1;
public SplashPane() {
setLayout(new BorderLayout(0, 4));
setBorder(new EmptyBorder(10, 10, 10, 10));
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(new CompoundBorder(
new javax.swing.border.EtchedBorder(),
new EmptyBorder(30, 20, 30, 20)));
panel.setBackground(Color.green);
JLabel label = new JLabel("Tracking target GPS coordinates...");
label.setFont(new Font("Verdana", Font.BOLD, 14));
panel.add(label);
add(panel);
add(progressBar, BorderLayout.SOUTH);
loadProgressBar();
}
private void loadProgressBar() {
ActionListener al = new ActionListener() {
private int count;
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
count = Math.min(100, ++count);
progressBar.setValue(count);
System.out.println(count);
if (count == 100) {
SwingUtilities.windowForComponent(SplashPane.this).dispose();
timer1.stop();
}
}
};
timer1 = new Timer(150, al);
timer1.start();
}
public static void showSplashScreen() {
JDialog frame = new JDialog();
frame.setModal(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setUndecorated(true);
frame.add(new SplashPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
}
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
You are already clearly saying what you want, so why not just do it? :)
I guess you would have to show the 2 JOptionPanes first, save the cell number in a global variable or hand it to the Splashscreen instance.
And after your splashscreen has finished show the 3rd JOPtion pane with the cellNumber you saved.
So you should edit your actionPefromed Method, similar to this:
public void actionPerformed(java.awt.event.ActionEvent evt) {
count++;
progressBar.setValue(count);
System.out.println(count);
if (count == 300) {
execute.setVisible(false);
timer1.stop();
//splash screen finished so show JoptionPane here
JOptionPane.showMessageDialog(null, "The address located within "
+ "GPS coordinates is: " + targetCell)
}
}
I've ben researching how to use swing timers for 2 days now and am trying to figure out how to change the image I have at the center of my JFrame. As of now my program runs properly, but the image does not change the way I want it to. This class was just used as a test so it might not have proper java syntax.
package hauntedHouseAdventure;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class timertest {
static JFrame sceneOne = new JFrame();
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ImageIcon image = new ImageIcon(
"/Users/computerscience2/Desktop/dark-forest-night-image.jpg");
JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add(imageLabel, BorderLayout.NORTH);
sceneOne.add(panel);
sceneOne.setResizable(false);
imageLabel.setVisible(true);
sceneOne.pack();
JButton leave=new JButton("Leave");
JButton stay= new JButton ("Stay");
leave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
sceneOne.setVisible(false);
}
});
stay.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent f)
{
//Execute when button is pressed
sceneOne.setVisible(false);
}
});
panel.add(leave, BorderLayout.EAST);
panel.add(stay, BorderLayout.WEST);
JLabel label1 = new JLabel("Test");
label1.setText("<html><font color='red'> It was approximately 11:30 pm. The night sky was black not a single star piercing through the darkness"
+ "except the thick and powerful moonlight."
+ "<br>"
+ "You are alone leaving a costume party at a friend's place."
+ "It was rather boring and you decided to leave early."
+ "A stutter is heard and your"
+ "<br>"
+ "car begins to shake"
+ "Your headlights and car lights crack. The engine is left dead silent."
+ "You are left in a total silence"
+ "and baked in merely the moonlight."
+ "<br>"
+ "There is a mere second of silence till a harsh chill ripes through the"
+ "car like a bullet through paper. You are left dumbfounded. What do you do?</font><html>");
label1.setHorizontalAlignment(JLabel.CENTER);
label1.setVerticalAlignment(JLabel.BOTTOM);
label1.setVisible(true);
label1.setOpaque(false);
panel.add(label1);
final ActionListener updater = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
ImageIcon image = new ImageIcon(
"/Users/computerscience2/Desktop/image-slider-5.jpg");
JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add(imageLabel, BorderLayout.NORTH);
sceneOne.add(panel);
}
};
Timer timer = new Timer(1000, updater);
timer.start();
sceneOne.setSize(2000,1000);
sceneOne.setTitle("The Car");
sceneOne.setVisible(true);
sceneOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sceneOne.setLocation(250, 200);
}
}
I see two problems in your code.
You are adding the new image to your panel, but not removing the old image.
You are not telling to your frame that your components changed and he needs to redraw.
I think the best way to do this, is just changing the icon of your imageLabel. Like this:
final JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
......
final ActionListener updater = new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon image = new ImageIcon("/Users/computerscience2/Desktop/image-slider-5.jpg");
imageLabel.setIcon(image);
imageLabel.updateUI(); //Tell to your frame he needs to redraw the image
}
};
I didn't look in detail but to change the image on the label then you don't need to create a new control, you just need to change the image on the existing one.
public void actionPerformed(ActionEvent event) {
ImageIcon image = new ImageIcon(
"/Users/computerscience2/Desktop/image-slider-5.jpg");
imageLabel.setIcon(image);
}
You will also need to make imageLabel either a member variable or final so that the actionPerformed method can see it.
enter image description hereI'm a new programmer and I'm working on a text adventure that uses dropdown boxes (choice) as an input device. I have an itemListener on the first box that populates the members of the 2nd with the members that can be added. The player is then allowed to click the submit button and the first box is reset to the first item on the list and the second box is supposed to be cleared. When I run the program, the first time it reacts exactly as planned. The 2nd time I try to input something using the drop down boxes, the dropdown box doesn't respond. I put a marker inside the itemListener to see if it was even triggering to find out that it wasn't. I feel like I've tweeked the program in every way imaginable but I have no idea what is causing this issue. If I toggle between the items in the drop down box a few times the itemListener starts to respond again.
This is a representation of my issue I threw together.
import java.awt.Choice;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
public class gui implements ActionListener
{
private static JTextPane outputField = new JTextPane();
private static JPanel mainPanel = new JPanel(new GridBagLayout());
private Choice commandDropDown = new Choice();
private Choice itemDropDown = new Choice();
private JButton submitButton = new JButton();
public gui()
{
JFrame frame = new JFrame("test");
mainPanel.setSize(450,585);
commandDropDown = buildCommandBox(commandDropDown);
commandDropDown.setBounds(100, 15, 100, 40);
itemDropDown.setBounds(200, 15, 100, 40);
submitButton.setText("submit");
submitButton.setBounds(15, 15, 100, 40);
submitButton.addActionListener(this);
frame.add(commandDropDown);
frame.add(itemDropDown);
frame.add(submitButton);
frame.setResizable(false);
frame.pack();
frame.setSize(300, 300);
//frame.setLayout(null);
//frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
itemDropDown.removeAll();
commandDropDown.select(0);
}
private Choice buildCommandBox(Choice custoChoi)
{
final Choice c = new Choice();
c.addItem("choices");
c.addItem("Option1");
c.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ie)
{
System.out.println("the action event for the command"
+ "box is working.");
if(c.getSelectedItem().equals("Option1"))
{
itemDropDown.addItem("things");
itemDropDown.addItem("stuff");
}
}
});
return c;
}
}
Hopefully these pictures clear up any confusion about my post.
http://imgur.com/a/h9oOX#0
In my opinion, your buildCommandBox( Choice custoChoi) is wrong, it should be something like that:
private Choice buildCommandBox(final Choice custoChoi) {
custoChoi.addItem("choices");
custoChoi.addItem("Option1");
custoChoi.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
System.out.println("the action event for the command" + "box is working.");
if (custoChoi.getSelectedItem().equals("Option1")) {
itemDropDown.addItem("things");
itemDropDown.addItem("stuff");
}
}
});
return custoChoi;
}
I would recommand to use JComboBox instants of Choice, if Swing is allowed.
I have made a GUI in NetBeans. It's a chat program and i have 4 commandos like /join, /leave, /whisper and /leave
private void CommandoActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(rootPane, "The following commandos are:" + "\n" + "\n" + "/join Channel name" + "\n" + "/leave channel name" + "\n" + "/whisper nick message" + "\n" + "/quit - quit the program");
}
And this is OK, but i want actionlister instead of the showMessageDialog so i can push on of them and it comes in my JTextField. I think i can get them there but i don't know how to get the actionlistener combined with this.
EDIT:
What i want is to push the Commando button and get up a windows where i have 4 new buttons, each with one commando (/join, /leave, /whisper and /exit) so when i push 1 of these buttons i get the commando in my text field so i just need to write the rest.
So if i push the "/join" button, i just need to write the channel name.
EDIT2: If I was pretty bad in describing the problem, I can show what i wanted and have done so far:
private void showCommandActionPerformed(java.awt.event.ActionEvent evt) {
Object[] options = { "/join", "/leave", "/whisper", "/quit", "Ingenting" };
int choice= JOptionPane.showOptionDialog(rootPane, "What do u want to do? ", null, WIDTH, WIDTH, null, options, rootPane);
switch (choice) {
case 0:
skrivTekst.setText("/Join ");
skrivTekst.requestFocus();
break;
case 1:
skrivTekst.setText("/Leave");
skrivTekst.requestFocus();
break;
case 2:
skrivTekst.setText("/Whisper");
skrivTekst.requestFocus();
break;
case 3:
skrivTekst.setText("/Join ");
skrivTekst.requestFocus();
case 4:
System.exit(1); //this is wrong. i just want to close this window, not the whole program
default:
JOptionPane.showMessageDialog(null, "donno what!?!?!?!?!?!?!" + choice);
}
}
I hope this show what i wanted and what i have done. Ty to all :)
So the only problem i have left is closing the one JOptionPane window and not the program
1) you can implements JRadioButtons in the ButtonGroup, then only one of choices would be available for selection, there you can implelements ActionListener, and inside ActionListener setText() for JTextField
2) please use standard Swing JComponents rather than prepared Components from the palette, sometimes is too hard override basic Swing methods
simple example based on example for JRadioButton's from tutorial
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/*
* RadioButtonDemo.java is a 1.4 application that requires these files:
* images/Bird.gif images/Cat.gif images/Dog.gif images/Rabbit.gif
* images/Pig.gif
*/
public class RadioButtonDemo extends JPanel implements ActionListener {
private static String birdString = "Bird";
private static String catString = "Cat";
private static String dogString = "Dog";
private static String rabbitString = "Rabbit";
private static String pigString = "Pig";
private static final long serialVersionUID = 1L;
private JLabel picture;
public RadioButtonDemo() {
super(new BorderLayout());
//Create the radio buttons.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setMnemonic(KeyEvent.VK_B);
birdButton.setActionCommand(birdString);
birdButton.setSelected(true);
JRadioButton catButton = new JRadioButton(catString);
catButton.setMnemonic(KeyEvent.VK_C);
catButton.setActionCommand(catString);
JRadioButton dogButton = new JRadioButton(dogString);
dogButton.setMnemonic(KeyEvent.VK_D);
dogButton.setActionCommand(dogString);
JRadioButton rabbitButton = new JRadioButton(rabbitString);
rabbitButton.setMnemonic(KeyEvent.VK_R);
rabbitButton.setActionCommand(rabbitString);
JRadioButton pigButton = new JRadioButton(pigString);
pigButton.setMnemonic(KeyEvent.VK_P);
pigButton.setActionCommand(pigString);
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);
group.add(dogButton);
group.add(rabbitButton);
group.add(pigButton);
//Register a listener for the radio buttons.
birdButton.addActionListener(this);
catButton.addActionListener(this);
dogButton.addActionListener(this);
rabbitButton.addActionListener(this);
pigButton.addActionListener(this);
//Set up the picture label.
picture = new JLabel("Narrative");
//The preferred size is hard-coded to be the width of the
//widest image and the height of the tallest image.
//A real program would compute this.
//picture.setPreferredSize(new Dimension(177, 122));
//Put the radio buttons in a column in a panel.
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(birdButton);
radioPanel.add(catButton);
radioPanel.add(dogButton);
radioPanel.add(rabbitButton);
radioPanel.add(pigButton);
add(radioPanel, BorderLayout.LINE_START);
pigButton.setVisible(false);
rabbitButton.setVisible(false);
add(picture, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
/** Listens to the radio buttons.
* #param e
*/
public void actionPerformed(ActionEvent e) {
String narr = e.getActionCommand();
picture.setText(narr);
}
/** Returns an ImageIcon, or null if the path was invalid.
* #param path
* #return
*/
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = RadioButtonDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("RadioButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new RadioButtonDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You want 4 buttons, each one setting a command text into the text field, is that right?
joinButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
theTextField.setText("/join");
}
});
And do the same with the other 3 buttons.
This is really basic stuff. Read the tutorial about event listeners.
Something like this?
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == join) {
textField.setText("/join");
} else if (source == leave) {
textField.setText("/leave");
} else if (source == whisper) {
textField.setText("/join");
} else {
textField.setText("/exit");
}
}
This is going on the assumption that your buttons are named join, leave, whisper, and exit.