JButton alignment in JFrame - java

I am making a pig latin translater using JFrame in Java. Here's my problem; I have a "quit" button that closes the program; that doesn't matter, but what does is I have no control over its alignment (or any other component). I tried using quit.setAlignmentY(BOTTOM_ALIGNMENT); in the hopes that that would align it to the bottom of the page, but nothing changed. Some help here, please?
In case anyone needs it, here's the code;
public class Main extends JFrame{
private static JLabel label, result;
private static JTextField english;
private static JButton quit;
private static String originalResult = "Translated to pig latin: ";
private static ArrayList<String> beginningSymbols = new ArrayList<>();
private static ArrayList<String> endingSymbols = new ArrayList<>();
//prompt for string to translate, display final result
public Main(){
super("Pig Latin Translator");
setLayout(new FlowLayout());
setVisible(true);
setSize(600, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
translatingHandler th = new translatingHandler();
label = new JLabel("Enter a phrase to translate into pig latin, then press enter:");
english = new JTextField(15);
result = new JLabel(originalResult);
quit = new JButton("Quit program");
english.addActionListener(th);
quit.addActionListener(th);
quit.setAlignmentY(BOTTOM_ALIGNMENT);
add(label);
add(english);
add(quit);
add(result);
english.requestFocus();
}
public static void main(String[] args){
new Main();
}
...
}
The JButton quit is the one I'm trying to align to the bottom of the page. Thanks!

Actually you are using FlowLayout. If you take a look at FlowLayout tutorials it is mentioned that
The FlowLayout class puts components in a row, sized at their
preferred size. If the horizontal space in the container is too small
to put all the components in one row, the FlowLayout class uses
multiple rows. If the container is wider than necessary for a row of
components, the row is, by default, centered horizontally within the
container.
If you insist on using FlowLayout align your components.
Anyways take a look at Using Layout Managers. For your task appropriate layout managers will be BorderLayout.
But if you need something very flexible use GridBagLayout or MigLayout but they are a little complex to use.
So as #HovercraftFullOfEels suggested try avoiding them.

Welcome to the confusing world of Java Swing. You probably want to look into layout managers. Specifically, BorderLayout might be of interest.

Related

How to Keep JCheckBox Horizontally inside JPanel

I have a JPanel. Inside Panel I have kept one JLabel and three JCheckBox.
I want to keep all the checkBox in one line after JLabel. Here is the sample code and some screenshots.
Output 1
Output 2
When i change to X_AXIS it is coming everything in one line and when i switch to Y_AXIS then it is coming new line means vertically.
But my requirement is all the checkbox should come next line means after JLabel.
JLabel should come in line and all the checkBox should come in one line.
public class CheckBoxWithJLabel {
public static void main(String[] args) {
JFrame f= new JFrame("CheckBox Example");
JPanel panel = new JPanel();
panel.setBounds(40,80,600,200);
JCheckBox chk_Embrodary=new JCheckBox("Embrodary");
JCheckBox chk_Cutting=new JCheckBox("Cutting");
JCheckBox cb_Sewing=new JCheckBox("Sewing");
panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.X_AXIS));
JLabel lblHeader=new JLabel("Job Work Process Selection");
panel.add(lblHeader);
panel.add(chk_Embrodary);
panel.add(chk_Cutting);
panel.add(cb_Sewing);
f.add(panel);
f.setSize(600,400);
f.setLayout(null);
f.setVisible(true);
}
}
I want this output like
this
How to solve this problem?
I would highly suggest you to have a look through the Java Swing Tutorial, especially the Laying Out Components Within a Container section, since it seems you lack some basic understanding of how Swing and its Layout Managers are supposed to be used.
Regarding your problem:
Currently, you are using a single BoxLayout, which " puts components in a single row or column". You only want that behavior for your JCheckBoxes though, and not for your JLabel. Keeping this in mind, the solution is to split up your components and to not put all of them in a single JPanel. Doing this will grant you more flexibility in how you design your GUI, since you can use multiple layouts in different nested panels.
You could do something like this (explanation in the code comments):
public static void main(String[] args) {
JFrame f = new JFrame("CheckBox Example");
// add a Y_AXIS boxlayout to the JFrames contentpane
f.getContentPane().setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JCheckBox cbEmbrodary = new JCheckBox("Embrodary");
JCheckBox cbCutting = new JCheckBox("Cutting");
JCheckBox cbSewing = new JCheckBox("Sewing");
// no need to set the bounds, since the layoutmanagers will determine the size
JPanel labelPanel = new JPanel(); // default layout for JPanel is the FlowLayout
JLabel lblHeader = new JLabel("Job Work Process Selection");
labelPanel.add(lblHeader); // JPanel for the label done
// JPanel for the comboboxes with BoxLayout
JPanel cbPanel = new JPanel();
cbPanel.setLayout(new BoxLayout(cbPanel, BoxLayout.X_AXIS));
cbPanel.add(cbEmbrodary);
cbPanel.add(cbCutting);
cbPanel.add(cbSewing);
f.add(labelPanel);
f.add(cbPanel);
// No need to set the size of the JFrame, since the layoutmanagers will
// determine the size after pack()
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
Output:
Sidenotes:
Don't set fixed sizes via setSize() or setBounds() to your components. Swing is designed to be used with appropariate LayoutManagers, and if you do that, calling pack() on the JFrame before setting it visible will layout the components and determine their appropriate size. (Also, don't use null-layout for the same reasons)
If you need the JLabel to not be centered but left aligned, like in your screenshot, then use the following:
FlowLayout layout = (FlowLayout) labelPanel.getLayout();
layout.setAlignment(FlowLayout.LEFT);

Is there a way of moving JPanel in BorderLayout?

I am using a BorderLayout for the frame (the first one that "caught" my attention in the tuts) and a FlowLayout for the labels (the one I found appropriate for what I do), and the result shows up like this:
My objective is to push the "2*1" a little bit down, to sort of "center" it.
I looked around and found a lot of people saying to use a null layout, but then saying it's not the best alternative (even though my window is not resizable), and the other solution I found was using a combo of layouts (unless I misunderstood).
The question is the one on top of this, plus if not, what really is the best alternative? (The following is the code that makes this window (minus the vars and other methods, to simplify visualization).
public Frame() {
super("Jogo de Multiplicar!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
setResizable(false);
getContentPane().setBackground(pink);
mensagem = new TransparentPanel();
operacao = new TransparentPanel();
//added stuff in mensagem and operacao
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}
My objective is to push the "2*1" a little bit down, to sort of "center" it.
If you just want more space at the top then you can use a Border:
operacao.setBorder( new EmptyBorder(...) );
Read the section from the Swing tutorial on How to Use Borders for more information.
If you want to actually center it you can use a BoxLayout:
Box box = Box.createVerticalBox();
box.add( Box.createVerticalGlue() );
box.add( topPanel );
box.add( Box.createVerticalGlue() );
box.add( bottomPanel );
The tutorial also has a section on How to Use BoxLayout. Search the table of contents.
You could use MigLayout as your only LayoutManager. It's pretty mighty and usually offers everything that the other managers do too.
With this it's pretty simple to center the components:
public class MultiplyExample extends JFrame{
private static final long serialVersionUID = 1L;
JLabel testLabel = new JLabel("2*2 = 4");
public MultiplyExample(){
super("Example");
setBounds(300, 50, 200, 200);
// Set the MigLayout, so that columns and then rows get centered
setLayout(new MigLayout("center, center"));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(testLabel);
}
public static void main(String[] args) {
JFrame testFrame = new MultiplyExample();
testFrame.setVisible(true);
}
}
Result:
Here is a demo what the MigLayout has to offer:
http://www.miglayout.com/swingdemoapp.jnlp
Here is a quickstart-guide:
http://www.miglayout.com/QuickStart.pdf
If you have to use BorderLayout, you could put your components onto another panel and put this one into the center by using BorderLayout.CENTER:
pane.add(button, BorderLayout.CENTER);

Making JLable in JTextPane Undeletable

I currently have a JLabel embedded in a JTextPane using this:
import javax.swing.*;
import javax.swing.text.*;
public class MainFrame
{
JFrame mainFrame = new JFrame("Main Frame");
JTextPane textPane = new JTextPane();
public MainFrame()
{
String[] components = {"Title", "\n"};
String[] styles = {"LABEL_ALIGN", "LEFT_ALIGN"};
StyledDocument sd = textPane.getStyledDocument();
Style DEFAULT_STYLE = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style LEFT_STYLE = sd.addStyle("LEFT_ALIGN", DEFAULT_STYLE);
StyleConstants.setAlignment(LEFT_STYLE, StyleConstants.ALIGN_LEFT);
Style CENTER_STYLE = sd.addStyle("CENTER_ALIGN", DEFAULT_STYLE);
StyleConstants.setAlignment(CENTER_STYLE, StyleConstants.ALIGN_CENTER);
JLabel titleLbl = new JLabel("Title");
Style LABEL_STYLE = sd.addStyle("LABEL_ALIGN", DEFAULT_STYLE);
StyleConstants.setAlignment(LABEL_STYLE, StyleConstants.ALIGN_CENTER);
StyleConstants.setComponent(LABEL_STYLE, titleLbl);
for(int i = 0; i < components.length; i++)
{
try
{
sd.insertString(sd.getLength(), components[i], sd.getStyle(styles[i]));
sd.setLogicalStyle(sd.getLength(), sd.getStyle(styles[i]));
}
catch(BadLocationException e)
{
e.printStackTrace();
}
}
mainFrame.add(textPane);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
How can I make the label un-deletable? Because whenever I hold backspace, the label ends up getting removed from the JTextPane
You might be able to use a NavigationFilter to prevent the removal of the component at the beginning of the text pane. Check out: How to make part of a JTextField uneditable for an example of this approach. In this case the label represents a single character so the prefix length would be set to 1. Or maybe you can just use the prefix concept itself and don't even use the JLabel.
Otherwise, you might be able to create a custom DocumentFilter. Check out the section from the Swing tutorial on Implementing a DocumentFilter for the basics.
So you would need to track the offset off the location of the component. Then in the remove(...) method of the filter you would need to check if you are removing data in the range of your offset. If so you would ignore the remove.
Of course the offset can dynamically change if you add or remove text before the label so you would need to manage that as well.
Or you can check out the Protected Text Component which attempts to manage all of that for you.
Why not just put your title label outside the text area? That seems more intuitive.
It looks like there's no real way to avoid this while still allowing the textarea to be editable. You could place the label above the text frame so that it occupies the same space, or above the text frame so that it behaves like a proper title.
Unfortunately, the nature of the textarea is that all of its subcomponents are editable or none of them are.

How to layout multiple panels on a jFrame? (java)

I am in the process of making my own java socket game. My game is painting alright to the full screen (where it says "paint graphics here", but im painting to the whole jframe at the moment). I want to add a textbox with a scroll bar for displaying only text, not taking any input and another textbox to take text inputs from the user and then a button to send the text, for chat purposes. But onto my question, how do I even start to lay this out? I understand I need a layout, but can someone help me on this? Here is my code at the moment (this code only sets up painting to the whole screen at the moment, need to divide the screen up now like I have in the picture above):
public class Setup extends JFrame implements Runnable{
JPanel panel;
JFrame window;
public Setup(Starter start, JFrame window){
window.setSize(600,500);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
panel = new Display(start);
this.window = window;
}
public void run(){
window.getContentPane().add(panel);
window.setBackground(Color.BLACK);
window.setVisible(true);
}
}
"new Display(start)" - this extends jpanel, its basically where I paint everything graphics wise.
In addition, I've seen people add in different panels but I cant have them be the same size. Like in the picture, the "paint graphics here" panel is the biggest one, and so on.
The JPanel is actually only a container where you can put different elements in it (even other JPanels). So in your case I would suggest one big JPanel as some sort of main container for your window. That main panel you assign a Layout that suits your needs ( here is an introduction to the layouts).
After you set the layout to your main panel you can add the paint panel and the other JPanels you want (like those with the text in it..).
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel paintPanel = new JPanel();
JPanel textPanel = new JPanel();
mainPanel.add(paintPanel);
mainPanel.add(textPanel);
This is just an example that sorts all sub panels vertically (Y-Axis). So if you want some other stuff at the bottom of your mainPanel (maybe some icons or buttons) that should be organized with another layout (like a horizontal layout), just create again a new JPanel as a container for all the other stuff and set setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS).
As you will find out, the layouts are quite rigid and it may be difficult to find the best layout for your panels. So don't give up, read the introduction (the link above) and look at the pictures – this is how I do it :)
Or you can just use NetBeans to write your program. There you have a pretty easy visual editor (drag and drop) to create all sorts of Windows and Frames. (only understanding the code afterwards is ... tricky sometimes.)
EDIT
Since there are some many people interested in this question, I wanted to provide a complete example of how to layout a JFrame to make it look like OP wants it to.
The class is called MyFrame and extends swings JFrame
public class MyFrame extends javax.swing.JFrame{
// these are the components we need.
private final JSplitPane splitPane; // split the window in top and bottom
private final JPanel topPanel; // container panel for the top
private final JPanel bottomPanel; // container panel for the bottom
private final JScrollPane scrollPane; // makes the text scrollable
private final JTextArea textArea; // the text
private final JPanel inputPanel; // under the text a container for all the input elements
private final JTextField textField; // a textField for the text the user inputs
private final JButton button; // and a "send" button
public MyFrame(){
// first, lets create the containers:
// the splitPane devides the window in two components (here: top and bottom)
// users can then move the devider and decide how much of the top component
// and how much of the bottom component they want to see.
splitPane = new JSplitPane();
topPanel = new JPanel(); // our top component
bottomPanel = new JPanel(); // our bottom component
// in our bottom panel we want the text area and the input components
scrollPane = new JScrollPane(); // this scrollPane is used to make the text area scrollable
textArea = new JTextArea(); // this text area will be put inside the scrollPane
// the input components will be put in a separate panel
inputPanel = new JPanel();
textField = new JTextField(); // first the input field where the user can type his text
button = new JButton("send"); // and a button at the right, to send the text
// now lets define the default size of our window and its layout:
setPreferredSize(new Dimension(400, 400)); // let's open the window with a default size of 400x400 pixels
// the contentPane is the container that holds all our components
getContentPane().setLayout(new GridLayout()); // the default GridLayout is like a grid with 1 column and 1 row,
// we only add one element to the window itself
getContentPane().add(splitPane); // due to the GridLayout, our splitPane will now fill the whole window
// let's configure our splitPane:
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); // we want it to split the window verticaly
splitPane.setDividerLocation(200); // the initial position of the divider is 200 (our window is 400 pixels high)
splitPane.setTopComponent(topPanel); // at the top we want our "topPanel"
splitPane.setBottomComponent(bottomPanel); // and at the bottom we want our "bottomPanel"
// our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically
bottomPanel.add(scrollPane); // first we add the scrollPane to the bottomPanel, so it is at the top
scrollPane.setViewportView(textArea); // the scrollPane should make the textArea scrollable, so we define the viewport
bottomPanel.add(inputPanel); // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea
// let's set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); // we set the max height to 75 and the max width to (almost) unlimited
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS)); // X_Axis will arrange the content horizontally
inputPanel.add(textField); // left will be the textField
inputPanel.add(button); // and right the "send" button
pack(); // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
}
public static void main(String args[]){
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
new MyFrame().setVisible(true);
}
});
}
}
Please be aware that this is only an example and there are multiple approaches to layout a window. It all depends on your needs and if you want the content to be resizable / responsive. Another really good approach would be the GridBagLayout which can handle quite complex layouting, but which is also quite complex to learn.
You'll want to use a number of layout managers to help you achieve the basic results you want.
Check out A Visual Guide to Layout Managers for a comparision.
You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.
You could use a series of compound layout managers instead.
I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.
I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)
I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.
But that's me

How to align the bottom of 3 JLabels that are held in a JPanel

I am trying to align the bottom of 3 JLabels that contain an image. The 3 JLabels are held in one big JPanel.
I found a tutorial about GUI using Java Swing here. But for some reason if i apply the example code (that is given for buttons) it doesn't work on the JLabels or JPanel.
This is the example code from the Oracle website:
button1.setAlignmentY(Component.BOTTOM_ALIGNMENT);
button2.setAlignmentY(Component.BOTTOM_ALIGNMENT);
Any idea what went wrong? I could send my code, but I thought maybe that would make it too confusing for what might be a simple answer too an easy question for most of you out here.
Thanks in advance.
EDIT:
public class LayoutOef_01 extends JFrame{
JPanel paneel;
JLabel label1, label2, label3;
ImageIcon pic1, pic2, pic3;
Border panelBord, labelBord;
public Layout_01(String titel){
super(titel);
paneel = new JPanel();
pic1 = new ImageIcon("images/simon1.png");
pic2 = new ImageIcon("images/simon2.png");
pic3 = new ImageIcon("images/simon3.png");
label1 = new JLabel(pic1);
label2 = new JLabel(pic2);
label3 = new JLabel(pic3);
paneel.add(label1);
paneel.add(label2);
paneel.add(label3);
panelBoord = BorderFactory.createLineBorder(Color.WHITE, 30);
paneel.setBorder(panelBord);
paneel.setBackground(Color.WHITE);
labelBoord = BorderFactory.createLineBorder(Color.BLACK, 2);
label1.setBorder(labelBord);
label2.setBorder(labelBord);
label3.setBorder(labelBord);
this.getContentPane().add(paneel);
this.pack();
}
public static void main(String[] args) {
Layout_01 lay1 = new LayoutOef_01("Layout_01");
lay1.setVisible(true);
}
}
So i tried placing the following code -in different places- inside the code above, but nothing changes:
label1.setAlignmentY(Component.BOTTOM_ALIGNMENT);
label2.setAlignmentY(Component.BOTTOM_ALIGNMENT);
label3.setAlignmentY(Component.BOTTOM_ALIGNMENT);
Check this sample: http://www.java2s.com/Code/JavaAPI/java.awt/ComponentBOTTOMALIGNMENT.htm
Remember to:
- set the layout on the panel.
- set the alignment on the button
- add the button to the panel.

Categories

Resources