Java GUI - buttons will not add to panel - java

Hello I am having a problem adding buttons to my GUI, I try to use BorderLayout to add the buttons but it does not show when I run. Since using BorderLayout my choice of background color reverts to white as well. Can anyone please help?
import javax.swing.*;
import java.awt.*;
public class BlackjackGUI{
private JFrame frame;
private JPanel panel;
private JButton newGameBtn, dealBtn, hitBtn, standBtn;
private JLabel playerMoneyLbl;
private JLabel playerCard1Lbl, playerCard2Lbl, playerCard3Lbl,
playerCard4Lbl, playerCard5Lbl, playerCard6Lbl, playerCard7Lbl;
private JLabel dealerCard1Lbl, dealerCard2Lbl, dealerCard3Lbl, dealerCard4Lbl,
dealerCard5Lbl, dealerCard6Lbl, dealerCard7Lbl;
private JLabel playerCardValueLbl, dealerCardValueLbl;
private JTextField betInputBox;
public BlackjackGUI(){
createForm();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createForm() {
JFrame frame = new JFrame("Blackjack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200,800);
frame.setVisible(true);
JPanel panel = new JPanel();
Color c = new Color(0, 100, 0);
panel.setBackground(c);
panel.setLayout(new BorderLayout());
}
public void addButtons() {
newGameBtn = new JButton("New Game");
panel.add(newGameBtn, BorderLayout.NORTH);
}
public static void main(String[] args) {
new BlackjackGUI();
}
}

Related

Adding a panel to a JFrame

There are no errors in the code but i cant seem to see the Jlabels in the window. Im not sure if the panel was added or if the jlabels were added to the panel .
public class JDemoResistance extends JFrame{
private final JButton button1;
private JPanel panel;
private final int WINDOW_WIDTH = 320;
private final int WINDOW_HEIGHT = 320;
public JDemoResistance() {
super("JDemoResistance");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JLabels Configs
JLabel label1 = new JLabel("Too expensive");
JLabel label2 = new JLabel("Bad reviews");
JLabel label3 = new JLabel("Bad quality");
JLabel label4 = new JLabel("Not worth it");
JLabel label5 = new JLabel("Dosent work");
//Button Configs
button1 = new JButton("Button");
button1.addActionListener(new ButtonListener());
//Panel Configs
panel = new JPanel();
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel.add(label5);
panel.add(button1);
setVisible(true);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e){
}
}
public static void main(String[] args) {
JDemoResistance jdr = new JDemoResistance();
}
}
You haven't added the panel to the frame, that's why you can't see any of the components. Add it before setting the JFrame visible.
//Add the panel to the frame
this.add(panel)
setVisible(true);
You must add the panel to the JFrame as well.
panel.add(...);
add(panel); // <-- you forgot this
setVisible(true);

How to add a button to a JFrame Gui

I'm trying to add a button to a frame gui.
i tried making a panel and adding it to that, but it does not work.
please help!
here is my code:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button;
JPanel panel;
// my error lines are under the "panel" and "button"
// it says i must implement the variables. what does that mean???
panel.add(button);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
Change:
JButton button;
JPanel panel;
to:
JButton button = new JButton();
JPanel panel = new JPanel();
You can also pass a String value in JButton() constructor for that string value to be shown on the JButton.
Example: JButton button = new JButton("I am a JButton");
Example Code:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
// Create JButton and JPanel
JButton button = new JButton("Click here!");
JPanel panel = new JPanel();
// Add button to JPanel
panel.add(button);
// And JPanel needs to be added to the JFrame itself!
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
Output:
Note:
Create the JButton and JPanel using new JButton("..."); and new JPanel()
Add the JPanel to the JFrame's content pane using getContentPane().add(...);
If you can Change this Program, You can adjust the button place also
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class agui extends JFrame
{
agui()
{
setTitle("My GUI");
setSize(400,400);
setLayout(null);
JButton button = new JButton("Click Here..!");
button.setBounds(50,100,100,50); /*Distance from left,
Distance from top,length of button, height of button*/
add(button);
setVisible(true);
}
public static void main(String[] args)
{
JFrame agui = new agui();
}
}
Output

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.

Align text and icon differently in JLabel

i'm trying to create a JLabel that has text aligned left and icon aligned right, i tried this code:
_ip = new JLabel(ip);
_ip.setFont(boldFont);
_ip.setBounds(5, 0, 100, 50);
_ip.setIcon(images.ipBan);
_ip.setBorder(BorderFactory.createLineBorder(Color.black, 1));
_ip.setHorizontalTextPosition(SwingConstants.LEFT);
add(_ip);
And this is what i get:
The red image shows the actual image alignment, the gray one shows where i want my image to be.
If i add
_ip.setAlignmentX(JLabel.RIGHT_ALIGNMENT);
Nothing happens, and if i add
_ip.setHorizontalAlignment(JLabel.RIGHT);
Icon is aligned right, but also text is aligned right, and i want it to align left
Is there a way to do it?
Alternatively, you can use a JPanel with a suitable layout, as shown here.
please DYM???
import java.awt.*;
import javax.swing.*;
public class CenteredJLabel {
private JFrame frame = new JFrame("Test");
private JPanel panel = new JPanel();
private JLabel label = new JLabel("CenteredJLabel");
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
public CenteredJLabel() {
panel.setLayout(new GridBagLayout());
panel.add(label);
label.setHorizontalAlignment(SwingConstants.LEFT);
label.setVerticalAlignment(SwingConstants.CENTER);
label.setIcon(errorIcon);
label.setIconTextGap(20);
label.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CenteredJLabel centeredJLabel = new CenteredJLabel();
}
});
}
}
EDIT
import java.awt.*;
import javax.swing.*;
public class CenteredJLabel {
private JFrame frame = new JFrame("Test");
private JPanel panel = new JPanel();
private JLabel labelOne = new JLabel("CenteredJLabel");
private JLabel labelTwo = new JLabel("1.1.1.1");
private JLabel labelThree = new JLabel("192.168.255.255");
private JLabel labelFour = new JLabel("192.168.255.255");
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
private Icon questnIcon = UIManager.getIcon("OptionPane.questionIcon");
private JPanel panelTwo = new JPanel();
public CenteredJLabel() {
panel.setLayout(new GridLayout(4, 0, 10, 10));
labelOne.setHorizontalAlignment(SwingConstants.LEFT);
labelOne.setVerticalAlignment(SwingConstants.CENTER);
labelOne.setIcon(errorIcon);
labelOne.setIconTextGap(20);
labelOne.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
panel.add(labelOne);
labelTwo.setHorizontalAlignment(SwingConstants.LEFT);
labelTwo.setVerticalAlignment(SwingConstants.CENTER);
labelTwo.setIcon(infoIcon);
labelTwo.setIconTextGap(20);
labelTwo.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
panel.add(labelTwo);
labelThree.setHorizontalAlignment(SwingConstants.LEFT);
labelThree.setVerticalAlignment(SwingConstants.CENTER);
labelThree.setIcon(warnIcon);
labelThree.setIconTextGap(20);
labelThree.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
panel.add(labelThree);
panelTwo.setLayout(new BorderLayout());
panelTwo.setOpaque(false);
panelTwo.add(labelFour, BorderLayout.WEST);
panelTwo.add(new JLabel(questnIcon), BorderLayout.EAST);
panel.add(panelTwo);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CenteredJLabel centeredJLabel = new CenteredJLabel();
}
});
}
}

Swing Methods on submission of button

How to close current frame (Frame1) and open a new frame (Frame2) already created and pass the data to frame2 from frame1 on the clicking of button?
Use a CardLayout1. Either that or one JFrame and one or more JDialog2 instances.
How to Use CardLayout
How to Make Dialogs
The very best way to accomplish this, is very much told to you by #Andrew Thompson.
And the other way to accomplish, the motive of the question as described in the code. Here as you make object of your new JFrame, you have to pass the things you need in the other class as an argument to the other class, or you can simply pass the object(with this you be passing everything in one go to the other class)
A sample code for a bit of help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFramesExample
{
public JFrame frame;
private JPanel panel;
private JButton button;
private JTextField tfield;
private SecondFrame secondFrame;
public TwoFramesExample()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
tfield = new JTextField(10);
tfield.setBackground(Color.BLACK);
tfield.setForeground(Color.WHITE);
button = new JButton("NEXT");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Here we are passing the contents of the JTextField to another class
// so that it can be shown on the label of the other JFrame.
secondFrame = new SecondFrame(tfield.getText());
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(tfield, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFramesExample();
}
});
}
}
class SecondFrame
{
private JFrame frame;
private JPanel panel;
private JLabel label;
private JButton button;
private TwoFramesExample firstFrame;
public SecondFrame(String text)
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
label = new JLabel(text);
button = new JButton("BACK");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
firstFrame = new TwoFramesExample();
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(label, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
}
Hope this be of some help.
Regards

Categories

Resources