Java GUI: How to Set Focus on JButton in JPanel on JFrame? - java

I've experimented and searched and I can't seem to figure out what I thought would be something simple, which is having my START button have focus when my little GUI app launches I.e., so all the user has to do is press their Enter/Return key, which will have the same effect as if they had clicked the START button with their mouse. Here is my code. Thanks for your help :)
private void initialize() {
// Launch the frame:
frame = new JFrame();
frame.setTitle("Welcome!");
frame.setSize(520, 480);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the image:
ImageIcon heroShotImage = new ImageIcon("heroShot.jpg");
JPanel heroShotPanel = new JPanel();
JLabel heroShot = new JLabel(heroShotImage);
heroShotPanel.add(heroShot);
// Create a panel to hold the "Start" button:
JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
// Create the "Start" button, which launches business logic and dialogs:
JButton start = new JButton("Start");
start.setToolTipText("Click to use library");
start.setFocusable(true); // How do I get focus on button on App launch?
start.requestFocus(true); // Tried a few things and can't get it to work.
// Listen for user actions and do some basic validation:
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// THE APP's LOGIC GOES HERE...
}
// Finish setting up the GUI and its components, listeners, and actions:
submitPanel.add(start);
frame.getContentPane().add(heroShotPanel, BorderLayout.NORTH);
frame.getContentPane().add(submitPanel, BorderLayout.SOUTH);
}

Try out this code.. All I have done is moving the requestFocus() method at the end.
Basically these are the two things you have to do for it to respond while pressing enter key and for it to be focused by default.
frame.getRootPane().setDefaultButton(start);
start.requestFocus();
package sof;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
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 TestFrame {
public static void main(String[] args) {
// Launch the frame:
JFrame frame = new JFrame();
frame.setTitle("Welcome!");
frame.setSize(520, 480);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the image:
ImageIcon heroShotImage = new ImageIcon("heroShot.jpg");
JPanel heroShotPanel = new JPanel();
JLabel heroShot = new JLabel(heroShotImage);
heroShotPanel.add(heroShot);
// Create a panel to hold the "Start" button:
JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton start = new JButton("Start");
start.setToolTipText("Click to use library");
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("I AM PRESSED");
}
});
submitPanel.add(start);
frame.getContentPane().add(heroShotPanel, BorderLayout.NORTH);
frame.getContentPane().add(submitPanel, BorderLayout.SOUTH);
frame.setVisible(true);
frame.getRootPane().setDefaultButton(start);
start.requestFocus();
}
}

If I'm understanding you then you want to do a click event of Start Button when user hits Enter key. If this is the case then you can do it as follows:
jFrame.getRootPane().setDefaultButton(start);// 'start' will be your start button
And if you just want to get focus on start Button then shift your requestFocus() method at the end (after you make your frame visible) and no need to pass true in it. Also it is better to use requestFocusInWindow() then requestFocus() as stated in java doc.

move your focus line to the end of the method
and change it to
start.requestFocus(); // without params

If you want your start button to get the focus then do this at the end
//This button will have the initial focus.
start.requestFocusInWindow();

not easy job because Focus/Focus_SubSystem came from Native OS and is pretty asynchronous,
1) inside one Containers works by wraping that into invokeLater(),
2) manage Focus betweens two or more Top-Level Containers, by #camickr

Related

How to make a JButton that will create other buttons in java Swing?

I am creating a user system to hold multiple details of multiple users, so I would like to create a button that would be able to create another button. When the second button is pressed a form will open for the user to fill. I have already created the form for the user to fill but I cannot manage to make the button to create more buttons to work. I have coded this but it does not show the button on the JPanel.
I have created the following code:
private void mainButtonActionPerformed(java.awt.event.ActionEvent evt) {
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
jPanel3.add(b);
b.setVisible(true);
}
I want to know what is the correct code to write in the events / mouseClick of the button.
When you add or remove components from a JPanel, you need to make that JPanel redraw itself. Just adding or removing a component does not make this happen. Hence, after adding or removing a component from a JPanel, you need to call method revalidate followed by a call to repaint.
Refer to Java Swing revalidate() vs repaint()
Also note that the following line of your code is not required since the visible property is true by default.
b.setVisible(true);
Also, it is recommended to use a layout manager which means you don't need to call method setBounds as you have in this line of your code.
b.setBounds(50,100,95,30);
EDIT
As requested, a sample application. Clicking on the Add button will add another button. Note that the ActionListener for the Add button is implemented as a method reference.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonAd {
private static final String ADD = "Add";
private JFrame frame;
private JPanel buttonsPanel;
private void addButton(ActionEvent event) {
JButton button = new JButton("Added");
buttonsPanel.add(button);
buttonsPanel.revalidate();
buttonsPanel.repaint();
}
private JPanel createAddButton() {
JPanel addButtonPanel = new JPanel();
JButton addButton = new JButton(ADD);
addButton.addActionListener(this::addButton);
addButtonPanel.add(addButton);
return addButtonPanel;
}
private void createAndDisplayGui() {
frame = new JFrame("Add Buttons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonsPanel(), BorderLayout.CENTER);
frame.add(createAddButton(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonsPanel() {
buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
buttonsPanel.setPreferredSize(new Dimension(450, 350));
return buttonsPanel;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new ButtonAd().createAndDisplayGui());
}
}

How to mimic the behavior of JPopupMenu with JDialog?

I'm implementing an "in app" search engine with Swing and I want it to behave exactly like Windows 10's search box.
The search box should:
Open above and to the right of the search button, touching the button's edge.
Have the focus when open.
Close (if open) on a press of the search button.
Close (if open) when pressing with the mouse anywhere out of the search box.
It was perfect if JPopUpMenu could have JDialog as it's child but since it can't I need to implement the behaviors from scratch (or do I?).
This is my first time using Swing and I'm having difficulties implementing everything by myself.
I tried looking for examples online but I couldn't find much helpful information.
Is there a workaround to the fact that JPopUpMenu can't host JDialog?
Are there examples of implementing the behaviors I described?
Thanks
===============================Edit============================
Thanks for the comments so far. I've managed to get the behavior I wanted except one issue.
The following code creates a frame with a button:
public static void main(String[] args){
JFrame mainWindow = new JFrame();
mainWindow.setSize(420,420);
mainWindow.setVisible(true);
JFrame popUp = new JFrame();
popUp.setSize(210, 210);
JButton button = new JButton("button");
mainWindow.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!button.isSelected()){
button.setSelected(true);
popUp.setVisible(true);
}
else{
button.setSelected(false);
popUp.setVisible(false);
}
}
});
popUp.addWindowFocusListener(new WindowAdapter() {
#Override
public void windowLostFocus(WindowEvent e) {
popUp.setVisible(false);
}
});
}
When I click the button, a pop-up window appears and if I click out of the main window the pop up disappear but then when I want to re-open the pop-up I need to press the button twice.
How can I get the button to operate correctly when the pop-up was closed due to lose of focus?
Your "solution" is very brittle. Try moving the main JFrame before left-clicking on the JButton.
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Netbeans section. Study the rest of the tutorial.
I created a main JFrame that pops up a JDialog. I put the close JButton on the JDialog. The JDialog is modal, meaning you cannot access the main JFrame while the JDialog is visible.
You can place the JDialog anywhere you wish on the screen. Normally, you have a JDialog appear in the center of the parent JFrame. That's where users expect a dialog to appear. I placed the JDialog towards the upper left, just to show you how it's done.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PopupExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new PopupExample().createAndShowGUI());
}
private JFrame mainWindow;
public void createAndShowGUI() {
mainWindow = new JFrame("Main Window");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.add(createMainPanel(), BorderLayout.CENTER);
mainWindow.pack();
mainWindow.setLocationByPlatform(true);
mainWindow.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(200, 200, 200, 200));
JButton button = new JButton("button");
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
createAndShowDialog(mainWindow);
}
});
return panel;
}
private void createAndShowDialog(JFrame frame) {
JDialog dialog = new JDialog(frame, "Dialog", true);
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.add(createDialogPanel(dialog), BorderLayout.CENTER);
dialog.pack();
// Here's where you set the location of the JDialog relative
// to the main JFrame
Point origin = frame.getLocation();
dialog.setLocation(new Point(origin.x + 30, origin.y + 30));
dialog.setVisible(true);
}
private JPanel createDialogPanel(JDialog dialog) {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
JButton button = new JButton("Close");
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
return panel;
}
}

Not able to enable a button after it is disabled in java swing

I have just started learning java swing and I have been trying to create a simple game. The game is similar to minesweeper. A window with a matrix of bottons with just 1 mine. On clicking a button, if it's not a mine, i disable the button and display green color, and if it's a mine i disable the button and display red color. I have displayed the color by setting the button background to the required color. I have done the implementation so far just fine.
Next i added a reset button, on clicking which i renable all buttons by using : setEnabled(true).
But for some reason, the button is not getting enabled. I have confirmed that the program flow reaches the code for enabling the button, but i'm not able to find the reason why it is not working.
Here is a test program i wrote with a reset button and 1 button. Same issue. Can anyone point out what I maybe doing wrong?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test implements ActionListener{
JFrame frame = new JFrame("Mine");
JButton buttons = new JButton();
JButton reset = new JButton("Reset");
Container grid = new Container();
public Test(){
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
frame.add(reset, BorderLayout.NORTH);
reset.addActionListener(this);
buttons = new JButton();
buttons.addActionListener(this);
frame.add(buttons, BorderLayout.CENTER);
}
public static void main(String[] args){
new Test();
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(reset))
buttons.setEnabled(true);
else{
if(event.getSource()==buttons){
buttons.setBackground(Color.RED);
buttons.setEnabled(false);
}
}
}
}
Actually it's getting enabled when you click reset, all you forgot to do was reset the color:
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(reset)){
buttons.setEnabled(true);
buttons.setBackground(null);
}else{
if(event.getSource()==buttons){
System.out.println("xxx");
buttons.setBackground(Color.RED);
buttons.setEnabled(false);
}
}
}

New JCheckboxes not appearing below eachother

I am trying to make a basic program where whenever you press a button, a JCheckbox is generated and added below the other JCheckbox on a panel. I figured out how to generate the JCheckbox with a ActionListener but I can't figure out how to get each new check box to appear below the previous one. Everything else seems to be working but I can't get this location thing to work.
box.setVisible(true);
_p.add(box);
int i = 0;
int u = i++;
box.setAlignmentX(0);
box.setAlignmentY(u);
Here is a sample of my code. I've been stuck on this problem for a very long time and would greatly appreciate any and all help.
Check out the Swing tutorial on Using Layout Managers. You could use a vertical BoxLayout or a GridBagLayout or maybe a GridLayout.
Whatever layout you choose to use the basic code for adding components to a visible GUI is:
panel.add(...);
panel.revalidate();
panel.repaint();
The other statements in your code are not necessary:
//box.setVisible(true); // components are visible by default
The following methods do not set a grid position.
//box.setAlignmentX(0);
//box.setAlignmentY(u);
JCheckbox lives in a container like a JPanel (that means that you add checkbox to a panel) . A JPanel have a layoutManager. Take a look about Using Layout Managers
You could use BoxLayout with Y_AXIS orientation or a GridLayout with 1 column and n rows.
Example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CheckBoxTest {
private JPanel panel;
private int counter=0;
public CheckBoxTest(){
panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
JButton button = new JButton(" Add checkbox ");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
panel.add(new JCheckBox("CheckBox"+Integer.toString(counter++)));
//now tell the view to show the new components added
panel.revalidate();
panel.repaint();
//optional sizes the window again to show all the checkbox
SwingUtilities.windowForComponent(panel).pack();
}
});
panel.add(button);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Checkbox example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(Boolean.TRUE);
CheckBoxTest test = new CheckBoxTest();
frame.add(test.panel);
//sizes components
frame.pack();
frame.setVisible(Boolean.TRUE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Bring JPanel to front of other objects in java (SWING)

I want to make a loading message when an app processes, so I used a JPanel over a JTree. But when the user clicks on the JPanel, the JTree will be selected and the JPanel will go to the back. After hiding the JPanel, it never shows again. I don't know why, but it seems it never go in front of the JTree.
I need a way to bring the JPanel in front of everything. How can I do this?
EDIT: Also I must mention that I don't want a JDialog. I want to use the JPanel on top of any element to show a loading message until a process finishes.
So here you have at least two solutions. Either go with what #Geoff and #sthupahsmaht are suggesting. BTW also possible is to use JOptionPane which automatically creates a dialog for you.
The other option would be to use a GlassPane from a frame.
Or yet another option is to use JLayeredPane as #jzd suggests.
EDIT:
Example showing how to use GlassPane to capture user selections.
Try following steps:
1.Left clicking on the glass pane visible at start. See the output.
2.Right click it. This hides the glass pane.
3.Left clicking on the content pane. See the output.
4.Right click it. Go to point 1.
Enjoy.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class OverPanel extends JPanel
{
private static void createAndShowGUI()
{
final JFrame f = new JFrame();
f.setPreferredSize(new Dimension(400, 300));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel glassPanel = new JPanel();
glassPanel.setBackground(Color.RED);
glassPanel.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
System.out.println("f.getGlassPane() mousePressed");
if(e.getButton() == MouseEvent.BUTTON3)
f.getGlassPane().setVisible(false);
}
});
f.setGlassPane(glassPanel);
f.getContentPane().setBackground(Color.GREEN);
f.getContentPane().addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
System.out.println("f.getContentPane() mousePressed");
if(e.getButton() == MouseEvent.BUTTON3)
f.getGlassPane().setVisible(true);
}
});
f.getGlassPane().setVisible(true);
f.pack();
f.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
}
EDIT2:
If you want to have an effect of a dialog, you can achieve it by incorporating appropriately this code into my example.
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
panel.setBackground(Color.YELLOW);
panel.add(new JLabel("I am message Label"));
panel.add(new JButton("CLOSE"));
JPanel glassPanel = new JPanel(new GridBagLayout());
glassPanel.setOpaque(false);
glassPanel.add(panel);
You need a to use a JLayeredPane for moving components in front of each other.
Here is a tutorial: How to use Layered Panes
Disabled Glass Pane might help you out.
It's not really clear how your code is organized. However, it sounds like what you might want is a modal dialog. Here's a link to a similar discussion with a number of referenced resources.
How to make a JFrame Modal in Swing java
Use JXLayer or JIDE Overlayable.
Jpanel main = new JPanel();
Jpanel a = new JPanel();
JPanel b = new Jpanel();
main.add(a);
main.add(b);
at this point the object:
a -> 0 ( index)
b -> 1 (index)
main.getComponentCount() = 2
main.setComponentZorder(b,0);
a -> 1
b -> 0;
b OVER
a DOWN
For those who have no problem using a JDialog, this is a sure way to get it to show up if you're having issues. Just make sure to control it properly if the dialog is modal, when disposing, setting focus etc.
JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);

Categories

Resources