I have 6 JLabel and each is having a different instance of a mouselistener class attached. How to know which JLabel has been clicked ? These JLabel form a two dimentional array.
You use getSource to get a refrence to the object which is clicked on:
label1.addActionListener(new yourListener());
label2.addActionListener(new yourListener());
public class yourListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
JLabel labelReference=(JLabel)e.getSource();
labelReference.someMethod();
}
}
The easiest way I did something like that was, to use JButtons and make them look like JLabels by the using this syntax formatting.
jButton.setBorder( BorderFactory.createEmptyBorder( 2, 2, 2, 2 ) );
jButton.setBorderPainted( false );
jButton.setContentAreaFilled( false );
jButton.setFocusPainted( false );
jButton.setHorizontalAlignment( SwingConstants.LEFT );
Then, what you want to is add an ActionLister and a ActionCommand. For example
jButton.addActionListener( this );
jButton.setActionCommand( "label1" );
Then just handle the actionListners to do what you wanted for each label.
public void actionPerformed( ActionEvent arg0 )
{
String command = arg0.getActionCommand();
if( command.equalsIgnoreCase( "label1" ) )
{
//label1 code
}
}
As mentioned below this also has the added benefit of supporting both keyboard and mouse activities.
I put this together based on your description:
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
for (int i = 0; i < 6; i++) {
JLabel l = new JLabel("Label " + (i + 1));
l.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JLabel l = (JLabel) e.getSource(); // here
System.out.println(l.getText());
}
});
f.add(l);
}
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
I think the line marked // here is mostly what you need.
Related
I have a class that has 4 private attributes, and through a JComboBox selection, I want to modify them through calling a procedure. However, it seems like even though the JComboBox appears with the selection, the attributes that are shown don't change.
public class PanneauVehicule extends JPanel {
private String[] vehicules;
private int majCarburant;
private int majPassager;
public class PanneauVehicule extends JPanel {
//Main constructor
public PanneauVehicule(){
//Creates a JPanel
super();
//Sets layout as BorderLayout
setLayout(new BorderLayout());
initListeVehicule();
initLabels();
}
public void initListeVehicule(){
vehicules = new String[] {Constantes.CS100 , Constantes.CS300 ,
Constantes.GREYHOUND102D3 , Constantes.GREYHOUNDG4500 ,
Constantes.TGVATLANTIQUE , Constantes.TGVDUPLEX};
final JComboBox<String> vehiculesList = new JComboBox<>(vehicules);
//Keep in mind the comboBox does appear with the right selections
add(vehiculesList,BorderLayout.NORTH);
//Here's where it doesnt work.
vehiculesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
majInfo(2,4);
}
});
}
public void majInfo(int test1, int test2){
this.majCarburant = test2;
this.majPassager = test1;
}
public void initLabels(){
JPanel panneauBas = new JPanel();
panneauBas.setLayout(new GridLayout(2,1,5,5));
JLabel labelCarburant = new JLabel();
labelCarburant.setText("Type de caburant: " + this.majCarburant);
JLabel labelPassagers = new JLabel();
labelPassagers.setText("Nb de passagers: " + this.majPassager);
panneauBas.add(labelPassagers);
panneauBas.add(labelCarburant);
add(panneauBas, BorderLayout.SOUTH);
panneauBas.setBackground(Color.WHITE);
}
After that, I use another procedure that will make majCarburant and majPassager appear on screen. However their values are shown as default (0). I can make their values change manually without using an ActionListener, but the task at hand requires me to use one.
I've been trying ways to just simply change the values through actionListener directly,
You don't invoke an ActionListener directly. Once an ActionListener has been added to the combo box, you can invoke:
setSelectedItem(...) or
setSelectedIndex(...)
on the combo box and the combo box will invoke the ActionListener.
I found the solution after a few more hours of meddling. I just integrated the procedure that creates labels into initListeVehicule, and from there the ActionListener can access the labels to modify their texts.
public void initListeVehiculeInfos(){
vehicules = new String[] {Constantes.CS100 , Constantes.CS300 ,
Constantes.GREYHOUND102D3 , Constantes.GREYHOUNDG4500 ,
Constantes.TGVATLANTIQUE , Constantes.TGVDUPLEX};
final JComboBox<String> vehiculesList = new JComboBox<>(vehicules);
add(vehiculesList,BorderLayout.NORTH);
JPanel panneauBas = panelGenerator();
//these setTexts serve as default values before doing your first selection
final JLabel carb = labelGenerator();
carb.setText("Carburant: Kérosène");
final JLabel passager = labelGenerator();
passager.setText("Nb Passager: 110");
vehiculesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
InterfaceVehicules info = FabriqueVehicule.obtenirVehicule(vehiculesList.getSelectedIndex());
carb.setText("Carburant: " + info.tabNomTypeCarburant[info.getTypeCarburant()] );
passager.setText("Nb Passagers: " + info.getNbPassagersMax());
}
});
panneauBas.add(carb);
panneauBas.add(passager);
add(panneauBas, BorderLayout.SOUTH);
}
I have made this simple text editor program but can't figure out how to change GUI component's properties while the program is running.
Suppose this is a part of my Text Editor's source code:
boolean wordwrap = false;
void mainFrame() {
frame = new JFrame("Text Editor");
textArea = new JTextArea(50,20);
textArea.setLineWrap(wordwrap);
and let's say I have an event source(JButton) added as Listener to change
textArea's .setLineWrap(boolean). Just like this:
public void actionPerformed(ActionEvent event) {
if(wordwrap) wordwrap = false;
else wordwrap = true;
textArea.setLineWrap(wordwrap);
frame.repaint();
}
But this code is not working!!. So, what is the correct way to update or edit a JAVA GUI component while the program is running ?
revalidate and validate()
will update the frame.
You do not need to use repaint().
Final Method:
public void actionPerformed(ActionEvent event) {
if(wordwrap) wordwrap = false;
else wordwrap = true;
textArea.setLineWrap(wordwrap);
frame.revalidate(); //is preferable but validate() also works.
}
You can either update the whole frame or just update the jComponent (insert TextArea instead of "frame".revalidate();)
Just FYI, after I got a chance to test it, it works fine without either the revalidate() or the repaint(). I suspect the problem was somewhere else in your code.
public class TestTextArea
{
private final static String testLine =
"This is some rather long line that I came up with for testing a textArea.";
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
gui();
}
} );
}
private static void gui()
{
JFrame frame = new JFrame();
final JTextArea textArea = new JTextArea();
JPanel span = new JPanel();
JButton toggle = new JButton( "Switch line wrap" );
toggle.addActionListener( new ActionListener()
{
#Override
public void actionPerformed( ActionEvent e )
{
textArea.setLineWrap( !textArea.getLineWrap() );
}
} );
for( int i = 0; i < 10; i++ )
textArea.append( testLine + testLine + "\n" );
span.add( toggle );
frame.add( span, BorderLayout.SOUTH );
frame.add( textArea );
frame.pack();
frame.setSize( 500, 500 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
My question is on how do I go about know what the text of the drag and drop location is. This is current working code.
gameCell.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
JButton button = (JButton)e.getSource();
int currentNumber = Integer.parseInt(button.getText());
TransferHandler handle = button.getTransferHandler();
handle.exportAsDrag(button, e, TransferHandler.COPY);
So the idea is there is a gameboard which is just a bunch of cells (all JButtons), one large table. When I drag one cell to another then the dragged cell's value will become the clicked cell's value, so therefore how do I tell the original value of the JButton cell before it is copied over by the dragged cell.
If you are just trying to "copy" the text from one button to another then you can use code like the following:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragIcon extends JPanel
{
public DragIcon()
{
TransferHandler iconHandler = new TransferHandler( "icon" );
MouseListener dragListener = new DragMouseAdapter();
JLabel label1 = new JLabel("Label1");
label1.setTransferHandler( iconHandler );
label1.addMouseListener(dragListener);
label1.setIcon( new ImageIcon("copy16.gif") );
JLabel label2 = new JLabel("Label2");
label2.setTransferHandler( iconHandler );
label2.addMouseListener(dragListener);
add( label1 );
add( label2 );
}
private class DragMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
// handler.exportAsDrag(c, e, TransferHandler.MOVE);
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Drag Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DragIcon());
frame.setLocationByPlatform( true );
frame.setSize(200, 100);
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
The default TransferHandler allows you to specify a property that you want to copy. In my example I'm copying the Icon. In your case you would use:
TransferHandler iconHandler = new TransferHandler( "text" );
to copy the text.
Note in my example I also tried to "move" the Icon from one label to another but it doesn't work. I'm not sure what needs to be changed to move a property.
I have a fully functional console-based database which I need to add GUIs to. I have created a tab page (currently only one tab) with a button "Display All Student" which when triggered will display a list of students inside a JTextArea which of course is in its own class and not inside the button's action listener class. Problem is, the JTextArea is not recognised inside button's action listener. If I add parameter into the action listener, more errors arise. Help?
I have searched Stack Overflow for similar problems but when I tried it in my code, doesn't really do the trick? Or maybe I just need a nudge in the head. Anyways.
Here is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StudDatabase extends JFrame
{
private JTabbedPane tabbedPane;
private JPanel studentPanel;
private static Scanner input = new Scanner(System.in);
static int studentCount = 0;
static Student studentArray[] = new Student[500];
public StudDatabase()
{
setTitle("Student Database");
setSize(650, 500);
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create the tab pages
createStudentPage();
// more tabs later...
// Create a tab pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Student Admin", studentPanel );
topPanel.add( tabbedPane, BorderLayout.CENTER );
}
public void createStudentPage()
{
studentPanel = new JPanel();
studentPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton listButton = new JButton("List All Student(s)");
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(studentCount > 0)
{
for(int i=0; i<studentCount; i++)
{
// print out the details into JTextArea
// ERROR! textDisplay not recognised!!!
textDisplay.append("Student " + i);
}
System.out.printf("\n");
}
else // no record? display warning to user
{
System.out.printf("No data to display!\n\n");
}
}
});
studentPanel.add(listButton);
JTextArea textDisplay = new JTextArea(10,48);
textDisplay.setEditable(true); // set textArea non-editable
JScrollPane scroll = new JScrollPane(textDisplay);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
studentPanel.add(scroll);
}
public static void main(String[] args)
{
StudDatabase mainFrame = new StudDatabase();
mainFrame.setVisible(true);
}
Your code isn't working for the same reason this wouldn't work:
int j = i+5;
int i = 4;
You have to declare variables before using them in Java.
Secondly, in order to use a variable (local or instance) from inside an inner class - which is what your ActionListener is - you need to make it final.
So, the below code will compile and run:
final JTextArea textDisplay = new JTextArea(10,48);
...
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
...
textDisplay.append("Student " + i);
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);
}
}