Display PopMenu with java Swing - java

I have a problem with popapMenu with java swing can you help me
there is my code
package com.bar.menu;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
#SuppressWarnings("serial")
public class PopMenuSample extends JFrame {
public PopMenuSample() {
super("Pop menu exemple");
this.setSize(600, 400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel panel = (JPanel) getContentPane();
// the content of the window
JScrollPane LeftjScrollPane = new JScrollPane(new JTree());
LeftjScrollPane.setPreferredSize(new Dimension(200, 0));
JTextArea textArea = new JTextArea();
JScrollPane rightjScrollPane = new JScrollPane(textArea);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
LeftjScrollPane, rightjScrollPane);
panel.add(splitPane);
JPopupMenu popupMenu = this.createPopupMenu();
textArea.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent event) {
if (event.isPopupTrigger()) {
popupMenu.show(event.getComponent(), event.getX(),
event.getY());
}
}
});
}
private JPopupMenu createPopupMenu() {
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem menuNew = new JMenuItem("New File");
popupMenu.add(menuNew);
return popupMenu;
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
PopMenuSample menuSample = new PopMenuSample();
menuSample.setVisible(true);
}
}
this exemple is very easy (a window is contains two zones on the left is the Jtree() and on the right is textArea in this place i want to activate my problem when is of the right mouse i want to display New File) but i can't to show the popmenu New File in the textArea by the left boton of my mouse
I used java 8
Can you help me and thanks :)

public void mousePressed(MouseEvent event) {
You are only checking the mousePressed event.
The popup trigger can be different for different LAF's.
You also need to check the mouseReleased event.
See the section from the Swing tutorial on Bringing Up a Popup Menu for more information.

Related

JPopupMenu appears but seems to not react

I've problems to get a JPopupMenu working correctly.
What I expect
The menu should pop up once I do a right click with my mouse. Then I can select an item from the menu and do whatever I want..
What I actually get
The menu appears once I do a right click but after that I can not select a menu item or at least I am missing the well known mouse hover highlight effect (I would expect that the item I am currently hovering is highlighted, like it is the case in the normal menu).
The see problem here (no highlight on hover):
Here is my example code:
package com.mycompany.mavenproject2;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
public class PopupMenuTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel pane = new JPanel();
JPopupMenu popup = new JPopupMenu();
popup.add(new JMenuItem("A"));
popup.add(new JMenuItem("B"));
pane.setSize(300,300);
pane.add(popup);
pane.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)) {
popup.setLocation(e.getXOnScreen(), e.getYOnScreen());
popup.setVisible(true);
}
}
});
frame.setTitle("Test");
frame.add(pane);
frame.setPreferredSize(new Dimension(300,300));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Edit
Compare to a "normal" menu with working hovering:
Edit #2
Please see the current (unexpected) behaviour:
You need to use the JPopupMenu show method, rather than the setVisible method.
Here's the code I tested with. I'm running Windows 10 and using the Java JDK 13.0.2 with Java 8 compliance. I get the highlight on the mouse over.
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
public class JPopupMenuTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JPopupMenuTest());
}
#Override
public void run() {
JFrame frame = new JFrame();
JPanel pane = new JPanel();
pane.setPreferredSize(new Dimension(300, 300));
pane.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
JPopupMenu popup = new JPopupMenu();
popup.add(new JMenuItem("A"));
popup.add(new JMenuItem("B"));
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
frame.setTitle("JPopupMenu Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Add a JScrollPane to a JList

I have the following code:
Main:
package PackageMain;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Main {
public static JFrame frame = new JFrame("Window");
public static PanelOne p1;
public static PanelTwo p2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 800, 600);
p1 = new PanelOne();
p2 = new PanelTwo();
frame.setVisible(true);
} catch(Exception e){
}
}
});
}
And class 2:
package PackageMain;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class PanelOne{
public PanelOne(){
loadScreen();
}
public void loadScreen(){
JPanel p1 = new JPanel();
DefaultListModel model = new DefaultListModel<String>();
JList list = new JList<String>(model);
//
JScrollPane scroll = new JScrollPane(list);
list.setPreferredSize(null);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
scroll.setViewportView(list);
//
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
System.out.println("You selected " + list.getSelectedValue());
}
});
p1.add(list);
Main.frame.add(p1);
Main.frame.revalidate();
Main.frame.repaint();
for (int i = 0; i < 100; i++){
model.addElement("test");
}
}
I've tried a bunch of stuff to get the JScrollPane to appear on the JList, but it doesn't want to. My best guess is that the model is screwing things up, but this is a simplified version, and the model needs to be there.
JScrollPane scroll = new JScrollPane(list);
You add the JList to the JScrollPane which is correct.
p1.add(list);
But then you add the JList to the JPanel, which is incorrect. A component can only have a single parent, so theJListis removed from theJScrollPane`.
You need to add the JScrollPane to the JPanel:
p1.add( scroll );
You're adding the list to too many components: to the JScrollPane's viewport -- OK, but also to the p1 JPanel -- not OK. Add it only to the viewport, and then add the JScrollPane to the GUI (p1 if need be).
Also:
There's no need to add the JList to the JScrollPane twice, in the constructor and in the viewport view as you're doing, once is enough.
list.setPreferredSize(null);????
Just add Scroll Pane to the frame rather than the List.
change your line with the below code:
Main.frame.add(scroll);

How can we put value on text field on output screen?

I want to put value in txtf1 at output screen and get it. How can we put value on text field on output screen?
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class demog extends JPanel implements ActionListener{
private TextField textf, txtf1;
public void jhand(){
textf = new TextField();
textf.setSize(40, 40);
textf.setText("20");
textf.setEditable(false);
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
//textf.setHorizontalAlignment(SwingConstants.CENTER);
textf.setLocation(15, 15);
//textf.addActionListener(this);
txtf1 = new TextField();
txtf1.setSize(40, 40);
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
//txtf1.setHorizontalAlignment(SwingConstants.CENTER);
txtf1.setLocation(50, 50);
JFrame frame = new JFrame("demo");
JPanel p = new JPanel();
p.setOpaque(true);
p.setBackground(Color.WHITE);
p.setLayout(null);
frame.setContentPane(p);
frame.setSize(500,500);
frame.setVisible(true);
p.add(textf);
p.add(txtf1);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
System.out.println(text);
}
public static void main(String... args){
demog g = new demog();
g.jhand();
}
}
You have to change some of your code in order to work. You had some problem in your code which I resolved them for you in the following code. See the comments to learn some in swing ;-)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
// Use upper Case in the start of you class names:
public class Demog extends JPanel implements ActionListener {
private JTextField textf, txtf1;
public Demog() {
jhand();
}
public void jhand() {
setLayout(new FlowLayout()); // Always set the layout before you add components
// you can use null layout, but you have to use setBounds() method
// for placing the components. For an advanced layout see the
// tutorials for GridBagLayout and mixing layouts with each other.
textf = new JTextField(); // Do not mix AWT component with
// Swing (J components. See the packages)
//textf.setSize(40, 40); // Use setPreferredSize instead
textf.setPreferredSize(new Dimension(40, 40));
textf.setText("20");
textf.setEditable(false); // Text fields are for getting data from user
// If you need to show something to user
// use JLabel instead.
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
add(textf);
txtf1 = new JTextField();
//txtf1.setSize(40, 40); Use setPreferredSize instead
txtf1.setPreferredSize(new Dimension(40, 40));
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
add(txtf1);
JButton b = new JButton("Click ME!");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
JOptionPane.showMessageDialog(Demog.this, "\"textf\" text is: "+text);
}
public static void main(String[] args) {
JFrame frame = new JFrame("demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Demog p = new Demog();
p.setBackground(Color.WHITE);
frame.setContentPane(p);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Good Luck.

Is the area too small for JPopupMenu?

In the last question I was asking the community why my JPopupMenu did not appear on the screen.
I was unable to come up with a simple , runnable, compilable example.
So, here is what I did for you guys:
Is the area too small to draw a popup?
I want my popup to be like this:
The code of what I did is visible in the first photo.
Code:
/* The old code entered here has been removed */
Complete code can be found here
edit 2
I copied the various JRadioButtonMenuItem and the setupJPopup() into a new file and ran. It works. Why doesn't it work in ScreenRecorder class?
Code
package demo;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class PopupTrial {
public PopupTrial(){
setupJPopup();
JFrame frame = new JFrame();
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
}
frame.getContentPane().add(label);
label.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
frame.setVisible(true);
frame.setSize(300, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new PopupTrial();
}
});
}
public void setupJPopup(){
encodingGroup.add(avi);
encodingGroup.add(quicktime);
popup.add(avi);
popup.add(quicktime);
popup.addSeparator();
recordingAreaGroup.add(entireScreen);
recordingAreaGroup.add(custom);
popup.add(entireScreen);
popup.add(custom);
popup.addSeparator();
cursorGroup.add(selectBlackCursor);
cursorGroup.add(selectWhiteCursor);
cursorGroup.add(selectNoCursor);
selectCursor.add(selectBlackCursor);
selectCursor.add(selectWhiteCursor);
selectCursor.add(selectNoCursor);
popup.add(selectCursor);
popup.pack();
}
JLabel label = new JLabel("Click Me");
ButtonGroup recordingAreaGroup = new ButtonGroup();
ButtonGroup cursorGroup = new ButtonGroup();
ButtonGroup encodingGroup = new ButtonGroup();
JPopupMenu popup = new JPopupMenu();
JRadioButtonMenuItem avi = new JRadioButtonMenuItem("AVI",true);
JRadioButtonMenuItem quicktime = new JRadioButtonMenuItem("QuickTime",false);
JRadioButtonMenuItem entireScreen = new JRadioButtonMenuItem("Entire Screen",true);
JRadioButtonMenuItem custom = new JRadioButtonMenuItem("Custom...",false);
JMenuItem selectCursor = new JMenu("Select a cursor");
JRadioButtonMenuItem selectWhiteCursor = new JRadioButtonMenuItem("White Cursor",true);
JRadioButtonMenuItem selectBlackCursor = new JRadioButtonMenuItem("Black Cursor",false);
JRadioButtonMenuItem selectNoCursor = new JRadioButtonMenuItem("No Cursor",false);
}
No, the size of the JFrame isn't related to why the PopupMenu isn't showing. Here's an example showing something similar to what you want (and using similar methods) working:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupMenu extends Box{
Dimension preferredSize = new Dimension(400,30);
public PopupMenu(){
super(BoxLayout.Y_AXIS);
final JPopupMenu menu = new JPopupMenu("Options");
for(int i = 1; i < 20; i++)
menu.add(new JMenuItem("Option" + i));
JLabel clickMe = new JLabel("ClickMe");
clickMe.setAlignmentX(RIGHT_ALIGNMENT);
clickMe.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
menu.show(e.getComponent(), e.getX(), e.getY());
}});
add(clickMe);
}
public Dimension getPreferredSize(){
return preferredSize;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PopupMenu());
frame.validate();
frame.pack();
frame.setVisible(true);
}
}

Using TextArea in TabbedPane

i have added a JTabbedPane with a JPanel in each tab. and a JText area within each JPanel.
the tabs can be dynamically created in the same template.
There is also a menu bar with a menu. it has options to replace an occurance of a string (eg replace "<" with "<") it worked perfectly when i just used a JPanel and textArea.
Now that i hav added the tabbedPane,... i dont know how to replace the content of the active tab alone,..
i have tried getting the selected component(getSelectedComponent() method and getComponentAt() method) and replacing the text,.. i didnt work
can some one help me
getSelectedIndex() and getSelectedComponent() should work. Check out How to Use Tabbed Panes tutorial, it has good examples.
EDIT: demo of getSelectedComponent and AbstractAction
import javax.swing.AbstractAction;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
public class TabbedPaneDemo {
static class TextDemoPanel extends JPanel{
private JTextArea textArea;
public TextDemoPanel(String text){
textArea = new JTextArea(5, 20);
textArea.setText(text);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane);
}
public JTextArea getTextArea() {
return textArea;
}
}
static class SetTextAction extends AbstractAction {
private JTabbedPane tabbedPane;
public SetTextAction(JTabbedPane tabbedPane){
super("Set text");
this.tabbedPane = tabbedPane;
}
#Override
public void actionPerformed(ActionEvent e) {
String value = JOptionPane.showInputDialog(tabbedPane, "Text", "New text");
if (value != null){
TextDemoPanel panel = (TextDemoPanel)tabbedPane.getSelectedComponent();
if (panel != null)
panel.getTextArea().setText(value);
}
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TabbedPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new TextDemoPanel("Tab 1 text"));
tabbedPane.addTab("Tab 2", new TextDemoPanel("Tab 2 text"));
tabbedPane.addTab("Tab 3", new TextDemoPanel("Tab 3 text"));
frame.add(tabbedPane, BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
JMenuItem item = new JMenuItem(new SetTextAction(tabbedPane));
menu.add(item);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Categories