Grab focus to a JPanel in a JLayeredPane - java

I have a JLayeredPane with 2 layers
the first layer is a JPanel Wrapping an Image.
the second layer is another object which extends JPanel called ResizableRectangle and implements KeyListener.
I've overrode the KeyPressed method but it doesn't receive the keyPressed event and the method doesn't get invoked.
I've set the setFocusEnable(true) and used grabFocus(), requestFocus() and requestFocusInWindows() but all of them return false.
I figured out when I press tab after the the JFrame loads , the Focus goes to the panel that I want , and the listener gets the events.
I've added a KeyListener to the JLayeredPane and it works fine but the problem is that i want to add listener to the panel not the layeredPane.

I hope that you put Image or ImageIcon to the JLabel then add to the JLabel MouseListener
then just to call
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
myPanel.grabFocus();
myPanel.requestFocus();//or requestFocusInWindows();
}
});

Related

How i can access method from jframe to jpanel?

In my btcFrame class I have the method
private void closeButtonMouseClicked(MouseEvent evt){
this.dispose();
}
In my BtcTitleBarPanel I have in button for that I tend to close the frame. In the constructor I am adding my listener to closeButton like below.
closeButton.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent evt){
closeButtonMouseClicked(evt);
}
});
Problem is I cannot reach closeButtonMouseClicked method within the panel. How should I be doing to solve this?
Images in case.
Methods from jframe
Methods in jpanel
I would add a getter within the Panel for the closeButton. After initializing the Panel in the frame I would add the listener to button within the Frame. Like, btcPanel.getCloseButton().addActionListener(new ...); and within this action listener you could close the frame, like btcFrame.this.dispose()
Though I am not sure if that is a good practise, I almost always create new classes for listening events, but in this case of yours maybe helpful.
PS(Out of topic): You should see how to name classes and methods, your
naming style is wrong.(i.e classes starts with Capital etc.)

NetBeans & Swing - dynamically add JPanel to JDialog

I am designing an application in NetBeans, as illustrated in the screenshot below.
When the user clicks on a JButton on a JFrame, a JDialog pops-up asking the user to enter a numeric value using a numeric keypad. I would like the JDialog to dynamically add 2 JPanels. JPanel 1 will contain a textbox for input. JPanel 2 will contain a numeric keypad. I designed them this way so that I could reuse the numeric keypad whenever I need it. The problem I am facing is displaying dynamically these 2 JPanels on the JDialog that pops-up. JDialog pops-up empty. Please take a look at my code below. Thank you all, I appreciate your help
This is the sample code of JDialog:
public class MyDialog extends javax.swing.JDialog {
public MyDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {//Add JPanel 2 (Numeric Keypad) to JDialog
Container contentPane = getContentPane();
NumericKeypadPanel nkp = new NumericKeypadPanel();
nkp.setLayout(new java.awt.BorderLayout());
contentPane.removeAll();
contentPane.add(nkp);
contentPane.validate();
contentPane.repaint();
}
});
}
This is the sample code for JPanel 2 (Numeric Keypad):
public class NumericKeypadPanel extends javax.swing.JPanel {
/** Creates new form NumericKeypadPanel */
public NumericKeypadPanel() {
initComponents();//Draws 10 number buttons
}
}
basicall there are two ways
1) add a new JComponent by holding JDialog size (in pixels) on the screen, all JCompoenets
or part of them could be shrinked
2) resize JDialog by calling pack(), then JDialog will be resized
both my a.m. rulles works by using Standard LayoutManagers (excepting AbsoluteLayout)
What is in the initComponents() function of the NumericKeypadPanel? If it's not actually creating components, you're not going to see anything in the dialog. I added a single line to the NumericKeypadPanel's constructor to change the background color of this panel, and indeed, it shows up in the dialog as a green panel.
public NumericKeypadPanel() {
//initComponents();//Draws 10 number buttons
setBackground(Color.green);
}

add components to a panel in Java

I'm creating an applet which consists of a class which extends JApplet, with a menubar and a class which extends a JPanel.(So there is a menubar and a JPanel shown in the applet).
In this class I add and remove some textfields to the JPanel. This all works fine. Here's where it gets tricky: it only works the first time. When I add some new textfields to the JPanel, they are added and visible in the JPanel, but the menubar in the JFrame stops working.
Since the code is too extensive I'll only post parts of it.
Here's the code where I add the JPanel to the JApplet:
public class Simulator extends JApplet implements ItemListener, ActionListener {
Container pane = getContentPane();
canvas = new DrawCanvas();
pane.add(canvas, BorderLayout.LINE_END);
}
Here's the code of the JPanel:
class DrawCanvas extends JPanel {
public void paintComponent(Graphics g) {
if(textfield != null)
remove(textfield);
textfield = new JTextField();
this.add(textfield);
}
}
This works the first time(when nothing is removed), but the second time the menubar stops working.
When I leave out the this.add(textfield); line, the menubar keeps working.
I once had similar problems with popup menus beeing painted behind other components.
Try calling static JPopupMenu.setDefaultLightWeightPopupEnabled(false); or the setLightWeightPopupEnabled on your specific submenu. This will make (all) popup menus (i.e. submenus) to heavy weight components that have a native peer.
I believe you are running into issues with threading. Adding and removing JComponents during painting might mess up the EDT (which is calling the paint method in the first place).

JMenuBar dropping down to a "custom" JPanel and "erased"

The JMenuItems of JMenuBar drops down to a JPanel added to the JFrame, but the JPanel erases the JMenuItems.
Do I supposed to pause the re-drawing of the JPanel?
I'm using getGraphics() on the JPanel for drawing an image, this method is called from a thread with (for example) 200 ms delay.
edit:
It's a (very simple) game inside the JPanel.
(I've added a field paused to the JPanel and i've edited the paint method so it repaints the JPanel only if paused is false, however I don't know if this "solution" is good. (It's set to true when the user clicks on the menu and set to false when selects or cancels it.)
You should always be repainting the JPanel from the Event Dispatch Thread, not an arbitrary thread. If you want to do this in order to animate the panel (e.g. with the 200ms delay you mention) then consider using javax.swing.Timer, which periodically fires an ActionEvent on the Event Dispatch Thread.
Example
public class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Add additional graphics operations here.
}
}
final JPanel panel = new MyPanel();
int delay = 200; // Milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.repaint();
}
};
new Timer(delay, taskPerformer).start();
I'm using getGraphics() on the JPanel
for drawing an image
Never use the getGraphics() method like that. You have no control over when the component should be repainted. Custom painting should be done by overriding the paintComponent() method of the panel. When you use the Timer you just use panel.repaint() and the Swing repaint manager should look after the details of what needs to be painted.
Have a look at javax.swing.Timer documentation
https://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/Timer.html
It has code right at the top to fire an event on fixed interval.

Placing drawing on JPanel

My program have 3 classes. 1) main, 2) frame, 3) drawingBoard. The logic of my program is that, a new drawing will be displayed every times user click on New pattern button (and this working fine).
1st class - main method
public class mainPage {
public static void main(String[]args){
JFrame appFrame = new Frame();
appFrame.setVisible(true);
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);*/
}
}
2nd class - describe the layout (I use Grid Bag Layout)
public class Frame extends JFrame implements ActionListener {
public Frame (){
GridBagLayout m = new GridBagLayout();
Container c = (Container)getContentPane();
c.setLayout (m);
GridBagConstraints con;
JButton bPattern = new JButton("New Pattern");
....
bPattern.addActionListener(this);
JPanel pDraw = new JPanel();
.....
pDraw.add(new drawingBoard()); //drawing will be placed in this panel
}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
3rd class - run drawing functions e.g. paintComponent (), etc.
public class drawingBoard extends JPanel {
public drawingBoard(){}
public void paintComponent(Graphic g){}
....
}
The problem is that, when I look on the console, it seems that even though the user did not click on the button, the program call the class 'drawingBoard' and repaint. The paint component is in the 3rd class (drawingBoard). Although this seem not to give me a problem (e.g. no drawing displayed on the panel unless the user click the button), I am just curious how this happened. is that because I wrote this code at FRAME class (). My intention to write this code is to make sure the drawing should be place in this specific panel (I have 3 panels) but not to call the 3rd class unless the button has been clicked.
JPanel pDraw = new JPanel();
pDraw.add(new drawingBoard()); //place drawing here
The repaint method (and subsequently, the paintComponent method) is not only called by the JFrame but also by Swing itself as well, when there needs to be a repaint of the contents of the JPanel.
The Painting in AWT and Swing article is a good place to start to get information on how painting works.
In this case, the repaint method is being called by events which the article calls System-triggered Painting:
In a system-triggered painting
operation, the system requests a
component to render its contents,
usually for one of the following
reasons:
The component is first made visible on the screen.
The component is resized.
The component has damage that needs to be repaired. (For example,
something that previously obscured the
component has moved, and a previously
obscured portion of the component has
become exposed).

Categories