Java GUI Moving buttons to bottom of the page - java

I was wondering how I would move my buttons to the bottom of the frame/window.
What I have now is this:
And what I want it to look like is this:
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Font;
public class checkbook{
static JButton Button[] = new JButton[8];
JLabel begin, accountName, balance;
JFrame frame;
JPanel jpanel, jpanel1;
Container contentPane;
private JTextField textAccount, textBalance;
public static void main(String[] args){
checkbook checkbook = new checkbook();
checkbook.startFrame();
}
checkbook(){
frame = new JFrame("Checkbook");
}
public void startFrame(){
String bottomButtons[] = {
"Create a New Account", "Load Trans from a file", "Add New Transactions", "Search Transactions",
"Sort Transactions", "View/Delete Transactions", "Backup Transactions", "Exit"
};
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
Font beginFont = new Font("Arial", Font.PLAIN + Font.BOLD, 22);
textAccount = new JTextField(" ", 15);
textBalance = new JTextField("0.0", 15);
begin = new JLabel("Use The Buttons below To Manage Transactions");
begin.setFont(beginFont);
contentPane.add(begin);
//Container contentPane1 = frame.getContentPane();
//contentPane1.setLayout(new FlowLayout());
JPanel jpanel = new JPanel();
accountName = new JLabel ("Account Name: ");
jpanel.add(accountName);
jpanel.add(textAccount);
balance = new JLabel ("Balance: ");
jpanel.add(balance);
jpanel.add(textBalance);
JPanel jpanel1 = new JPanel();
jpanel1.setLayout(new GridLayout(2,4));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
jpanel1.add(Button[i]);
//Button[i].addActionListener(AL);
}
frame.pack();
frame.setSize(800, 300);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(jpanel);
frame.add(jpanel1);
}
}
So I was wondering what would I do to move the buttons down to the bottom. Would I have to use a BorderLayout and use BorderLayout.SOUTH etc or is there a way to do this with the GridLayout I already have. If I have to use the BorderLayout how would I keep my buttons in order (2 rows, 4 columns).

Would I have to use a BorderLayout and use BorderLayout.SOUTH
Yes, but the best answer is for you to try it and see what happens. Why don't you?
If I have to use the BorderLayout how would I keep my buttons in order(2 rows, 4 columns).
Nest JPanels. Put the buttons in a GridLayout using JPanel, and place that JPanel BorderLayout.SOUTH, or better, BorderLayout.PAGE_END
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class NestedPanels extends JPanel {
private static final String TITLE_TEXT = "Use The Buttons Below To Manage Transactions";
private static final String[] BTN_TEXTS = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
private static final int TITLE_POINTS = 24;
public NestedPanels() {
JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD,
TITLE_POINTS));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(20));
accountBalancePanel.add(new JLabel("Balance:"));
accountBalancePanel.add(new JTextField(10));
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for (String btnText : BTN_TEXTS) {
southBtnPanel.add(new JButton(btnText));
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(400, 400))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
NestedPanels mainPanel = new NestedPanels();
JFrame frame = new JFrame("Nested Panels Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which displays as:

Related

JScrollPane not showing in my JTextArea

I have a JTextArea named as txtChat which is used as the chatting area in my chatbot. I have created a JScrollPane scroll = new JScrollPane(txtChat) and added my txtChat inside the JScrollPane. My JTextArea is being put inside a Panel which has BorderLayout, so I have added my scroll to the panel which contains my JTextArea chatPanel.add(scroll, BorderLayout.East). BUT IT IS NOT WORKING! Like when my conversation go longer, the scroll does not appear!
Sorry the code is quite long, so I just pasted the essential parts here.
public class GUI_V3 extends JFrame {
//mainPanel into Frame
private JPanel mainPanel = new JPanel();
//clock component
private JTextField timeF = new JTextField(8);
//Button component
private Box btnBox = Box.createHorizontalBox();
private JButton button1 = new JButton("Add Keywords");
private JButton button2 = new JButton("Help");
//Top menu bar
private JPanel topPanel = new JPanel();
//Typing Area
private JTextField txtEnter = new JTextField();
//Typing Panel
private JPanel typingPanel = new JPanel();
//Chat Area
private JTextArea txtChat = new JTextArea();
private JPanel chatPanel = new JPanel();
//Scroll
private JScrollPane scroll = new JScrollPane(txtChat);
private String name;
private Conversation_V3 convo = new Conversation_V3();
public GUI_V3(){
//Frame attributes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000,1000);
this.setVisible(true);
//this.setResizable(false);
this.setLocationRelativeTo(null);
this.setTitle("Welcome to Haidilao");
//clock attributes
timeF.setEditable(false);
timeF.setFont(new Font("Arial",Font.BOLD,48));
timeF.setBackground(new Color(228,224,199));
timeF.setHorizontalAlignment(SwingConstants.RIGHT);
//button attributes
button1.setFont(new Font("Arial",Font.PLAIN,38));
button2.setFont(new Font("Arial",Font.PLAIN,38));
btnBox.add(button1);
btnBox.add(Box.createRigidArea(new Dimension(10,70)));
btnBox.add(button2);
//Add ActionListener to buttons
Button1Handler handlerB1 = new Button1Handler();
button1.addActionListener(handlerB1);
Button2Handler handlerB2 = new Button2Handler();
button2.addActionListener(handlerB2);
//Top menu bar
topPanel.setLayout(new BorderLayout());
topPanel.add(btnBox, BorderLayout.WEST);
topPanel.add(timeF, BorderLayout.EAST);
topPanel.setBackground(new Color(228,224,199));
//Typing Area Attribute
txtEnter.setFont(new Font("DejaVu Sans",Font.PLAIN,30));
typingPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
typingPanel.setLayout(new BorderLayout());
typingPanel.setBackground(new Color(228,224,199));
typingPanel.add(txtEnter);
//Add action listener for typing area
TypingHandler handlerT = new TypingHandler();
txtEnter.addActionListener(handlerT);
//Chat Area Attribute
txtChat.setEditable(false);
txtChat.setFont(new Font("DejaVu Sans",Font.PLAIN,30));
txtChat.setLineWrap(true);
txtChat.setWrapStyleWord(true);
chatPanel.setBorder(BorderFactory.createEmptyBorder(5,20,10,20));
chatPanel.setLayout(new BorderLayout());
chatPanel.setBackground(new Color(228,224,199));
chatPanel.add(txtChat, BorderLayout.CENTER);
chatPanel.add(scroll, BorderLayout.EAST);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//mainPanel Layout
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(typingPanel, BorderLayout.SOUTH);
mainPanel.add(chatPanel, BorderLayout.CENTER);
//Add components to the JFrame
this.add(mainPanel);
//Add actionListener to clock
ClockHandler handlerC = new ClockHandler();
Timer t = new Timer(500, handlerC);
t.start();
//display greetings and ask for name
name = greetings();
addText(botSays("Welcome! " + name + ", you can ask me anything about the menu by providing keywords."));
}
//Action handler for txtEnter
private class TypingHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//grab input
String input = txtEnter.getText();
//add to chat area
txtChat.append(name + ": " + input + "\n");
//set input field to empty
txtEnter.setText("");
SoundEffect.music();
convo.setInput(input);
addText(botSays(convo.getReply()));
//set the chat area to bottom of scroll
txtChat.setCaretPosition(txtChat.getDocument().getLength());
}
}
Please find a working solution and tweak this as per your requirements.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
}
}
Hope this will be helpful. :-)

How can I get the contents of my GUI to look a certain way? (Java)

So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:

Break line around JPanel section

Hello I am trying to add a border or a line break separating the north section from the rest of the JPanel. Basically using set border I have a border around the whole window but then want a line from one section of the border straight across horizontally to the other side. when i add a border to a JPanel that is added to BorderLayout.NORTH it puts a whole border inside the section. not the outline of the section. hope you know what i mean.
Attached I have a section of my code that is holding all my JPanel code in it so far. any help I would love, thanks.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class GamePanel extends JPanel {
private JTextPane playertext;
private JTextField wealthstring, currentwealth;
public GamePanel() {
super();
setLayout(new BorderLayout());
setBackground(Game.getBackgroundColor());
Border raised = BorderFactory.createRaisedBevelBorder();
Border lowered = BorderFactory.createLoweredBevelBorder();
setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(4, 4, 4, 4), (BorderFactory.createCompoundBorder(raised, lowered))));
add(northpanel(), BorderLayout.NORTH);
add(eastpanel(), BorderLayout.EAST);
}
private JPanel northpanel() {
Font northfont = new Font("Engravers MT", Font.BOLD, 12);
playertext = new JTextPane();
playertext.setFont(northfont);
playertext.setEditable(false);
playertext.setText("Player: \n" + Game.getName());
playertext.setBackground(Game.getBackgroundColor());
playertext.setBorder(new EmptyBorder(10,10,10,10));
wealthstring = new JTextField("Money: ");
wealthstring.setFont(northfont);
wealthstring.setEditable(false);
wealthstring.setHorizontalAlignment(wealthstring.RIGHT);
wealthstring.setBorder(null);
wealthstring.setBackground(Game.getBackgroundColor());
currentwealth = new JTextField();
currentwealth.setFont(northfont);
currentwealth.setEditable(false);
currentwealth.setHorizontalAlignment(wealthstring.RIGHT);
currentwealth.setBackground(Game.getBackgroundColor());
currentwealth.setBorder(null);
String wealthrounded = String.format("%.2f", Game.getMoney());
currentwealth.setText(wealthrounded);
JPanel wealthtext = new JPanel();
wealthtext.setLayout(new GridLayout(2, 1));
wealthtext.setBackground(Game.getBackgroundColor());
wealthtext.setBorder(new EmptyBorder(10,10,10,10));
wealthtext.add(wealthstring);
wealthtext.add(currentwealth);
JPanel northpanel = new JPanel();
northpanel.setLayout(new BorderLayout());
northpanel.setBackground(Game.getBackgroundColor());
northpanel.add(playertext, BorderLayout.WEST);
northpanel.add(wealthtext, BorderLayout.EAST);
return northpanel;
}
private JPanel eastpanel() {
JButton tab1 = new JButton("Tab 1");
JButton tab2 = new JButton("Tab 2");
JButton tab3 = new JButton("Tab 3");
JPanel easttabs = new JPanel();
easttabs.setLayout(new GridLayout(1, 3));
easttabs.add(tab1);
easttabs.add(tab2);
easttabs.add(tab3);
JPanel eastpanels = new JPanel();
eastpanels.setLayout(new BorderLayout());
eastpanels.add(easttabs, BorderLayout.NORTH);
return eastpanels;
}
}
Like this?
For that we would use a JSeparator.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class UnderlinePageStart {
private JComponent ui = null;
UnderlinePageStart() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel pageStart = new JPanel(new BorderLayout(2,2));
ui.add(pageStart, BorderLayout.PAGE_START);
pageStart.add(new JLabel("Page Start", SwingConstants.CENTER));
// add a 'horizontal line'
pageStart.add(new JSeparator(), BorderLayout.PAGE_END);
ui.add(new JScrollPane(new JTextArea(5, 25)));
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
UnderlinePageStart o = new UnderlinePageStart();
JFrame f = new JFrame("Underline Page Start");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Placing of JPanels on the JFrames is not correct

I wrote a program to compose a GUI using swing/awt framework for my assignment. So far, I am able to get the pieces working together, but when I put them all into a JFrame, they are not coming out as expected.
I have recently started working on Java GUI framework, and not sure what is missing in my code. How can I get this working properly?
I am also attaching the screen shots (see at the bottom) of the output I am getting.
public class MainFrame extends JFrame {
public MainFrame() {
addComponentsToPane(this.getContentPane());
}
private void addComponentsToPane(Container pane) {
// Set layout
GridBagConstraints gbc = new GridBagConstraints();
this.setTitle("Test tool");
this.setSize(600, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2, 1));
// Add video JComponent
mMainPanel = new MainPanel();
pane.add(mMainPanel, 0);
// Add conference screen panel
mFeedPanel = new FeedPanel();
pane.add(mFeedPanel, 1);
// Add a button panel
mButtonPanel = new ButtonPanel();
pane.add(mButtonPanel, 2);
this.setResizable(true);
this.setVisible(true);
this.pack();
}
}
// In actual output, there is 1 screen in this panel.
// mScreen1 is derived from JComponent object.
public class MainPanel() extends JPanel {
public MainPanel() {
addMainPanelComponents();
}
private void addMainPanelComponents() {
this.setSize(352, 240);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 2));
add(mScreen);
setVisible(true);
}
}
// In actual output, there are 3 screens in this panel. I have shown code for 1 screen only
// mScreen1 is derived from JComponent object.
public class FeedPanel extends JPanel {
public FeedPanel() {
addFeedPanelComponents();
}
private void addFeedPanelComponents() {
String img1 = "images/screen1.png";
setSize(352, 150);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 3));
Image image1 = ImageIO.read(new File(img1));
mScreen1.setImage(image1);
add(mScreen1);
setVisible(true);
}
}
public class ButtonPanel extends JPanel {
public ButtonPanel() {
addButtonPanelComponents();
}
private void addButtonPanelComponents() {
this.setSize(352, 150);
this.setBackground(Color.yellow);
this.setLayout(new GridLayout(1,
5));
// Add Button to panel
mStartButton = new JButton("Start");
this.add(mStartButton);
mStartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StartButtonActionListener(ae);
}
});
mStopButton = new JButton("Stop");
this.add(mStopButton);
mStopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StopButtonActionListener(ae);
}
});
setVisible(true);
}
}
This comes by default on running the code.
This comes after manually resizing the frame.
The combination of BorderLayout , GirdLayout and BoxLayout can do this for you(Actually it's not the only choice).
Here is the code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridLayoutTest {
public void createUI(){
JFrame frame = new JFrame();
JPanel topPanel = new TopPanel();
JPanel buttomPanel = new ButtomPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel,BorderLayout.CENTER);
mainPanel.add(buttomPanel,BorderLayout.SOUTH);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
GridLayoutTest test = new GridLayoutTest();
test.createUI();
}
#SuppressWarnings("serial")
class TopPanel extends JPanel{
public TopPanel(){
setLayout(new GridLayout(2, 3));
ImageIcon icon = new ImageIcon("capture.png");
JLabel label1 = new JLabel(icon);
label1.setVisible(false);
JLabel label2 = new JLabel(icon);
JLabel label3 = new JLabel(icon);
label3.setVisible(false);
JLabel label4 = new JLabel(icon);
JLabel label5 = new JLabel(icon);
JLabel label6 = new JLabel(icon);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);
add(label6);
}
}
#SuppressWarnings("serial")
class ButtomPanel extends JPanel{
public ButtomPanel(){
JButton startButton = new JButton("start");
JButton stopButton = new JButton("stop");
JButton recordButton = new JButton("record");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
}
}
}
BoxLayout is so good too provide white space and help you to center the component.
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
Add Glue before the first component and after the last component will help you too center the component and add strut can help you to provide white space you want. you can refer to https://stackoverflow.com/a/22525005/3378204 for more details.
Here is the effect:
The BoxLayout won't affect your component's size. Hope it can help you.
Try this :
public class Main{
private JFrame f;
private JLabel l1, l2, l3,l4;
private JPanel p1, p2, p3;
private JButton b1, b2, b3;
public Main(){
this.f = new JFrame();
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.f.setLayout(new GridLayout(3,1));
this.p1 = new JPanel();
this.p1.setLayout(null)
this.p1.setSize(yoursize);
this.l1 = new JLabel();
this.l1.setBounds(x,y,xspan,yspan);
this.p1.add(l1);
this.p2 = new JPanel();
this.p2.setLayout(new GridLayout(1,3));
this.l2 = new JLabel();
this.l3 = new JLabel();
this.l4 = new JLabel();
this.p2.add(l2);
this.p2.add(l3);
this.p2.add(l4);
this.p3 = new JPanel();
this.p3.setLayout(new GridLayout(1,3));
this.b1 = new JButton();
this.b2 = new JButton();
this.b3 = new JButton();
this.p3.add(b1);
this.p3.add(b2);
this.p3.add(b3);
this.f.add(p1);
this.f.add(p2);
this.f.add(p3);
this.f.pack();
this.f.setResizeable(false)
}}
Add your video components instead of labels and you can change the color of the components as you wish.
Also if you want more control over the size and position of the components, use null layout and place them individually using setBounds() function as once shown in the program above. It is surely time consuming but makes the layout perfect.

about layouts in simple calculator

hi there i am trying to make a calculator with coding sizes,layouts etc. by myself (trying to not use NetBeans and it is not a homework). but i am facing with a problem about empty spaces. i have a TextArea and Buttons but as you can see below i cant handle this space problem. here is my code,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
public class calculator extends JFrame {
public calculator(){
initComponents();
}
private void initComponents(){
JPanel panelScreen = new JPanel(new GridLayout(0,1));
JTextArea screen = new JTextArea();
panelScreen.add(screen);
JFrame frame = new JFrame("CALCULATOR");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panelButtons = new JPanel(new GridLayout(3,3));
JButton oneButton = new JButton("1");
panelButtons.add(oneButton);
JButton twoButton = new JButton("2");
panelButtons.add(twoButton);
JButton threeButton = new JButton("3");
panelButtons.add(threeButton);
JButton fourButton = new JButton("4");
panelButtons.add(fourButton);
JButton fiveButton = new JButton("5");
panelButtons.add(fiveButton);
JButton sixButton = new JButton("6");
panelButtons.add(sixButton);
JButton sevenButton = new JButton("7");
panelButtons.add(sevenButton);
JButton eightButton = new JButton("8");
panelButtons.add(eightButton);
JButton nineButton = new JButton("9");
panelButtons.add(nineButton);
frame.getContentPane().add(panelScreen, BorderLayout.NORTH);
//frame.getContentPane().add(new JSeparator(), BorderLayout.CENTER);
frame.getContentPane().add(panelButtons, BorderLayout.SOUTH);
frame.setBounds(50, 50, 500, 500);
frame.setResizable(false);
//frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new calculator();
}
}
and this the picture of programme;
i appreciate if you can help me. anyway thanks :)
A few suggestions:
Don't set the JFrame's size, and in fact don't set any sizes.
Call pack to all the components to set their own sizes.
If you want the buttons bigger, consider changing the size of their fonts.
e.g.,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
public class Calc2 {
public static final String[][] BUTTON_TEXTS = {
{"7", "8", "9", "+"},
{"4", "5", "6", "-"},
{"1", "2", "3", "*"},
{"0", ".", "/", "="}
};
public static final Font BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 24);
private static void createAndShowGui() {
JTextField field = new JTextField(10);
field.setFont(BTN_FONT.deriveFont(Font.PLAIN));
JPanel btnPanel = new JPanel(new GridLayout(BUTTON_TEXTS.length,
BUTTON_TEXTS[0].length));
for (int i = 0; i < BUTTON_TEXTS.length; i++) {
for (int j = 0; j < BUTTON_TEXTS[i].length; j++) {
JButton btn = new JButton(BUTTON_TEXTS[i][j]);
btn.setFont(BTN_FONT);
btnPanel.add(btn);
}
}
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(field, BorderLayout.PAGE_START);
mainPanel.add(btnPanel, BorderLayout.CENTER);
JFrame frame = new JFrame("Calc2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
// no need to extend frame!
//public class Calculator extends JFrame {
public class Calculator {
public Calculator(){
initComponents();
}
private void initComponents(){
// I find it easier to create a panel and SET it as the content pane
JPanel gui = new JPanel(new BorderLayout(5,5));
// add some padding to the main GUI
gui.setBorder(new EmptyBorder(4,4,4,4));
// not needed if only a single compoinent is to be added!
//JPanel panelScreen = new JPanel(new GridLayout(0,1));
// add some constraints to make the output field bigger.
// if it is intended to be single line, a JTextField should be used.
JTextArea screen = new JTextArea(2,25);
gui.add(screen, BorderLayout.NORTH);
//panelScreen.add(screen);
JFrame frame = new JFrame("CALCULATOR");
frame.setContentPane(gui);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add padding around the buttons
JPanel panelButtons = new JPanel(new GridLayout(3,3,4,4));
JButton oneButton = new JButton("1");
panelButtons.add(oneButton);
JButton twoButton = new JButton("2");
panelButtons.add(twoButton);
JButton threeButton = new JButton("3");
panelButtons.add(threeButton);
JButton fourButton = new JButton("4");
panelButtons.add(fourButton);
JButton fiveButton = new JButton("5");
panelButtons.add(fiveButton);
JButton sixButton = new JButton("6");
panelButtons.add(sixButton);
JButton sevenButton = new JButton("7");
panelButtons.add(sevenButton);
JButton eightButton = new JButton("8");
panelButtons.add(eightButton);
JButton nineButton = new JButton("9");
panelButtons.add(nineButton);
//frame.getContentPane().add(new JSeparator(), BorderLayout.CENTER);
// Add the buttons to the CENTER and they will
// fill whatever space they are provided.
gui.add(panelButtons, BorderLayout.CENTER);
//frame.setBounds(50, 50, 500, 500);
//frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Calculator();
}
});
}
}
You might like to study this example that follows the suggestions of #HFOE and #mre. Note that "size" appears nowhere in the code.
Read Laying Out Components Within a Container
Implement appropriate layout(s)
EDIT -
Quick solution - replace the JFrame layout manager with BoxLayout (i.e. setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS))).

Categories

Resources