This might be a very stupid question posted at the dead of the night. I am trying to create two JButtons placed one on top of the other. However for some reason, it is not getting properly aligned. The left edge of the bottom button b2 appears slightly to the left of the left edge of top bottom b1.
Here is the code:
class thistrial extends JPanel implements ActionListener
{
...
public thistrial()
{
.....
add(new JSeparator(SwingConstants.HORIZONTAL));
//ADD THE START AND STOP BUTTONS
Border raisedBorder = BorderFactory.createRaisedBevelBorder();
b1 = new JButton("START");
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.CENTER);
b1.setPreferredSize(new Dimension(220,100));
add(new JSeparator(SwingConstants.HORIZONTAL));
b2 = new JButton("STOP");
b2.setPreferredSize(new Dimension(220,100));
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
add(b1);
add(b2);
.............
}
}
/** MAIN function **/
public static void main(String args[])
{
//Create and set up the window.
JFrame frame = new JFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setSize(398,480);
frame.setLocation(300,200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
thistrial newContentPane = new thistrial();
frame.setContentPane(newContentPane);
//Display the window.
frame.setVisible(true);
}
What can I do about it?
Your example extends JPanel, which uses FlowLayout by default. Instead, you might try GridLayout, as shown in A Visual Guide to Layout Managers.
I'd suggest using the right layout manager. Your code shows none.
Related
I am trying to get a JInternalFrame to appear on my screen when a button is pressed, a pop up effect basically. However when the button is pressed the JInternalFrame does not appear on the screen. Also when I resize the screen all the elements expand with it, I am wondering if there is a way to get a pop up window to appear on the screen and keep the layout manager I have now still in place so that when the window is resized the elements are also resized with it
public class testing2 implements ActionListener {
JButton buttonAppear = new JButton();
JLayeredPane LayeredPane = new JLayeredPane();
public static void main(String[] args) {
new testing2();
}
public testing2() {
LayeredPane = new JLayeredPane();
BorderLayout borderlayoutpane = new BorderLayout();
LayeredPane.setLayout(borderlayoutpane);
JPanel mainPanel = new JPanel();
BorderLayout borderlayout = new BorderLayout();
mainPanel.setLayout(borderlayout);
JButton button = new JButton("Button");
mainPanel.add(button, "Center");
buttonAppear = new JButton("Panel Appear");
buttonAppear.addActionListener(this);
mainPanel.add(buttonAppear, "South");
LayeredPane.add(mainPanel, 2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(LayeredPane);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == buttonAppear)
{
JInternalFrame inFrame = new JInternalFrame("Internal Frame", true, true, true, true);
inFrame.setBounds(10, 10, 200, 200);
inFrame.setVisible(true);
LayeredPane.add(inFrame, 1);
}
}
}
a pop up effect basically.
Then use a JDialog. A JInternalFrame was designed to work with a JDesktopPane.
mainPanel.add(button, "Center");
Don't use hardcode strings for the constraint. Use the field provided by the API:
mainPanel.add(button, BorderLayout.CENTER);
Also, follow Java naming conventions. Variable names should NOT start with an upper case character. Be consistent.
Don't know if it will make a difference but components with a higher layer number are painted on top of components with a lower index. So I would guess the panel (which is opaque) would just paint over top of the internal frame. Read the section from the Swing tutorial on How to Use Layered Panes. Also read the section on How to Use Root Panes to find the special variable for "popups" on a layered pane.
I have to align a button on my program to the exact middle, the current code I have runs it but displays the button as large as the program, I am wanting a center button that is a specific size, here is what I tried
/**
* Created by Timk9 on 11/04/2016.
*/
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
{
JFrame window = new JFrame("Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(true);
window.setSize(600, 600);
window.setVisible(true);
window.setLocationRelativeTo(null);
JPanel p = new JPanel(new GridBagLayout());
//Button does not appear until I resize the program?
JButton b1 = new JButton("Click here");
GridBagConstraints c = new GridBagConstraints();
p.add(b1);
window.add(p);
}
public static void main(String[] args) {
new Test();
}
}
JPanel p = new JPanel(new GridBagLayout());
You create a panel with a GridBagLayout which is a good layout manager to use to center the component.
p.add(b1);
But then you add the button to the panel without using any contraints.
The code should be:
p.add(b1, c);
//Button does not appear until I resize the program?
All components should be added to the frame BEFORE the frame is made visible. The setVisible(...) statement should be the last statement of the constructor.
Also could you point out which part is an instance initializer block, I thought I was using a constructor
See the FrameDemo example from the Swing tutorial on How to Make Frames for a better way to structure your code so you follow Swing conventions. Start with the working code and make the changes to add your panel containing the button, instead of using the JLabel. Note you no longer need to use the getContentPane() method, you can just add the panel directly to the frame.
It is the LayoutManager that defines how components are layed out where and how big. GridLayout which you are using e. g. divides the available space in equal grid fields and makes the components completely fill this space which is why your button is as big as your application. See here for more info about LayoutManagers: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Btw. your code is not compilable: new JButton("he"),JButton.ALIGN_CENTER)
I am trying to get a JInternalFrame to appear on my screen when a button is pressed, a pop up effect basically. However when the button is pressed the JInternalFrame does not appear on the screen. Also when I resize the screen all the elements expand with it, I am wondering if there is a way to get a pop up window to appear on the screen and keep the layout manager I have now still in place so that when the window is resized the elements are also resized with it
public class testing2 implements ActionListener {
JButton buttonAppear = new JButton();
JLayeredPane LayeredPane = new JLayeredPane();
public static void main(String[] args) {
new testing2();
}
public testing2() {
LayeredPane = new JLayeredPane();
BorderLayout borderlayoutpane = new BorderLayout();
LayeredPane.setLayout(borderlayoutpane);
JPanel mainPanel = new JPanel();
BorderLayout borderlayout = new BorderLayout();
mainPanel.setLayout(borderlayout);
JButton button = new JButton("Button");
mainPanel.add(button, "Center");
buttonAppear = new JButton("Panel Appear");
buttonAppear.addActionListener(this);
mainPanel.add(buttonAppear, "South");
LayeredPane.add(mainPanel, 2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(LayeredPane);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == buttonAppear)
{
JInternalFrame inFrame = new JInternalFrame("Internal Frame", true, true, true, true);
inFrame.setBounds(10, 10, 200, 200);
inFrame.setVisible(true);
LayeredPane.add(inFrame, 1);
}
}
}
a pop up effect basically.
Then use a JDialog. A JInternalFrame was designed to work with a JDesktopPane.
mainPanel.add(button, "Center");
Don't use hardcode strings for the constraint. Use the field provided by the API:
mainPanel.add(button, BorderLayout.CENTER);
Also, follow Java naming conventions. Variable names should NOT start with an upper case character. Be consistent.
Don't know if it will make a difference but components with a higher layer number are painted on top of components with a lower index. So I would guess the panel (which is opaque) would just paint over top of the internal frame. Read the section from the Swing tutorial on How to Use Layered Panes. Also read the section on How to Use Root Panes to find the special variable for "popups" on a layered pane.
I've been spending some time relearning java and a peculiar logic error hit me here.
import javax.swing.*;
import java.awt.*;
class Frame
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
Container content = frame.getContentPane();
content.setBackground(Color.blue);
content.add(btn1);
content.add(btn2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//end main
}
I've created 2 JButton objects, and they should be the same size, with different location and text. This of course is not the case, the "FOO" button is exactly where and how I want it to be, but the "BAR" button is the size of the entire frame.
Help!
1) You are attempting to use Absolute LayoutManager via setSize and setLocation etc, but without calling setLayout(null) on the component you are adding the JButtons to. However this is not a best practice in Swing.
When adding to JFrame contentpane default layout is BorderLayout which adds components to is default position of BorderLayout.CENTER.
Have a read on A Visual Guide to Layout Managers
2) Also when using a correct LayoutManager you would omit JFrame#setSize(..) call and replace it with JFrame#pack() before setting the JFrame visible.
3) Also have a read on Concurrency in Swing specifically on The Event Dispatch Thread
which dictates all swing components be created on EDT via SwingUtillities.invokeXXX(..) block:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//create and manipulate swing components here
}
});
4) Also rather use JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); as this will allow any other threads timers etc to carry on execution even after JFrame has been disposed.
add:
frame.getContentPane().setLayout(null);
To your code after the line:
frame.setSize(400, 500);
Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).In your code the buttons are stacked over the other.That is why you get this Error(as you think it is).
This will solve your problem:-
import javax.swing.*;
import java.awt.*;
class OP3
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
JPanel p = new JPanel(new FlowLayout());
p.add(btn1);
p.add(btn2);
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//end main
}
Just add a panel to the frame and add the buttons to the panel.
import javax.swing.*;
import java.awt.*;
class source
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JPanel panel=new JPanel();//panel added here
panel.setSize(frame.size());
panel.setLocation(0, 0);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
panel.add(btn1);
panel.add(btn2);
Container content = frame.getContentPane();
content.setBackground(Color.blue);
content.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//endmain
Is it possible to have some extra space around the edges of a JFrame that uses AbsoluteLayout? When I have a button as the downwardsmost component on the JFrame, it gets positioned right up against the bottom edge of the JFrame window, and it looks bad. I would like to know if there's a way to add a little extra space between components and the edge of the JFrame while using AbsoluteLayout.
Suggestions:
When you add a component to a JFrame, you're actually adding it to the JFrame's contentPane. To give the contentPane a "buffer" border, consider giving it an EmptyBorder(...) with the parameters being int constants for the amount of border desired around the component.
Avoid using "absolute" layouts for anything, and especially for placing components at easy to place locations for the layout managers, such as at the bottom of the GUI.
For example, note in the GUI created in the code below how the center and bottom JPanel's don't go out to the edge of the GUI because of the empty border:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
public class ButtonAtBottom {
private static void createAndShowGui() {
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton("Bottom Button"));
bottomPanel.setBorder(BorderFactory.createTitledBorder("Bottom Panel"));
JPanel centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createTitledBorder("Center Panel"));
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
// **** here I add the border to the mainPanel which I'll
// make into the contentPane
int eb = 25;
mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
// don't set the preferredSize per Kleopatra, but am doing it
// here simply to make code shorter for this sscce
mainPanel.setPreferredSize(new Dimension(500, 400));
JFrame frame = new JFrame("ButtonAtBottom");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You can use Box.createRigidArea(dimensions) to create an empty space that you can add below the button.
Set an empty border on your content panel where SIZE is the amount of padding you want.
JFrame frame = new JFrame();
JPanel panel = new JPanel(null);
panel.setBorder(BorderFactory.createEmptyBorder(SIZE,SIZE,SIZE,SIZE);
frame.setContentPane(panel);
//The rest
The arguments are for top, left, bottom and right padding so if you want different paddings on each edge, you can set it accordingly.