Java Textfield focus - java

Hello I have a problem with the focus
mytext= new JTextField();
mytext.requestFocus(true);
gc.fill =GridBagConstraints.HORIZONTAL ;
gc.gridx =3; gc.gridy=4;
gbl.setConstraints(mytext,gc);
jContentPane.add(mytext);
I tried
mytext.requestFocus();
too
and how can I auto-select the text in the textfield so the text is marked?

From the Swing Tutorial
If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed. The following sample code shows how this operation can be done:
//...Where initialization occurs...
JFrame frame = new JFrame("Test");
JPanel panel = new JPanel(new BorderLayout());
//...Create a variety of components here...
//Create the component that will have the initial focus.
JButton button = new JButton("I am first");
panel.add(button);
frame.getContentPane().add(panel); //Add it to the panel
frame.pack(); //Realize the components.
//This button will have the initial focus.
button.requestFocusInWindow();
frame.setVisible(true); //Display the window.

As for selecting all the text you should use...
mytext.selectAll();
As for getting focus, maybe you should try the requestFocus function after everything has been added to jContentPane.

Related

How to fix GUI components "leaving" their panels or taking up more space they they are supposed to?

I am trying to make a GUI for a game. I am very new to Java, especially GUI. The code below is a snippet which is supposed to make a JFrame with nested panels for organization. It works until I add buttons to the button panel. They end up on the boardBckg panel. If I manage to place them on the correct panel the JTextField disappears or it takes up the entire screen. I have been working on this part of the code for the past two days and I could really use GUI tips.
private void makeWindow()
{
boardPanel = new JPanel();
boardBckg = new JPanel();
menuPanel = new JPanel();
save = new JButton("Save");
save.setSize(Buttons);
load = new JButton("Load");
load.setSize(Buttons);
replay = new JButton ("Replay");
replay.setSize(Buttons);
words = new JTextField();
frame = new JFrame(title);
boardPanel.setSize(PANEL);
boardPanel.setMaximumSize(MAX);
boardPanel.setMinimumSize(MIN);
boardPanel.setLayout(new GridLayout(m,n));
boardBckg.setSize(1000, 1000);
boardBckg.setBackground(Color.cyan);
boardBckg.add(boardPanel, BorderLayout.CENTER);
frame.setSize(1500, 1000);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxLayout vertical = new BoxLayout(menuPanel, BoxLayout.Y_AXIS);
menuPanel.setSize(500, 1000);
menuPanel.setBackground(Color.blue);
menuPanel.setLayout(vertical);
frame.add(boardBckg);
frame.add(menuPanel);
JPanel iGiveUp = new JPanel();
iGiveUp.setBackground(Color.black);
JPanel buttons = new JPanel();
buttons.setBackground(Color.darkGray);
buttons.add(save);
buttons.add(load);
buttons.add(replay);
menuPanel.add(iGiveUp);
menuPanel.add(buttons);
iGiveUp.add(words);
boardBckg.add(boardPanel, BorderLayout.CENTER);
The default layout of a JPanel is the FlowLayout. You can't just specify a BorderLayout constraint when you add the component to the panel.
frame.add(boardBckg);
frame.add(menuPanel);
The default layout for (the content pane of) the frame is a BorderLayout. If you don't specify a constraint, then the component is added to the BorderLayout.CENTER. Problem is only one component can be added to the CENTER so you only see the last comoponent added.
frame.setVisible(true);
Component should be added to the frame BEFORE the frame is packed and made visible. So the above statement should be the last statement in your constructor.
I have no ideas what your desired layout is but you need to start with something simple and take advantage of the default BorderLayout of the frame.
So your basic logic might be something like:
JPanel menuPanel = new JPanel()
menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));
menuPanel.add(...);
menuPanel.add(...);
JPanel center = new JPanel();
center.setLayout(...);
center.setBackground( Color.BLUE );
center.add(...);
frame.add(menuPanel, BorderLayout.LINE_START);
frame.add(center, BorderLayout.CENTER);
frame.pack();
frame.setVisible( true );
The main point is to break the panels down logically and add them to the frame one at a time. So first get the menu and its child components added to the frame is the correct position. Then you can add the CENTER panel and its child components.

Change dimensions of JButton

I have problem with this. The button is taking up the entire JFrame. I've tried changing the dimensions of the JFrame and the JButton but with no changed. It's completely hiding a JTable underneath. Could someone please tell me what I'm doing wrong.
JFrame FRAME = new JFrame();
JButton BUTTON = new JButton("OK");
FRAME.add(new JScrollPane(TableName));
BUTTON.setPreferredSize(new Dimension(20,30));
FRAME.add(BUTTON);
FRAME.setSize(700, 600);
FRAME.setVisible(true);
FRAME.setLocationRelativeTo(null);
The default layout manager for a a JFrame is a BorderLayout. You are attempting to add two component the CENTER which is not allowed. Only the last one added will be displayed.
You need to specify constraints when adding components to a BorderLayout. Your code should be something like:
frame.add(new JScrollPane(TableName), BorderLayout.CENTER);
button.setPreferredSize(new Dimension(20,30));
frame.add(button, BorderLayout.PAGE_START);
Also, variables names should NOT be upper cased. Follow Java convention.
Read the section from the Swing tutorial on How to Use BorderLayout for more information and working examples. The tutorial code will also show you how to better structure your program so you follow Swing coding conventions.
Don't add the button straight to the frame, create a JPanel first, add the button to the panel then add the panel to the frame.
JFrame frame = new JFrame();
// frame.setBounds(x axis, y axis, weight, height)
frame.setBounds(10,10,304,214);
frame.getContentPane().setLayout(null);
JButton button = new JButton("Button");
button.setBounds(98, 75, 126, 39);
frame.getContentPane().add(button);
frame.setVisible(true);

Put a JLabel over two JButtons

Okay so before you ask, yes I'm not using any Layout Manager. No, that doesn't make this bad design (as I've seen people in here saying because someone simply didn't use one). The thing is i want the label to always (and I mean always) show over the two buttons (over the gap left by them which makes it impossible to put it as an Icon or a text on the JButton).
JFrame frame = new JFrame("ColorTap");
private void init() {
JButton jb1 = new JButton(""), jb2 = new JButton("-");
JLabel label = new JLabel("TEXT HERE");
label.setForeground(Color.white);
label.setFont(new Font("Arial Bold",Font.ITALIC,30));
label.setBounds(60,249,200,100);
frame.setLayout(null);
jb1.setBounds(0, 0, 300,298);
jb2.setBounds(0, 302, 300, 300);
jb1.setBackground(Color.black);
jb2.setBackground(Color.black);
jb1.setBorderPainted(false);
jb2.setBorderPainted(false);
frame.add(label);
frame.add(jb1);
frame.add(jb2);
frame.setResizable(false);
frame.setSize(300, 628);
frame.setLocation(550, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
After this what's stranger to me is that the button on the bottom stays under the label and not the one on the top... HELP! Thanks
Swing is optimized to paint components in two dimensions. That is it assumes components will never overlap. Overlapping JButtons cause a problem because of the rollover effects which only cause the buttons to be painted, not the label, so the button is painted over the top of the label.
So you need to tell Swing that components do overlap so Swing can make sure components are painted in the proper ZOrder:
JPanel panel = new JPanel()
{
#Override
public boolean isOptimizedDrawingEnabled()
{
return false;
}
};
Now you can set the layout manager of the panel and add your components to the panel and they will be painted properly.
See: How to put a JButton with an image on top of another JButton with an image? for a working example that DOES use layout managers.

Java Swing JFrame Layout

I just wrote a simple code where I want a textfield and a button to appear on the main frame, but after running all I see is the textfield.
If I write the code of the button after the textfield then only the button is displayed.
Any idea why?
JFrame mainframe=new JFrame();
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setBounds(0,0,200,200);
JButton jb=new JButton();
jb.setText("Leech");
mainframe.add(jb);
JTextField link=new JTextField(50);
mainframe.add(link);
mainframe.pack();
mainframe.setVisible(true);
The default layout on a JFrame is a BorderLayout. Calling the add method on a Container with such a layout is equivalent to a call add(..., BorderLayout.CENTER). Each of the locations of the BorderLayout can contain only one element. Hence making two calls
mainframe.add(jb);
mainframe.add(link);
results in a CENTER containing the last component you added. If you want to avoid this you can either add it to different locations, or use another layout manager (for example a FlowLayout) by calling JFrame#setLayout
Instead of adding directly Components to the JFrame, use a JPanel as container with the desired LayoutManager.
Here you can find several tutorials on layout managers.
Basically in Swing the LayoutManager is responsible for laying out the children Components (establishing their position and their size), so every container component you use inside your app, should be configured with the appropiate LayoutManager.
Add your components to a JPanel and then add that panel to the ContentPane of JFrame.
JFrame window = new JFrame();
JPanel mainframe = new JPanel();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(0,0,200,200);
JButton jb = new JButton();
jb.setText("Leech");
mainframe.add(jb);
JTextField link = new JTextField(50);
mainframe.add(link);
window.getContentPane().add(mainframe);
window.pack();
window.setVisible(true);
You can also use something like Flow Layout which is the default layout used by JPanel. It is used to arrange components in a line or a row. For example from left to right or from right to left:
Flow layout arranges components in line and if no space left all remaining components goes to next line. Align property determines alignment of the components as left, right, center etc.
To use it you will need to set JFrame layout by using JFrame.setLayout(layout) and to pass flow layout as a parameter.
Following example shows components arranged in flow layout:
package example.com;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FlowLayoutExample {
FlowLayoutExample(){
JFrame frame = new JFrame("Flow Layout");
JButton button, button1, button2, button3, button4;
button = new JButton("button 1");
button1 = new JButton("button 2");
button2 = new JButton("button 3");
button3 = new JButton("button 4");
button4 = new JButton("button 5");
frame.add(button);
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.setLayout(new FlowLayout());
frame.setSize(300,300);
frame.setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutExample();
}
}
Check out to learn more about JFrame layouts.
JFrame's default Layout Manager is BorderLayout. If you want the automatic layout, you may use the FlowLayout:
mainframe.setLayout(new FlowLayout());
If you want to specify coordinates by setBounds() method, you have to cancel the setting of layout manager on JFrame:
mainframe.setLayout(null);
jb.setBounds(10,10,100,50);
link.setBounds(10,70,180,100);
if you see BorderLayout Documentation
mainframe.add(jb); is equals to mainframe.add(jb,BorderLayout.CENTER);
mainframe.add(link); is equals to mainframe.add(jb,BorderLayout.CENTER);
so it just show the last one

Open new tab in frame other than the frame where button is clicked

I have 2 frames. One contains buttons that do appropriate actions on data. And secnd frame which contains data in tab view.
Now I have to add one button in first frame by clicking on this button a new tab should be added on second frame. How can I do this?
Make the JTabbedPane of the second frame accessible in first frame and then just simply call add() method of JTabbedPane to add a new tab in it.
Following is a sample code for that:
First frame:-
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250,250);
JButton button = new JButton("Add tab to another frame.");
button.addActionListener(this);
frame.add(button);
frame.setVisible(true);
Second frame:-
Decalre a global variable of tabbedPane
JTabbedPane tabs;
int i = 0; // just a tab counter. You might not need this.
Initializaition code
JFrame frame2 = new JFrame("Demo 2");
frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame2.setSize(250,250);
tabs = new JTabbedPane();
frame2.add(tabs);
frame2.setVisible(true);
Action on button click in first frame:-
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.add(new JLabel("tab number "+i));
tabs.add((i++)+"",panel); //--access tabbedPane of second frame here.
}

Categories

Resources