I have .txt files and I read them to a JList, then I want to select a name of a file from a JComboBox, read that file, create the list and appear on the frame inside of a JScrollPane.
I have almost everything working the only problem is that I can't add the scroll pane with the list to the frame correctly and the list only appears when I press the button "envia". The way I have my code inserting the list to the scroll pane and then to the window is not correct because the scroll pane are being inserted on top of each other, but its the closest I got to wokring.
I want it to appear on the the scroll pane and on the frame correctly when I press on the combo box and not when I press "envia". I don't understand why the list only appears when I press that button.
combo2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
falarpara = combo2.getSelectedItem().toString();
try {
lista = f.getList(user, falarpara);
janela.add(lista.getlist());
JScrollPane j = new JScrollPane(lista.getlist());
janela.add(j);
janela.validate();
} catch (FileNotFoundException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
}
});
envia.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String a = new String(user + ":" + " " + txt.getText());
f.escreve(user, falarpara, a);
lista.add(a);
txt.setText(null);
}
});
Related
In my java code below it produces a frame with a jtextrea. This allows for simple text processing. All I want to do is add " Sam". Which is 5 spaces with sam at the end. Every time the user hits enter. You can see also the gif I added below which is exactly what I am looking for.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class text11 extends JFrame implements ActionListener {
// JFrame
static JFrame f;
// text area
static JTextArea jt;
// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("textfield");
// create a label to display text
// create a object of the text class
text11 te = new text11();
// create a text area, specifying the rows and columns
jt = new JTextArea(" ", 20, 20);
JPanel p = new JPanel();
// add the text area and button to panel
p.add(jt);
f.add(p);
// set the size of frame
f.setSize(300, 300);
f.show();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
String actionKey = "ADD_SAM";
InputMap inputMap = jt.getInputMap(JComponent.WHEN_FOCUSED);
KeyStroke enterPressed = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
inputMap.put(enterPressed, actionKey);
jt.getActionMap().put(actionKey, new TextAction(actionKey) {
#Override
public void actionPerformed(ActionEvent e) {
jt.append(" Sam\n");
}
});
To get input so you know when the use hits enter, you have to create your own KeyListener class. If you don't know how to use it, here is a handy link from the documentation you can use: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html.
But simply put, an KeyListener is an interface where you have to specify a few methods, but in your case I think the only one you need is keyPressed(KeyEvent e)(which is called pressed). If you're interested in the others, keyReleased(KeyEvent e) is when a key gets released, and keyType(KeyEvent e) is when it's pressed and released quickly. Then, use JFrames addKeyListener(KeyListener k) to add your custom action listener.
After you did that, you can use JTextArea's setText() and getText() method to append " sam" to the end (the 5 spaces get cut of by stack overflow, I know you want 5 spaces).
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
jt.setText(jt.getText() + " sam");
}
}
If you added the KeyListener correctly, you should be fine!
I have a JList with MULTIPLE_INTERVAL_SELECTION enabled and I'd like to pass the order in which the items are selected to another process.
I've tried using a MouseListener on the JList and checking if getClickCount() == 1 then add it to an array, however, this will not add new items that are below the selected item, it only adds items that are above the currently selected item in the JList.
For example if my list looks like this:
1
2
3
4
5
If I click number 1 first, then the below code will only show 1 for every subsequent click. If I click 3 first and then click 5 the number that pops up is 3. If I click 3 and then click 2 or 1, those numbers will popup correctly.
So I never actually get to the part of adding data to an array because I cannot get the data to display based up an action correctly.
Here is sample code from the listener:
private class ListBoxListener implements ListSelectionListener, MouseListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if(e.getSource().equals(aList)) {
System.out.println(aList.getSelectedValue());
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getClickCount() == 1) {
JOptionPane.showMessageDialog(null, aList.getSelectedValue());
}
}
}
Is there anything glaringly wrong with what I'm trying to do?
you should try this code
JFrame frame = new JFrame("JList Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
String[] selections = {"Java", "C++", "C", "Scala", "JavaScript"};
JList list = new JList(selections);
frame.add(new JScrollPane(list));
frame.pack();
frame.setVisible(true);
MouseListener mouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent mouseEvent) {
if (mouseEvent.getClickCount() == 1) {
int index = list.locationToIndex(mouseEvent.getPoint());
if (index >= 0) {
Object obj = list.getModel().getElementAt(index);
JOptionPane.showMessageDialog(null, obj);
}
}
}
};
list.addMouseListener(mouseListener);
}
I understoud that you want to add an item listener to jList. So here is a simple code to show you how to do it:
ArrayList<String> list = new ArrayList<>();
jList1.addListSelectionListener(new ListSelectionListener(){
#Override
public void valueChanged( ListSelectionEvent e){
if(! e.getValueIsAdjusting()){
list.add(jList1.getSelectedValue());
}
}
});
I added JLabel on JFrame and displayed frame on YES button click of JOptionPane, it displays frame but didn't display label text.
int yes = JOptionPane.showConfirmDialog(null,"Do you want to reactivate previous
schedule(s)","Reactivate Schedule",JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if(yes == JOptionPane.OK_OPTION) {
setVisible(false);
disp_wait.setVisible(true);
for(int i=0 ; i<options.taskList.size(); i++) {
dataList = Options.getInstance().getTaskList();
Task task=dataList.get(i);
boolean active = task.getActive();
if(active) {
task.setActive(true);
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.getMessage();
}
}
}
}
All your code is performing some processing during an event handling. In Java this is a problem, the GUI only gets drawn once all the event handling is processed. Besides that, it would be great to see the code for your JFrame, it probably does not add the Label before calling pack()
This is my actionListener for a popup menu button i want to add this picture on the panel after every its clicked
mntmNewMenuItem.addActionListener(new ActionListener() {
//This method will be called whenever you click the button.
int i;
public void actionPerformed(ActionEvent e) {
try {
label.setIcon(new ImageIcon
(new URL("file:/C:/Users/Ashad/JunoWorkspace/FYP1/table.png")));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
panel.add(label);
//redraw panel after addition
panel.validate();
panel.repaint();
handleDrag(label);
}
});
you can only add a UI object once.
if you want just a single instance to be added, you need to remove that element 1st then add. (but it doesn't seem logical removing then adding).
instead you can create a Label() object inside actionperformed
public void actionPerformed(ActionEvent e) {
label = new Label();//Added
try {
label.setIcon(new ImageIcon
(new URL("file:/C:/Users/Ashad/JunoWorkspace/FYP1/table.png")));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
I was trying to make a JMenu behave like a JButton but I'm having some problems and hopefully someone here can help!
I've added a MenuListener to the JMenu item with this but I cant get the popup menu/focus to leave to enable me to properly click the JMenu repeated times to trigger this function and i was hoping someone could tell me what i'm doing wrong. Thanks.
public void menuSelected(MenuEvent e)
{
... // do stuff here code
JMenu source = (JMenu)e.getSource();
source.setSelected(false);
source.setPopupMenuVisible(false);
}
Not completely sure what you're asking...
But JMenuBar inherits from Container - if you'd rather add a JButton to it than a JMenu you can simply call -
JMenuBar menuBar = ....
JButton myButton = ....
menuBar.add(myButton);
This code sample runs in eclipse, Again concerned about how you are using it?
public class MyMenuFrame extends JFrame {
public MyMenuFrame() throws HeadlessException {
super("My Frame");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
Container pane = this.getContentPane();
pane.setLayout(new BorderLayout());
pane.add(new JLabel("Hi there"), BorderLayout.PAGE_START);
this.setVisible(true);
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.addMenuListener(new MenuListener() {
#Override
public void menuSelected(MenuEvent e) {
System.out.println("a");
}
#Override
public void menuDeselected(MenuEvent e) {
System.out.println("a");
}
#Override
public void menuCanceled(MenuEvent e) {
System.out.println("a");
}
});
menubar.add(menu);
this.setJMenuBar(menubar );
}
public static void main(String[] args) {
new MyMenuFrame();
}
}
I know this is an old thread, but I think I might have a solution. I stumbled accross this problem in one of my apps, and found a workaround. Try using a JMenuItem instead of a JMenu. It will have the same L&F as a JMenu when you attach it to a JMenuBar. The only thing you have to do is set the size of your new "button", as your Layout Manager (even if you have not set one) will resize this component based on its own rules:
http://www.javaworld.com/javaworld/jw-09-2000/jw-0922-javatraps.html
The way to do it is found under that link (if you feel uncomfortable clicking on the link, google for "setsize doesnt work" - it will be the in the top ten results). If you do not set the size properly, your new "button" will fill up the remaining space of your JMenuBar.
try this code:
menuItem.setMinimumSize(someMenu.getSize());
menuItem.setPreferredSize(someMenu.getSize());
menuItem.setMaximumSize(someMenu.getSize());
menuItem.setActionCommand("ActionText");
setActionCommand() method will set an action command, so that when you click your new "button" this will be the action command passed by the action event argument to the action performed method, so that you can easily identify it:
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
Hope this helps!
It's very difficult to determine what you're trying to do here. But I don't think you are properly using JMenu.
A JMenu is the object that represents a Menu. It is separate from the menu bar (JMenuBar) and from the menu item (JMenuItem). A JMenuBar usually contains multiple JMenus (File, Edit, etc) which in turn contain multiple JMenuItems (New, Open, Close). The JMenuItems are what is clicked and "acts like a button" in the menu.
To get a menu item to act like a button, simply add it to the menu. For example:
JMenu fileMenu = new JMenu("File");
JMenuItem newChoice = new JMenuItem("New");
newChoice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
newHasBeenSelected();
}
});
fileMenu.add(newChoice);
If you're trying to create a pop-up menu, you need to use JPopupMenu instead of JMenu, and you don't need a JMenuBar. Here are the Java tutorials on menus: http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
And here are the Java docs for JMenuBar, JMenu, JPopupMenu, and JMenuItem.
If you edit your question and give a more detailed explanation of what you're doing I might be able to give more specific help.
Ok I decided to investigate this a bit more and The following is the reslut and appears to act just like a JButton but appears like a jmenu on a jmenubar. Code below. (note just adding an actionListener to a JMenu didnt work right which is the reason for the mouselistener. You add an actionListener to the menubutton just like a normal button and as long as you dont add any menuitems to the menubutton (which technically you could) it will appear as a JMenu on the JMenuBar but behave like a button.
import java.awt.Component;
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.lang.reflect.Method;
import java.util.EventListener;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
public class MenuButton extends JMenu {
private boolean startedIn = false;
private ActionListener action;
public MenuButton(String title) {
super(title);
removeListeners(this);
this.addMouseListener(new MenuButtonListener());
}
public MenuButton(ImageIcon icon) {
super();
removeListeners(this);
this.addMouseListener(new MenuButtonListener());
this.setIcon(icon);
}
public void addActionListener(ActionListener a) {
action = a;
}
//we need to remove all the listeners already associated with a JMenu. If we do
//not do this, then it will not behave as expected because some mouseclicks are eaten
//by these listeners. There is no easy way to do that, the following method is a
//workaroundprovided in the java bug database.
static private void removeListeners(Component comp) {
Method[] methods = comp.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
String name = method.getName();
if (name.startsWith("remove") && name.endsWith("Listener")) {
Class[] params = method.getParameterTypes();
if (params.length == 1) {
EventListener[] listeners = null;
try {
listeners = comp.getListeners(params[0]);
} catch (Exception e) {
// It is possible that someone could create a listener
// that doesn't extend from EventListener. If so, ignore
// it
System.out.println("Listener " + params[0]
+ " does not extend EventListener");
continue;
}
for (int j = 0; j < listeners.length; j++) {
try {
method.invoke(comp, new Object[] { listeners[j] });
// System.out.println("removed Listener " + name +
// " for comp " + comp + "\n");
} catch (Exception e) {
System.out
.println("Cannot invoke removeListener method "
+ e);
// Continue on. The reason for removing all
// listeners is to
// make sure that we don't have a listener holding
// on to something
// which will keep it from being garbage collected.
// We want to
// continue freeing listeners to make sure we can
// free as much
// memory has possible
}
}
} else {
// The only Listener method that I know of that has more
// than
// one argument is removePropertyChangeListener. If it is
// something other than that, flag it and move on.
if (!name.equals("removePropertyChangeListener"))
System.out.println(" Wrong number of Args " + name);
}
}
}
}
public class MenuButtonListener extends MouseAdapter {
boolean within = false;
boolean pressed = false;
public void mousePressed(MouseEvent e) {
MenuButton.this.setSelected(true);
pressed = true;
//System.out.println("pressed");
}
public void mouseReleased(MouseEvent e) {
//System.out.println("released");
MenuButton.this.setSelected(false);
if (action != null && within && pressed) {
action.actionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, null));
MenuButton.this.setSelected(false);
}
pressed = false;
}
#Override
public void mouseEntered(MouseEvent e) {
within = true;
}
#Override
public void mouseExited(MouseEvent e) {
within = false;
}
}
}