I'm learning how to make GUIs in Java. Right now what I'm trying to do is make a small box with 2 buttons next to each other (with maybe.. 10px of padding between them) inside a JPanel. When I run this program in JGrasp I just get an empty window. What am I doing wrong?
MyButtons.java
import javax.swing.*;
import java.awt.*;
public class MyButtons extends JFrame{
public MyButtons(){
JPanel pnlMain = new JPanel();
this.setTitle("MyButtons");
JButton btn1 = new JButton("Button 1");
JButton btn2 = new JButton("Button 2");
pnlMain.add(btn1);
pnlMain.add(btn2);
this.add(pnlMain);
}
}
TestMyButtons.java
import javax.swing.*; // for JFrame, JPanel, JLabel, JTextField,
import java.awt.*; // for BorderLayout
public class TestMyButtons {
public static void main(String[] args) {
MyButtons test = new MyButtons();
test.setVisible(true);
test.setSize(1000,300);
test.setLocation(200,300);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
EDIT: Revised to show the correct code. Answer marked below. All I did was add one line to the bottom of MyButtons.Java >.<
You must also add the pnlMain to the JFrame's content pane or set it as content pane of the frame.
Create Button's Object as given below.
JButton btn1 = new JButton("Button 1");
JButton btn2 = new JButton("Button 2");
Related
I want to make a JButton that lies on the NorthPane of the frame, but when I run the program there's no button. Why does it do that?
I'm using IntelliJ IDEA.
BTW I'm posting this question again, cause the first time I didn't get the desired answer.
Here's my code.
package com.company;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
class Fantasyrpglifesim implements JButton {
Fantasyrpglifesim() {
}
public static void main(String[] args) {
MouseInputAdapter();
//Frame//
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.setSize(1500, 1500);
frame.getContentPane();
frame.setVisible(true);
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel northPanel = new JPanel();
mainPanel.add(northPanel,BorderLayout.NORTH );
//frame.setLayout(new FlowLayout());//
//Buttons//
frame.add(BUTTON);
BUTTON.setText("Age up");
northPanel.add(BUTTON);
northPanel.add(BUTTON1);
BUTTON1.setText("Test");
northPanel.add(BUTTON2);
BUTTON2.setText("Test1");
northPanel.add(BUTTON2);
BUTTON2.setText("Test2");
northPanel.add(BUTTON3);
BUTTON3.setText("Test3");
northPanel.add(BUTTON4);
BUTTON4.setText("Test4");
northPanel.add(BUTTON5);
BUTTON5.setText("Test5");
northPanel.add(BUTTON6);
BUTTON6.setText("Test6");
northPanel.add(BUTTON7);
BUTTON7.setText("Test7");
northPanel.add(BUTTON8);
BUTTON8.setText("Test8");
northPanel.add(BUTTON9);
BUTTON9.setText("Test9");
northPanel.add(BUTTON10);
BUTTON10.setText("Test10");
northPanel.add(BUTTON11);
BUTTON11.setText("Test11");
northPanel.add(BUTTON12);
BUTTON12.setText("Test12");
northPanel.add(BUTTON13);
BUTTON13.setText("Test13");
northPanel.setVisible(true);
//panels//
//mainPanel.add(northPanel, BorderLayout.NORTH);//
}
private static void MouseInputAdapter() {
}
}
to add a JButton you have to create a JButton object and add that to the JPanel.
And you need to define it for EVERY button that you want to have.
anywhere. I'm surprised your compiler isn't flagging that
Anyway what you want should look sth like this
JButton testButton = new JButton("test");
northPanel.add(testButton);
First, I want you to check your compiler and IntelliJ cause they're not working if you can run the code you posted.
You cannot implement a JButton unless you have made an interface yourself.
Cause the JButton is not an interface.
No need to set a BorderLayout for your JPanel. FlowLayout will do the job.
Use a for loop to avoid duplicate code.
Learn how to use Swing components.
import javax.swing.*;
import java.awt.*;
class Fantasyrpglifesim {
private static int count = 1;
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton age = new JButton("Age up");
mainPanel.add(age);
for (int x=0; x<14;x++){
JButton button = new JButton();
button.setText("Test"+ count++);
mainPanel.add(button);
}
frame.getContentPane().add(BorderLayout.NORTH,mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1500, 1500);
frame.setVisible(true);
}
}
Is this your desired output?
Im rather new at Java, I am have created a home page and a few buttons, When i click one of the buttons it sets the homepage panel visibility to false, opens a new class and sets that classes Jpanel to visible.
homePanel.setVisible(false);
Goodsin Barcode = new Goodsin();
Goodsin.setVisible(true);
However once it opens the new class "Goodsin" it wont show any of the Buttons or TextFileds. I know it is opening the new class as a System.out.println prints to the console but nothing displays in the JFrame and i do not know why.
Here is my code of the new class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Goodsin {
public JPanel Goodsin;
public JTextField item1;
public String code;
public JButton btn1;
public Goodsin() {
System.out.println("TEST");
Goodsin = new JPanel();
item1 = new JTextField(10);
btn1 = new JButton("Look up Barcode");
Goodsin.setVisible(true);
Goodsin.add(item1);
item1.setSize(80, 30);
Goodsin.add(btn1);
btn1.setSize(80, 30);
}
public void getString(String code) {
System.out.println(code);
}
}
Im sure i am not doing something correct with the Jpanel or adding the textfields or button but all the answers i have seen so far havnt worked.
I suggest you add your panels to a JFrame. You can either do this by extending JFrame from the class or simply instantiating one in your constructor. Then you can simply add and remove (or set visible/invisible) as you wish. Be sure to validate your JFrame/JPanel after changing visibility though.
Try to do something like this:
Goodsin = new JPanel();
item1 = new JTextField(10);
btn1 = new JButton("Look up Barcode");
item1.setSize(80, 30);
Goodsin.add(item1);
btn1.setSize(80, 30);
Goodsin.add(btn1);
JFrame frame = new JFrame("JFrame Example");
Goodsin.setLayout(new FlowLayout());
frame.add(Goodsin);
I suggest you try the following code :
public class Goodsin extends JFrame{
public static void main(String[] args) {
Goodsin ui = new Goodsin();
JTextField item1 = new JTextField(10);
JButton btn1 = new JButton("Look up Barcode");
JPanel centralPanel = new JPanel(new FlowLayout());
centralPanel.add(item1);
centralPanel.add(btn1);
item1.setSize(80, 30);
btn1.setSize(80, 30);
ui.add(centralPanel);
ui.pack();
ui.setVisible(true);
}
}
Everything is done in the main method in my example, however you still can improve this code and refactor it in a better way.
just you have to set Bounds of Goodsin panel or set Size and add in home page frame
im trying to design java GUI frame which contains labels, textfields, radio buttons and button..
i want to position each component in specific place tried setBounds() but it didn't work..
also im trying to change background color of the frame using getContentPane().setBackground(Color.white) and setBackground(Color.white) but didnt work too.
how to do it ?
this is my code :
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class test extends JFrame{
public static void main(String[] args) {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("WHO IS THE WINNER");
guiFrame.setSize(700,500);
guiFrame.setLocationRelativeTo(null);
final JPanel first = new JPanel();
JLabel un = new JLabel("UserName:");
JTextField textField = new JTextField(20);
JLabel sn = new JLabel("Server Name:");
JTextField textField2 = new JTextField(20);
un.setLabelFor(textField);
sn.setLabelFor(textField2);
first.add(un);
first.add(textField);
first.add(sn);
first.add(textField2);
final JPanel second = new JPanel();
JLabel level = new JLabel("Level:");
JLabel score = new JLabel("Score:");
JLabel question = new JLabel("Question:");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox radio1 = new Checkbox("True", radioGroup,false);
Checkbox radio2 = new Checkbox("False", radioGroup,true);
second.add(score);
second.add(level);
second.add(question);
second.add(radio1);
second.add(radio2);
JButton next = new JButton( "Next");
next.addActionListener(
new ActionListener() {
#Override public void actionPerformed(ActionEvent event) {
first.setVisible(false);
} });
guiFrame.add(first, BorderLayout.NORTH);
guiFrame.add(second, BorderLayout.CENTER);
guiFrame.add(next,BorderLayout.SOUTH);
guiFrame.setVisible(true);
}
}
for the positioning for example i want the first label and text field under them the other label and text field not beside them.. same for other labels and radio buttons i don't want them it be beside each other i want o give them a specific position to be in..
can someone please help ?
Thanks :)
This answer is just for Eclipse IDE.
An easy way to place all the widgets is doing it from the Design tab, placed at the bottom-left side of the window. Just change from Source perspective to Design perspective. It will open a simple panel with everything you need. Just drag the different widgets and place them in their position.
To change the background of the frame, do it from the properties of the frame in the Design tab or add the following code to the constructor of the panel:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
I understand how to create radio buttons and I understand how to create a text area. What I have trouble with is combing the two onto one frame.
Can anyone help me or show me how to do so? Do I have to layout a grid with boarders?
Here I was trying to follow my text book on ways to combine the two but I sort of failed. :(
I've tried other ways but none have worked for me. When I attempt to do the text area and radio buttons separately, they work.
This isn't my final code. My finish product should allow me to keep track of how many times a certain student is picked, like a vote, and printing out the totals in the text area each time.
Getting this part to work will help me further advance in my code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class AsnTwo extends JFrame
{
private JRadioButton jrbS1 = new JRadioButton("Student 1");
private JRadioButton jrbS2 = new JRadioButton("Student 2");
private JRadioButton jrbS3 = new JRadioButton("Student 3");
private JTextArea jtaT = new JTextArea("Hello");
public static void main(String[] args)
{
AsnTwo frame = new AsnTwo();
JPanel panel = new JPanel();
frame.pack();
frame.setTitle("Assignment Two");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public AsnTwo()
{
JPanel jpTextArea = new JPanel();
jpTextArea.setLayout(new GridLayout(2,1));
jtaT.setEditable(false);
jtaT.setLineWrap(true);
jtaT.setText("Something");
add(jpTextArea, BorderLayout.EAST);
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(3,1));
jpRadioButtons.add(jrbS1);
jpRadioButtons.add(jrbS2);
jpRadioButtons.add(jrbS3);
add(jpRadioButtons, BorderLayout.WEST);//Adds buttons to GUI
ButtonGroup group = new ButtonGroup();
group.add(jrbS1);
group.add(jrbS2);
group.add(jrbS3);
}
public void printTextField(String text)
{
jtaT.setText("Hello");
}
}
Never mind. I got it. I just had to change
add(jpTextArea, BorderLayout.EAST);
to
add(jtaT, BorderLayout.EAST);
I'm trying to do a little program that use some buttons and text field.
I was able to create window with JPanel but don't have idea how to add button and text field
The code I'm using is:
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,SZEROKOSC,WYSOKOSC);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
panel.add(this);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextField pole = new JTextField(10);
JButton przycisk = new JButton("teasda");
przycisk.setPreferredSize(new Dimension(300, 350));
przycisk.setLayout(new BorderLayout());
panel.add(przycisk);
przycisk.setVisible(true);
pole.setBounds (300,300,200,200);
pole.setLayout(null);
pole.setVisible(true);
panel.add(pole);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
// addMouseListener(this);
}
You need to use the layout properly, when using border layout you need to tell it which border to use (, BorderLayout.NORTH or something), check out the tutorials at oracles page.
P.S. Think of how your naming your fields etc. Naming something "przycisk" just gives me a reason not to read the code further.
Thank You for help and sorry for Polish names(fixed already).
I was able to add Text Area with scroll.
Looks like problem was in panel.add(this); putted before button and text field.
From my understanding if panel.add(this) is set before panel.add(pole); then panel.add(this) is set in front and pole is added but not seen.
Below my actual working code:
...
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,WIDTH,HEIGHT);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextArea pole = new JTextArea();
pole.setLayout(null);
pole.setLineWrap(true);
//pole.setBackground(Color.BLACK);
pole.setEditable(false);
JScrollPane scroll = new JScrollPane(pole);
scroll.setBounds(25,250,500,300);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll);
panel.add(this);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
addMouseListener(this);
}
...
This code is from this site: Example of Java GUI
//Imports are listed in full to show what's being used
//could just import javax.swing.* and java.awt.* etc..
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GuiApp1 {
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
new GuiApp1();
}
public GuiApp1()
{
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Example GUI");
guiFrame.setSize(300,250);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//Options for the JComboBox
String[] fruitOptions = {"Apple", "Apricot", "Banana"
,"Cherry", "Date", "Kiwi", "Orange", "Pear", "Strawberry"};
//Options for the JList
String[] vegOptions = {"Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery", "Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish", "Shallot", "Spinach", "Swede"
, "Turnip"};
//The first JPanel contains a JLabel and JCombobox
final JPanel comboPanel = new JPanel();
JLabel comboLbl = new JLabel("Fruits:");
JComboBox fruits = new JComboBox(fruitOptions);
comboPanel.add(comboLbl);
comboPanel.add(fruits);
//Create the second JPanel. Add a JLabel and JList and
//make use the JPanel is not visible.
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
JList vegs = new JList(vegOptions);
vegs.setLayoutOrientation(JList.HORIZONTAL_WRAP);
listPanel.add(listLbl);
listPanel.add(vegs);
JButton vegFruitBut = new JButton( "Fruit or Veg");
//The ActionListener class is used to handle the
//event that happens when the user clicks the button.
//As there is not a lot that needs to happen we can
//define an anonymous inner class to make the code simpler.
vegFruitBut.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
//When the fruit of veg button is pressed
//the setVisible value of the listPanel and
//comboPanel is switched from true to
//value or vice versa.
listPanel.setVisible(!listPanel.isVisible());
comboPanel.setVisible(!comboPanel.isVisible());
}
});
//The JFrame uses the BorderLayout layout manager.
//Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
guiFrame.add(listPanel, BorderLayout.CENTER);
guiFrame.add(vegFruitBut,BorderLayout.SOUTH);
//make sure the JFrame is visible
guiFrame.setVisible(true);
}
}
For the future i will recommend you to use the extends JFrame so you can only write a gui like this without initialize a JFrame:
public class CalculatorGUI extends JFrame {
public CalculatorGUI() {
setTitle("Calculator");
setBounds(300, 300, 220, 200);
}}
I suggest you check out a couple of tutorials about how to create a Java Gui or sth.