Add JTextField to OverlayLayout - java

I have a JTextField being added to an OverlayLayout, but the JTextField automatically scales to be the dimensions of the entire panel, which I don't want. I also don't want to mess with the dimensions of the JTextField because the default height is just right for the font, and the width is supposed to be defined by the number of columns in the constructor. What would be the right way to fix this?
Here's the relevant code that I have now:
frame = new JFrame("frame");
frame.setResizable(false);
panel = new GamePanel();
panel.setPreferredSize(new Dimension(500,300));
panel.setLayout(new OverlayLayout(panel));
JTextField t = new JTextField(50);
panel.add(t);
frame.add(panel);
frame.pack();
frame.setVisible(true);
GamePanel is just a subclass of JPanel; it doesn't do anything that would affect the JTextField.
EDIT: ok, I've heard now that using the default Swing layout managers isn't the best idea. kleopatra linked a page that refers to three third-party layouts that should accomplish pretty much everything you need to do, but I can't find anything that would let me overlay a text field (or other component) onto another custom-rendered panel. What would be the right approach?

Does this work as you want it?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.LayoutManager;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
public class OverlaySampleAlignment0 {
public static void main(String args[]) {
JFrame frame = new JFrame("Overlay Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(500,300));
LayoutManager overlay = new OverlayLayout(panel);
panel.setLayout(overlay);
JTextField field = new JTextField("", 12);
field.setMaximumSize(field.getPreferredSize());
//button.setMaximumSize(new Dimension(25, 25));
field.setBackground(Color.white);
field.setAlignmentX(0.0f);
field.setAlignmentY(0.0f);
panel.add(field);
frame.add(panel);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
The height is exactly the height needed for the font, and the width is (in my example) 12 "columns" (JTextField does not use a monospaced font by default in my Java setup). Additionally I aligned it in the upper left corner.
This might also help trouble-shooting layout issues:
Link
Most of the code is copied from here: Link. I just added the setMaximumSize(...) and used a JTextField instead of buttons etc.

Related

How can i get rid of the blue highlight inside JCombobox?

The JCombobox's "content" window has this blue highlight that i don't know how to get rid of, please help.
Here is an example of the problem:
package example;
import java.awt.CardLayout;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(1);
frame.setSize(500, 500);
frame.setLayout(new CardLayout());
frame.setVisible(true);
JPanel panel=new JPanel();
panel.setLayout(null);
frame.add(panel);
String[] model = {"pres.", "PPS.", "P. inp.", "P. mais q."};
JComboBox combox;
combox = new JComboBox(model);
combox.setBounds(100, 100, 145, 30);
combox.setBackground(new Color(215, 211, 165));
combox.setFocusable(false);
panel.add(combox);
panel.updateUI();
}
}
The combo box is a complex components that uses multiple components internally. The UI determines how the components interact with one another.
For example change your code to the following:
JComboBox combox;
combox = new JComboBox(model);
combox.setBorder( new LineBorder(Color.YELLOW) );
BasicComboBoxRenderer renderer = new BasicComboBoxRenderer();
renderer.setBorder( new LineBorder(Color.RED) );
combox.setRenderer(renderer);
And you will notice that the blue highlight is not a border of the combo box or its render, implying there is another internal container we don't have access to.
If you really want to solve the problem then you will need to customize the MetalComboBoxUI class, which is never an easy task because many of the painting methods will be private. But take a look at the code of the class to see if it can be done.
Other issues with your code:
Don't use updateUI(). The method is invoked internally in Swing when the LAF is changed. You are not changing the LAF
Components should be added to the frame BEFORE the frame is visible. This will eliminate the need for the updateUI().

Overlaying a JButton onto a JFrame with a JTabbedPan in its content pane?

The below code creates a frame with a JTabbedPane in the frame's contentPane and a "Help" button added directly to the frame's layered pane - at a higher index than the default, so it should always be painted in front of the tabbed pane. But as you can see if you run it, as soon as you click on one of the tabs (or, on Mac, as soon as you hover over a tab), the "Help" button gets painted over - i.e. disappears. You have to resize the frame to make the "Help" button re-appear.
Is this a Java bug or am I doing something wrong? If the latter, what needs to be done to fix the problem? I've consulted both https://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html and https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html .
Please pardon the poor positioning of the "Help" button. I was just trying to write a quick test to include here. The idea is the to overlay a "Help" icon button in the unused space of the JTabbedPane.
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class TabTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
JTabbedPane tp = new JTabbedPane();
tp.addTab("hello", new JPanel());
tp.addTab("there", new JPanel());
frame.getContentPane().add(tp, BorderLayout.CENTER);
JLayeredPane layeredPane = frame.getRootPane().getLayeredPane();
JButton helpButton = new JButton("Help");
helpButton.setBounds(800, 5, 50, 20);
layeredPane.add(helpButton, 400);
frame.setSize(new Dimension(900, 800));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
This is a common misunderstanding with JLayeredPane.
If you have a look at the JavaDocs for Container, you will note that there are (at least) two add methods
Container#add(Component, int)
Container#add(Component, Object)
The question you need to answer is, which one are you actually calling?
Both the JavaDocs for JLayeredPane and How to use JLayeredPane demonstrate that you should be calling the second one.
While the first can affect the z-ordering of the components, it's no guarantee that the component positions won't be changed.
Instead of:
layeredPane.add(helpButton, 400);
you should be using:
layeredPane.add(helpButton, new Integer(400));
which will pass the value as a constraint to the container, instead of the desired position within the container hierarchy - yeah, suitable I know
An alternative solution might be to use the glassPane instead, for example...
JFrame frame = new JFrame();
JTabbedPane tp = new JTabbedPane();
tp.addTab("hello", new JPanel());
tp.addTab("there", new JPanel());
frame.getContentPane().add(tp, BorderLayout.CENTER);
// Null layout used here for demonstration purposes only
JPanel glassPane = new JPanel(null);
glassPane.setOpaque(false);
frame.getRootPane().setGlassPane(glassPane);
// This is important, as setGlassPane makes it invisible
glassPane.setVisible(true);
JButton helpButton = new JButton("Help");
helpButton.setBounds(800, 5, 50, 20);
glassPane.add(helpButton);
frame.setSize(new Dimension(900, 800));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

Java component deployment using JPanel

I wanted components deployment like this picture:
I wrote a code that makes two JPanel in a JFrame and puts components JPanel on left side. I set Frame Layout to BorderLayout and Each panel's Layout to FlowLayout. However, result was not what I wanted. Even List is not appear.
Result picture:
Can you tell me what to do?
There is a code below.
package com.java.APISearch;
import java.awt.*;
import javax.swing.*;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
JPanel search;
JPanel result;
JLabel ksLb;
JTextField ksTf;
JButton ksOK;
JCheckBox choicePackage;
JCheckBox choiceClass;
JCheckBox choiceFunc;
JTextField dsTf;
JButton dsOK;
JLabel rcLb;
JList<String> rcList;
JTextField resultTf;
Container contentPane;
public MainFrame(String title) {
super(title);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
setLocation(screenSize.width/2 - 300, screenSize.height/2 - 200);
setSize(new Dimension(600, 400));
setResizable(false);
setLayout(new BorderLayout());
search = new JPanel();
result = new JPanel();
search.setLayout(new FlowLayout(FlowLayout.LEFT));
search.setSize(new Dimension(300,400));
result.setLayout(new FlowLayout());
result.setSize(new Dimension(300,400));
contentPane = getContentPane();
contentPane.add(search, BorderLayout.WEST);
contentPane.add(result, BorderLayout.EAST);
ksLb = new JLabel("키워드 검색");
ksTf = new JTextField(20);
ksOK = new JButton("검색");
search.add(ksLb);
search.add(ksTf);
search.add(ksOK);
choicePackage = new JCheckBox("package");
choiceClass = new JCheckBox("class");
choiceFunc = new JCheckBox("function");
dsTf = new JTextField(20);
dsOK = new JButton("검색");
search.add(choicePackage);
search.add(choiceClass);
search.add(choiceFunc);
search.add(dsTf);
search.add(dsOK);
rcLb = new JLabel("recent search");
rcList = new JList<String>();
search.add(rcLb);
search.add(rcList);
}
}
The common strategy to solve complex computing tasks, is to break them into small, well defined manageable tasks. Divide and conquer.
This also applies to gui: break the design into small, easy to layout containers.In this case, for example start by dividing the design into two areas:
Serach panel added to JFrame's NORTH, and a main panel added to JFrame's CENTER. The main panel is a container for all other gui components. See more info in the code.
Here is a skeleton to demonstrate the strategy. Note the comments :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainFrame extends JFrame {
public MainFrame(String title) {
super(title);
setSize(new Dimension(600, 400));
setResizable(false);
//setLayout(new BorderLayout());// no need. its the default for JFrame
JPanel search = new JPanel();
search.setLayout(new FlowLayout(FlowLayout.LEFT));
//search.setSize(new Dimension(300,400)); //let layout manager set size
//set preferred size if needed
JLabel ksLb = new JLabel("Search:");
JTextField ksTf = new JTextField(20);
JButton ksOK = new JButton("Click Me");
search.add(ksLb);
search.add(ksTf);
search.add(ksOK);
add(search, BorderLayout.NORTH); //add search to content pane
//construct a container to hold all the rest
//set border layout to it
JPanel mainPanel = new JPanel(new BorderLayout());
//add content to mainPanel:
//add result to NORTH
//add a JPanel to hold list and label to CENTER
add(mainPanel, BorderLayout.CENTER);//main to content pane
setVisible(true);
}
}
More examples of applying this strategy: 1 2 and 3
To make thing like this, use NetBeans (or some other tool that will help you create layout).
In NetBeans, getting something like you want takes ~5 minutes. It's really easier comparing to writing code for yourself.
In my personal opinion, GridBagLayout is the best thing when it comes to most of Swing based components. You can easily take control over each and every cell (whether it should grow or not, how anchors should behave, whether components should fill cell or not, etc.).
Take a look here: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
If you don't know which layout would suit you best, you can always take a look here:
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
For NetBeans tutorial, take a look here: https://netbeans.org/kb/docs/java/quickstart-gui.html

Layout - Relative to screensize

So I am a computer science student and I've finished my first year. I wanted to create a simple program and I realized that I am so tired of using no layout;
this.setLayout(null);
It is so tiresome to add bounds to every single component. Well, I have been using JPanel components and GridLayout a lot, which have made my work a bit easier. But I am tired of it.
I care very much about the look of the GUI I make and use almost half the time programming to make the GUI look good before I start adding the functionality of the code. By not using a layout and adding bounds I am forced to setResizable(false) because it looks bad if I change the size of the JFrame.
I've been searching a bit, and I know of BorderLayout, and FlowLayout, but I don't like them. Is there any Layout that keeps the relative size of the components with respect to the size of the window?
For example I want to make a simple program that looks like this: (Quick sketch in Photoshop)
I can easily make this with 3 panels, but as I said, if I change the size of the frame everything stays in place instead of being relative to the window-size.
Can you guys help me?
This design looks for me to fit the BorderLayout, where in the NORTH you have the values that changes the CENTER you have the main part, and the SOUTH you have the buttons.
Link to the Oracle Border Layout
You can apply this BorderLayout to the JFrame, then create 3 JPanels for each of the NORTH,CENTER and SOUTH sections. If you want to use responsive design for the components and panels, take a look at GridBagLayout which is much more flexible than the GridLayout
Layout management is a very complex problem, I don't think people really appreciate just how complex it really is.
No one layout is ever going to achieve everything your want, in most cases, you will need to resort to two or more layouts, especially as your requirements become more complex.
For example, the following is simply a BorderLayout at the base and the buttons on a JPanel using a FlowLayout
Which is achieved by using
JList listOfThings = new JList(...);
JTextField tf = new JTextField();
JButton add = new JButton("Add");
JButton delete = new JButton("Delete");
JButton go = new JButton("Go...");
JPanel buttons = new JPanel();
buttons.add(add);
buttons.add(delete);
buttons.add(go);
add(new BorderLayout());
add(tf, BorderLayout.NORTH);
add(new JScrollPane(listOfThings));
add(buttons, BorderLayout.SOUTH);
For more complex layouts, I would consider using something like GridBagLayout. You may also want to consider MigLayout as an alternative
Take a look at Laying Out Components Within a Container for more details about using layout managers
I'd like to use the combination of BorderLayout and BoxLayout. BorderLayout let me put the component based on their relative location's relation and BoxLayout let me manage the subtle distance ( create some white space). You can use component.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right)); to achieve this goal too.
Here is a demo and hope it can help you.
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class LayoutTest{
private JTextField jTextField;
public void createUI(){
JFrame frame = new JFrame("Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(new TextFieldPanel());
mainPanel.add(Box.createVerticalStrut(8));
mainPanel.add(new ListPanel());
mainPanel.add(Box.createVerticalStrut(8));
mainPanel.add(new ButtonPanel());
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
LayoutTest layoutTest = new LayoutTest();
layoutTest.createUI();
}
#SuppressWarnings("serial")
class TextFieldPanel extends JPanel{
public TextFieldPanel(){
setLayout(new BorderLayout());
jTextField = new JTextField();
jTextField.setEditable(false);
add(jTextField,BorderLayout.CENTER);
}
}
#SuppressWarnings("serial")
class ListPanel extends JPanel implements ListSelectionListener{
private JList<String> list;
public ListPanel(){
setLayout(new BorderLayout());
String stringArr[] = new String[30];
for (int i = 0; i < 30; i++) {
stringArr[i] = "JList :This line is item" + i;
}
list = new JList<String>(stringArr);
JScrollPane scrollPane = new JScrollPane(list);
add(scrollPane,BorderLayout.CENTER);
setBackground(new Color(211,211,211));
list.addListSelectionListener(this);
}
#Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
jTextField.setText(list.getSelectedValue());
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel{
public ButtonPanel(){
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
setLayout(new BorderLayout());
add(button1,BorderLayout.WEST);
add(button2,BorderLayout.CENTER);
add(button3,BorderLayout.EAST);
}
}
}
Here is the effect:
You can use BoxLayout for ButtonPanel if you don't want to let the button's size change.
#SuppressWarnings("serial")
class ButtonPanel extends JPanel{
public ButtonPanel(){
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(button1);
add(Box.createHorizontalStrut(8));
add(button2);
add(Box.createHorizontalStrut(8));
add(button3);
}
}
And the effect is like this:
For more infomation about using BoxLayout to generate whitespace, you can refer to https://stackoverflow.com/a/22525005/3378204
Try GridBagLayout.
Your sketch is actually quite close to the one of the examples in the official tutorial.
HVLayout keeps the relative size of the components with respect to the size of the window, that is, if you configure components to have a relative size (e.g. buttons usually do not grow or shrink - they stick to their preferred size). This SO question was one of the motivations for me to push HVLayout to a release and a screenshot is included (showing big window size, smalll size and preferred "default" size):
Source code for the window is in RelativeToWindowSize.java
A number of helper-classes from HVLayout are used to build the window, so I don't think it will be of much use here, but to get an impression, the "build window" part shown below:
public RelativeToWindowSize build() {
CSize cs = new CSize();
CForm form = new CForm(new VBox(new Insets(2, 4, 2, 4)), cs);
addTitledBorder(form.get(), "Vertical box", Color.BLACK);
form.add(new JScrollPane(
tfield = new JTextArea("Value that changes with value choosen from list.\nhttp://stackoverflow.com/questions/24462297/layout-relative-to-screensize/")
)).csize().setAreaSize(1.0f, 2.5f).fixedMinHeight().setMaxHeight(4.0f);
// tfield shows mono-spaced font by default.
tfield.setFont(SwingUtils.getUIFont());
form.add(new JScrollPane(vlist = new JList<String>(getListValues())))
.csize().setAreaSize(1.0f, 5.0f);
form.addChild(new HBox());
addTitledBorder(form.get(), "Horizontal box", Color.RED);
form.addChild(new HBox(SwingConstants.CENTER));
addTitledBorder(form.get(), "Centered box.", Color.BLUE);
form.add(createButton(cs, "Add"));
form.add(createButton(cs, "Modify"));
form.up();
form.addChild(new HBox(SwingConstants.TRAILING));
addTitledBorder(form.get(), "Trailing box", Color.GREEN);
form.add(createButton(cs, "Delete"));
setContentPane(form.getRoot());
pack();
setLocationByPlatform(true);
//applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
vlist.addListSelectionListener(this);
log.debug(getClass().getName() + " build.");
return this;
}
private Component createButton(CSize cs, String text) {
// For purpose of demo, let button shrink in width.
return cs.set(new TButton(text)).setFixed().shrinkWidth(0.33f).get();
}

How to set a specific dimension of a Button object in Java Swing?

I have this simple Java Swing test application that show an upper label and under this label a button:
package com.techub.exeute;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import org.jdesktop.application.SingleFrameApplication;
public class Main extends SingleFrameApplication{
public static void main(String[] args) {
Main a = new Main();
a.startup();
}
#Override
protected void startup() {
JFrame frame = new JFrame("FrameDemo");
frame.setMinimumSize(new Dimension(800, 400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel myLabel = new JLabel("Hello World !!!", SwingConstants.CENTER);
myLabel.setFont(new Font("Serif", Font.BOLD, 22));
myLabel.setBackground(Color.RED);
myLabel.setOpaque(true);
myLabel.setPreferredSize(new Dimension(100, 80));
frame.getContentPane().add(myLabel, BorderLayout.NORTH);
Button myButton = new Button("Click Me !!!");
myButton.setMaximumSize(new Dimension(50, 25));
frame.getContentPane().add(myButton, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
The button is in the BorderLayout.CENTER position. The problem is that this button occupies all available space in the CENTER position also if I have set the Maximum Size property with a Dimension object.
What am I wrong? What can I do to create a button having specific dimension?
You're currently telling Java to place the button in the center of your BorderLayout. Java then thinks that you want the entire area filled with this button. If you want to place a normal sized button in the center of your BorderLayout, add the button to a new JPanel and place the JPanel inside BorderLayout.CENTER.
Doing this, you're telling Java to fill out BorderLayout.CENTER with your JPanel. The elements that you place inside this JPanel will appear normal, because these elements are not getting "stretched" because of your BorderLayout - the JPanel is.
You fail to realize that it's not only the max/min/preferred sizes of the components that determine the outcome. The LayoutManager has a lot to say in this, and as you noticed, BorderLayout will fill the whole area with the component.
What you can do is create a JPanel, make it use for example FlowLayout and put that JPanel to BorderLayout.CENTER and the JButton to the JPanel.
You are using BorderLayout, North region has JLabel. JButton is put on center. JButton will occupy all the space left as per BorderLayout.
Please find more information about Layout on link : http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
U are using BorderLayout, button occupy all the left space of the frame.
use setBounds() function .
myButton.setBounds(10,200,100,30);

Categories