Java GUI panel unable to refresh? - java

I have 3 panels in the frame, panel, panel1, panel2. When I click on the button it doesn't remove the panel from the frame.
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
// some stuffs here.
++current;
frame.remove(panel1);
frame.revalidate();
frame.repaint();
}
}
edit: i used this too but it doesn't work as well
frame.remove(panel1);
frame.getContentPane().invalidate();
frame.getContentPane().validate();
frame.getContentPane().repaint();

Related

Focus component after changing content pane of JFrame

I'm changing my JFrame's content pane and simply want to focus a JTextField in the new panel. So I'm doing this:
JPanel pNew = new JPanel();
frame.setContentPane(pNew);
frame.revalidate();
frame.repaint();
public JPanel() {
...
tf.requestFocusInWindow();
}
When I use setVisible(false) and setVisible(true) instead of revalidating and repainting my frame, I get my wished effect, but that's not the way I want to do it.
What else happens in setVisible() but revalidating and repainting?
A CardLayout is typically used to swap panels.
However, even the default implementation of CardLayout does not set focus on the panel when it is swapped. However you can check out Card Layout Focus which will allow you to request focus on the panel when it is switched.
The requestFocusInWindow() method only works on a component that is displayed in a visible frame. So you can't invoke the method in the constructor of the class.
You could use the RequestFocsListener found in Dialog Focus. It will wait until the panel is added to a visible GUI before generating the event.
I got it to work simply by putting the requestFocusInWindow() call in the button's action listener. As camickr mentioned the call needs to be made after the constructor. Here's an example program showing how I got it to work. Hope it helps!
public class PanelRevalidate {
public JFrame frame;
public MyPanel panel1, panel2;
public PanelRevalidate() {
frame = new JFrame();
panel1 = new MyPanel(1);
panel2 = new MyPanel(2);
frame.setContentPane(panel1);
panel1.getSwap().addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
frame.setContentPane(panel2);
frame.revalidate();
panel2.getTextField().requestFocusInWindow();
}
});
panel2.getSwap().addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
frame.setContentPane(panel1);
frame.revalidate();
panel1.getTextField().requestFocusInWindow();
}
});
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new PanelRevalidate();
}
});
}
}
And the MyPanel class:
public class MyPanel extends JPanel {
public JTextField tf;
public JButton swap;
public JLabel panel_label;
public MyPanel(int n) {
tf = new JTextField(25);
swap = new JButton("Swap");
panel_label = new JLabel("panel " + n);
add(tf);
add(swap);
add(panel_label);
}
public JButton getSwap() {
return swap;
}
public JTextField getTextField() {
return tf;
}
}

Adding JLabels to JFrame using ActionListener and for loop

I want to add a JLabels to JFrame with for loop and ActionListener. The idea is: I have a button, and when i click the button, program is adding labels, but in my code when i click button nothing happens, without button and ActionListener, labels are adding properly. Code:
public class Test extends JFrame implements ActionListener{
JLabel[] labels;
TextField dane;
JButton button;
public Test(){
super();
dane=new TextField();
button=new JButton("Oblicz");
setLayout(new GridLayout(33,0));
add(dane);
add(button);
setVisible(true);
pack();
}
#Override
public void actionPerformed(ActionEvent v) {
showGUI();
revalidate();
repaint();
}
private JLabel[] createLabels(){
JLabel[] labels=new JLabel[20];
for (int i=0;i<20;i++){
labels[i]=new JLabel("message"+i);
}
return labels;
}
private void showGUI(){
labels=createLabels();
for (int i=0;i<labels.length;i++){
this.add(labels[i]);
}
}
public static void main(String[] args){
new Test();
}
}
Ok, i changed my code as you sugested, but it still doesn't work. What's wrong here ? I have no idea( I'm very beginner so every suggestions would be nice )
...but in my code when i click button nothing happens
I don't see where you've attached a listener to your button. Try:
button.addActionListener(this);
When adding components to a visible GUI the basic code is:
panel.add(...);
panel.revalidate(); // to invoke the layout managers
panel.repaint(); // to paint the new components
So after the loop is finished adding the labels to the frame you need to revalidate() the frame.

JDialog not centered over parent JFrame

I am trying to get my JDialog to popup in the center of my JFrame on a button click. I have JOptionPanel that popup correctly over the parent JFrame, but the JDialog is popping up relative to the JFrame but not in the center.
The buttons are actually JMenuItem in my code, but I wrote them here as JButton to make things easier and straight forward.
Here's my code:
call from my Parent JFrame:
JButton about = new JButton("About");
about.addActionListener(new ActionListener() { //this one IS NOT in the center of MyJFrame
public void actionPerformed(ActionEvent e) {
new AboutDialog(MyJFrame.this);
}
});
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() { //this one IS in the center of MyJFrame
public void actionPerformed(ActionEvent e) {
if(JOptionPane.showConfirmDialog(MyJFrame.this, "Are you sure you want to exit ?","",JOptionPane.YES_NO_OPTION) == 0)
System.exit(0);
}
});
AboutDialog Class
public class AboutDialog extends JDialog{
public AboutDialog(JFrame parent) {
setLocationRelativeTo(parent);
setLayout(new BorderLayout());
...
Thank you
setLocationRelativeTo(parent);
The above code needs to be executed AFTER you have added all the components to the dialog and packed the dialog and before you make the dialog visible.
In your current code the size of the dialog is (0, 0) so it can't be centered properly.

"Linking" JComponents in Java?

I have a few buttons and a few panels. Each button corresponds to a panel. I want to add an ActionListener to each button so that when the buttons are clicked, the visibility of the panels are toggled. However, inside the ActionPerformed method, I cannot get the JPanel. Here's basically what I have:
JFrame frame1=new JFrame();
JPanel panel=new JPanel();
frame1.add(panel);
JFrame frame2=new JFrame();
JButton btn=new JButton(panel.getName());
btn.addActionListener(new ActionListener(){
public void ActionPerformed(ActionEvent e){
(somehow get panel).setVisible(false);
}
});
frame2.add(btn);
It might be better to create a class that implements ActionListener. You could then pass in a reference to the parent JPanel and then refer to that in the actionPerformed method.
But if you really wanted to, you could use this convoluted one-liner.
((JComponent)e.getSource()).getParent().setVisible(false);
An AbstractAction could work well:
class ButtonAction extends AbstractAction {
private JPanel panel;
public ButtonAction(JPanel panel) {
super(panel.getName());
this.panel = panel;
}
public void actionPerformed(ActionEvent e) {
panel.setVisible(false);
}
}
elsewhere:
someContainer.add(new JButton(new ButtonAction(panel)));
It is not very good solution, but you can link swing components in following way
button.putClientProperty("panel", panel1);
//and somewhere in code
((JPanel)button.getClientProperty("panel")).setVisible(false);
This should work:
e.getSource().getParent().setVisible(false);

Enable only mouse event over a jbutton - Disable keyboard event for jbutton

I have a problem.
I created a game. When I open it I must press ENTER to start the game (just enter).
Now I upgraded the game with one button named "EXIT GAME". I don't know why my enter key doesn't work anymore because of this button. If i remove it then Ican press enter again and play the game.
I must set only click pressed event to that button or something like this? Please help me.
public class LeftPanel extends JPanel implements ActionListener {
JButton ExitGame;
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
add(new JButton("Exit Game"));
{
ExitGame.addActionListener(this);
}
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
Problem 1 - The JButton is the only focusable component within your UI. Therefore, when you start you program, it gains default focucs. While it has default focus. It will consume the Enter key strokes.
Problem 2 - JPanel is not focusable, meaning it can never receive key board focus. From your description, I would assume you are using a KeyListener, which leads to
Problem 3 - Using KeyListener...KeyListener will only respond to key events when the component it is registered to is focusable and has focus. You can over come this by using Key Bindings.
...Solutions...
Use JLabel instead of JButton. This will require you to register a MouseListener to the label in order to recieve notification of the mouse clicks, but it won't respond to key events...
Better still, add a "Start" button as well...
You can try:
public class LeftPanel extends JPanel implements ActionListener {
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
JButton ExitGame = new JButton("Exit Game");
ExitGame.addActionListener(this);
ExitGame.setActionCommand("Exit");
add(ExitGame );
}
public void actionPerformed(ActionEvent e) {
if("Exit".equals(e.getActionCommand())
System.exit(0);
}
}
This line looks like a syntax error:
add(new JButton("Exit Game"));
{
ExitGame.addActionListener(this);
}
I think it should be something like this:
ExitGame= new JButton("Exit");
this.add(ExitGame);
ExitGame.addActionListener(this);
I haven't tested this, but I think with some tweaking you should be able to get it to do what you want it to. I hope that works!
-Frank
public void actionPerformed(ActionEvent e) {
if("Exit".equals(e.getActionCommand())
System.exit(0);
}
As ActionlListener can be triggered by both Mouse and Keyboard, but now user only want to response mouse event, so change the action listener to mouselistener. Tested and passed.
public class LeftPanel extends JPanel implements ActionListener {
JButton ExitGame;
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
ExitGame= new JButton("Exit Game")
add(ExitGame);
ExitGame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
}
}

Categories

Resources