JPopupMenu.show shows popupmenu with strange behaviour (sometimes appears as grey box) - java

I have a JFrame containing a JTabbedPane containing a JPanel in a Tab.
In this JPanel, I want a JPopupMenu to show at Mouse Position when clicking the right mouse button.
To do this, I use the show(invoker, x, y) method.
My Problem: The JPopupMenu has a very strange behaviour; sometimes it displays without containing everything (just a grey box) and sometimes it displays in the top left corner of the Panel, behaving completely as expected.
Code:
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
class Testframe extends JFrame {
public static JFrame frame;
private static final long serialVersionUID = 1L;
public Testframe(String string) {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle(string);
setSize(200,200);
setVisible(true);
}
public static void main(String[] args) {
frame = new Testframe("Title");
JTabbedPane tabpane = new JTabbedPane(JTabbedPane.TOP);
tabpane.addTab("title", new TestPanel());
frame.add(tabpane);
tabpane.setVisible(true);
}
}
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
public class TestPanel extends JPanel implements MouseListener {
private static final long serialVersionUID = 1L;
JPopupMenu activeDropdown;
TestPanel() {
setBackground(Color.GREEN);
setVisible(true);
addMouseListener(this);
}
private void dropdown(MouseEvent e) {
activeDropdown = new JPopupMenu();
JMenuItem item = new JMenuItem("Eintrag 0");
activeDropdown.add(item);
activeDropdown.show(Testframe.frame, e.getX(), e.getY());
this.add(activeDropdown);
}
#Override
public void mouseClicked(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)) {
if (activeDropdown != null)
this.remove(activeDropdown);
dropdown(e);
}
}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
}
If I try to put the JTabbedPane into a separate Class, the JPopupMenu appears anywhere (seems to be a fixed position) on the screen, completely independent from the window position.

Change your dropdown method as below. That should work as expected.
private void dropdown(MouseEvent e) {
activeDropdown = new JPopupMenu();
JMenuItem item = new JMenuItem("Eintrag 0");
activeDropdown.add(item);
this.add(activeDropdown);
activeDropdown.show(this, e.getX(), e.getY());
}
However, I don't understand why you are removing the existing JPopMenu and adding a new one on every right-mouse click.

You can simply use JComponent.setComponentPopupMenu to handle righ-click popup-menus. This is much simpler and will handle all the wiring code for you.
Small example with your code:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class TestPanel extends JPanel {
private static final long serialVersionUID = 1L;
JPopupMenu activeDropdown;
TestPanel() {
setBackground(Color.GREEN);
activeDropdown = new JPopupMenu();
JMenuItem item = new JMenuItem("Eintrag 0");
activeDropdown.add(item);
setComponentPopupMenu(activeDropdown);
}
protected void initUI() {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabpane = new JTabbedPane(JTabbedPane.TOP);
tabpane.addTab("title", this);
frame.add(tabpane);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestPanel().initUI();
}
});
}
}
NB: Avoid using static variables!

Related

how to set semi-transparent jframe when "submit" button is clicked?

loadingLab=new JLabel("The name is being saved..");
loadPanel.add(loadingLab);
submitBttn=new JButton("Submit");
submitBttn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Submit Button Clicked!!");
try {
//something is wrong in here as it throws an exception
//what is wrong?
frame.setUndecorated(false);
frame.setOpacity(0.55f);
//when above both lines are commented, the code works fine
//but doesnt have transparency
frame.add(loadPanel,BorderLayout.SOUTH);
frame.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
I am trying to display transparent JFrame when "submit" button is clicked which displays panel with a JLabel...
I have tried using setOpacity(0.55f), but it throws exception.. what am i doing wrong?
Unfortunately I think there's no way to keep the system window decoration, you will probably have to go with the default one. Since I'm not 100% sure if you want to toggle the opacity of the whole frame or just the frame's background, I've included both functions in my example. (mKorbels answer help you more if you don't want to have a decoration)
Code:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class TransparentExample extends JFrame {
public TransparentExample() {
super("TransparentExample");
Color defaultBackground = getBackground();
float defaultOpacity = getOpacity();
JToggleButton button1 = new JToggleButton("Toggle background transparency");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button1.isSelected()) {
setBackground(new Color(defaultBackground.getRed(), defaultBackground.getGreen(),
defaultBackground.getBlue(), 150));
} else {
setBackground(defaultBackground);
}
}
});
JToggleButton button2 = new JToggleButton("Toggle opacity of whole frame");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
if (button2.isSelected()) {
setOpacity(0.55f);
} else {
setOpacity(defaultOpacity);
}
setVisible(true);
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(button1);
getContentPane().add(button2);
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
TransparentExample frame = new TransparentExample();
frame.setVisible(true);
}
});
}
}
Picture of frame with no togglebutton selected:
Picture of frame with the first togglebutton selected:
Picture of frame with the second togglebutton selected:
#Programmer007 wrote - the exception is "
java.awt.IllegalComponentStateException: The frame is displayable."
please where I can't see any, for more info about the possible exceptions to read,
as mentioned no idea, everything is about your effort, transformed to the SSCCE / MCVE, short, runnable, compilable
.
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class GenericForm extends JDialog {
private static final long serialVersionUID = 1L;
private Timer timer;
private JDialog dialog = new JDialog();
private int count = 0;
public GenericForm() {
dialog.setSize(400, 300);
dialog.setUndecorated(true);
dialog.setOpacity(0.5f);
dialog.setName("Toggling with opacity");
dialog.getContentPane().setBackground(Color.RED);
dialog.setLocation(150, 150);
dialog.setVisible(true);
timer = new javax.swing.Timer(1500, updateCol());
timer.setRepeats(true);
timer.start();
}
private Action updateCol() {
return new AbstractAction("Hello World") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
boolean bol = dialog.getOpacity() < 0.55f;
count += 1;
if (count < 10) {
if (bol) {
dialog.setOpacity(1.0f);
dialog.getContentPane().setBackground(Color.WHITE);
} else {
dialog.setOpacity(0.5f);
dialog.getContentPane().setBackground(Color.RED);
}
} else {
System.exit(0);
}
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GenericForm();
}
});
}
}

Close a JtabbedPane with JInternalFrame Inside

How can I close a JTabbedPane with an JInternalFrame included when I click a button inside this form?
My project has 3 JForms, 1 TabbedPane, 1 JInternalFrame and 1 Main window (to register data). To create my JTabbedPanes I use the method addTab() and from that form I have the button to close which calls another window (Main registry), I used the dispose() and setVisible(false) methods but they don't do anything.
An example (there are 3 clases -Administrador, -MenuPrincipal, -ventanaRegistro) :
First Class a JFrame and on top a JTabbedPane (this is where I create my tabs)
public class MenuPrincipal extends javax.swing.JFrame
{
Administrador ventanaAdministrador = new Administrador();
void showTabs()
{
JTabbedPane.addTab("Administrador", ventanaAdministrador);
}
public MenuPrincipal()
{
initComponents();
showTabs();
}
}
Second Class a JInternalFrame with a single button
public class Administrador extends javax.swing.JInternalFrame
{
void showAdminWindow()
{
ventanaRegistro ventanaRegistro = new ventanaRegistro();
ventanaRegistro.setVisible(true);
}
void closeThisWindow()
{
this.dispose();
}
public Administrador()
{
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
showAdminWindow();
closeThisWindow();
}
}
Third Class a simple JFrame. This is just code to register data.
The real problem is that my method closeThisWindow() doesn't close the second Jtabbed window, and I want to make it that when I click a button (which is on the JTabbedPane) make the third class visible and the Second Class invisible/Close it.
See if the following code does what you expect. If it doesn't please elaborate so I can improve my answer.
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
public class MenuPrincipal extends javax.swing.JPanel {
Administrador ventanaAdministrador = new Administrador();
public MenuPrincipal()
{
setPreferredSize(new Dimension(290, 200));
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
ventanaAdministrador.setPreferredSize(new Dimension(350, 100));
tabbedPane.addTab("Admin", ventanaAdministrador);
tabbedPane.addTab("2nd Tab", new JPanel());
add(tabbedPane);
}
/**
* #param args
*/
public static void main(String[] args) {
JFrame testFrame = new JFrame("Main Test Window");
testFrame.setDefaultCloseOperation(WindowConstants.
DISPOSE_ON_CLOSE);
testFrame.setPreferredSize(new Dimension(450, 350));
MenuPrincipal menuP = new MenuPrincipal();
testFrame.getContentPane().add(menuP);
testFrame.pack();
testFrame.setVisible(true);
}
}
And:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Administrador extends javax.swing.JInternalFrame {
void showAdminWindow()
{
JFrame ventanaRegistro = new JFrame("Admin Window");
ventanaRegistro.
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
ventanaRegistro.setPreferredSize(new Dimension(350, 200));
ventanaRegistro.pack();
ventanaRegistro.setVisible(true);
}
void closeThisWindow()
{
Window window = SwingUtilities.getWindowAncestor(this);
window.dispose();
}
public Administrador()
{
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH);
JButton closeWindowBttn = new JButton("Close Window and open a new one");
closeWindowBttn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
closeWindowActionPerformed();
}
});
panel.add(closeWindowBttn);
}
private void closeWindowActionPerformed() {
showAdminWindow();
closeThisWindow();
}
}

How could I make the colour BLACK be transparent on top of the uploaded image?

Right now all I have is created the black background and uploaded my image I wanted. I want to make it so the image is behind a transparent background. I initially had this all in separate class files but put them all in one main class
package Flashlight;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Flashlight3 extends JFrame {
public class FlashLabelChange extends JPanel {
Flashlight.FlashDisp flashDisp;
public FlashLabelChange(Flashlight.FlashDisp _flashDisp) {
flashDisp = _flashDisp;
JButton btn1 = new JButton("Start");
add(btn1);
class Button implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Start")) {
flashDisp.UpdateLabel("Start");
}
}
}
ActionListener button = new Button();
btn1.addActionListener(button);
}
}
public class FlashDisp extends JPanel {
private JLabel lblName;
private String sLabel;
private JLabel lblImage;
public FlashDisp() {
lblImage = new JLabel();
add(lblImage);
lblName = new JLabel("Start?");
add(lblName); //add it to the Frame
}
void UpdateLabel(String _sNew) {
sLabel = _sNew;
lblName.setText(sLabel);
}
void UpdateBackground(String _sNew) {
sLabel = _sNew;
if (sLabel == ("Black")) {
setBackground(Color.black);
lblImage.setIcon(new ImageIcon("Hallway.png"));
}
}
}
public class FlashColour extends JPanel {
FlashDisp flashDisp;
public FlashColour(FlashDisp _flashDisp) {
flashDisp = _flashDisp;
setLayout(new GridLayout(3, 1));
JButton btnDark = new JButton("Dark");
add(btnDark);
class ColourChangeListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Dark")) {
flashDisp.UpdateBackground("Black");
}
}
}
ActionListener colourChangeListener = new ColourChangeListener();
btnDark.addActionListener(colourChangeListener);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
FlashMain flashMain = new FlashMain();
frame.setSize(400, 400);
frame.setTitle("FLAAAASH LIGHT");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(flashMain);
frame.setVisible(true);
}
}
I think that you need to use the opaque method.
Have a look here
setOpaque(true/false); Java for using opaque.
Hope that helps.

Why can this code note be run as a JFrame?

I am trying to make an applet run as a JFrame. The code I have below is simple but should work. It will run as an JApplet but when I go to RUN AS --> nothing appears.
import java.awt.*;
import java.applet.Applet;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LifeCycle extends Applet
{
private static final long serialVersionUID = 1L;
String output = "test";
String event;
public void init()
{
gui(); //I am not certain if this needs to be there.
event = "\nInitializing...";
printOutput();
}
public void start()
{
event = "\nStarting...";
printOutput();
}
public void stop()
{
event = "\nStopping...";
printOutput();
}
public void destroy()
{
event = "\nDestroying...";
printOutput();
}
private void printOutput()
{
System.out.println(event);
output += event;
repaint();
}
private void gui() {
JFrame f = new JFrame("Not resizable");
JPanel d = new JPanel();
// LifeCycle a = new LifeCycle();
// a.init();//not working
d.setLayout(new BorderLayout());
d.add(new JButton("a"));
d.add(new JButton("b"));
d.setBackground(Color.RED);
//f.add(new LifeCycle());
f.add(d);
f.setSize(545,340);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setTitle("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//a.destroy();
}
public void paint(Graphics g)
{
System.out.println("Graphics Paint Method!");
g.drawString(output, 100, 100);
}
public static void main(String[] args) {
LifeCycle l = new LifeCycle();
l.gui();
}
}
I would like to see the code that should be changed, but I cannot seem to find why this will not work. I have added to buttons to the panel to be displayed.
Don't mix AWT (Applet) with Swing components. Stick with just Swing.
Gear your class towards creating JPanels. Then you can place it in a JApplet if you want an applet or a JFrame if you want a JFrame.
Read up on use of BorderLayout -- you're adding multiple components to the default BorderLayout.CENTER position, and only one component, the last one added, will show.
For example ...
LifeCycle2.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
class LifeCycle2 {
private static final int GAP = 5;
private static final int PREF_W = 545;
private static final int PREF_H = 340;
private JPanel mainPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return LifeCycle2.this.getPreferredSize();
}
};
public LifeCycle2() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
buttonPanel.add(new JButton("A"));
buttonPanel.add(new JButton("B"));
buttonPanel.setOpaque(false);
JPanel flowLayoutPanel = new JPanel();
flowLayoutPanel.setOpaque(false);
flowLayoutPanel.add(buttonPanel);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.setBackground(Color.red);
mainPanel.add(flowLayoutPanel, BorderLayout.NORTH);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public JComponent getMainPanel() {
return mainPanel;
}
}
Show as a JFrame,
LifeCycleFrame.java
import javax.swing.*;
public class LifeCycleFrame {
private static void createAndShowGui() {
LifeCycle2 lifeCycle2 = new LifeCycle2();
JFrame frame = new JFrame("LifeCycleTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(lifeCycle2.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Show as an applet,
LifeCycleApplet.java
import java.lang.reflect.InvocationTargetException;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
public class LifeCycleApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
LifeCycle2 lifeCycle2 = new LifeCycle2();
getContentPane().add(lifeCycle2.getMainPanel());
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}
Add f.setVisible(true); to the end of the gui() method. Without this call your frame won't be shown.
Please read the "How to Make Frames" Tutorial

Java - Change JLabel

I have a class of buttons called Keys.java which returns a panel of buttons to the class called Control.java. I have a JLabel in Control.java, but what I want to do is change a JLabel when a button is pressed. How would you go about doing this?
I have tried setting a string in Keys.java which changes based on the button and then setting the JLabel's text equal to the string but it doesn't seem to work.
Any thoughts on how to achieve this?
It may be that you are updating the wrong string or setting the corresponding label's text incorrectly. Both are required. In the example below (using your names), the two updates are tightly coupled in the button's actionPerformed(). A more loosely coupled approach is shown here.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/questions/9053824 */
public class JavaGUI extends JPanel {
private Control control = new Control();
private Keys keys = new Keys("Original starting value.");
public JavaGUI() {
this.setLayout(new GridLayout(0, 1));
this.add(keys);
this.add(control);
}
private class Control extends JPanel {
public Control() {
this.add(new JButton(new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Command: " + e.getActionCommand());
keys.string = String.valueOf(System.nanoTime());
keys.label.setText(keys.string);
}
}));
}
}
private class Keys extends JPanel {
private String string;
private JLabel label = new JLabel();
public Keys(String s) {
this.string = s;
label.setText(s);
this.add(label);
}
}
private void display() {
JFrame f = new JFrame("JavaGUI");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new JavaGUI().display();
}
});
}
}

Categories