Button and textfield don't show up in Java - java

For school I had to make a JFrame and within that One button and Two textfields. Whatever you put in Textfield one have to get into textfield two when the button is pressed. I got the code to the point I should see the textfields and the button when i run the program. For whatever reason it doesn't.
My come so far:
package helloworld;
import javax.swing.*;
import java.awt.event.*;
public class HelloWorld extends JFrame {
public static void main(String[] args) {
JFrame frame = new HelloWorld();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hello World Button App");
JPanel panel = new JPanel();
frame.setContentPane(panel);
fram.setVisible(true);
}
}
class panel extends JPanel {
public JButton btn1 = new JButton("Klick!");
public JTextField txt1 = new JTextField(10);
public JTextField txt2 = new JTextField(10);
public panel() {
add(btn1);
add(txt1);
add(txt2);
}
}
I am not yet allowed to post images but I will provide a link to the picture down here
I am sorry if this question allready exests but i couldnt's find a similar question.
I am new to programming so please dont yell at me when I forgot something or wrote something wrong in it!

Here i have modified your code a bit, but did in a similar way.
I won't extend JFrame until and unless i don't want to do something creative, but you always CAN.
You had already extended JFrame , so no worth of calling methods with frame.foo()
but simply foo() , and most important JFrame frame = new HelloWorld() , will make no sense, if you have already extended you class with JFrame:
import javax.swing.*;
public class HelloWorld extends JFrame{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new HelloWorld().setVisible(true);
}
});
}
public HelloWorld()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Button App");
panel pan= new panel();
add(pan.panel);
pack();
setVisible(true);
}
}
class panel {
private JButton btn1 = new JButton("Klick!");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
JPanel panel;
public panel() {
panel = new JPanel();
panel.add(btn1);
panel.add(txt1);
panel.add(txt2);
}
}
Also, you can also extend your panel class with JPanel :
public HelloWorld()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Button App");
panel pan= new panel();
add(pan);
pack();
setVisible(true);
}
}
class panel extends JPanel {
private JButton btn1 = new JButton("Klick!");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
public panel() {
add(btn1);
add(txt1);
add(txt2);
}
}

That is because your class name is panel not JPanel
Modify this:
panel panel = new panel();
frame.setContentPane(panel);
frame.setVisible(true);
You should try to use names for your Class that are not so confusing, and try to declare them with uppercase.
Example:
Class Panel extends JPanel {}
Object:
Panel panel = new Panel()
Here you can clearly read which one is the class name and which is the object (instance of that class) of that class.

You declared a class called panel that you are not using anywhere. Please replace the line bwlow:
JPanel panel = new JPanel();
with:
SomePanel panel = new SomePanel();
Then, your class panel becomes SomePanel to follow correct class naming.
Some thoughts to help you:
Name your classes following the Java style
Don't use public fields
Set layouts on your panels. This time it worked for you as the default is FlowLayout.

Related

Java Swing JComboBox/ Button edit parameters

I am quite new to working with GUI in Java. I was trying several things, for example, adding a new entry to a JComboBox or changing a JButtons caption using the following commands in the run method:
pwSelection.addItem("Name 1");
dec_btn.setText("Example");
protected JComboBox pwSelection = new JComboBox(contents);
Unfortunately, none of it shows any effect as soon as I start the program.
The layout was made with the IntelliJ GUI Form Creator.
It would be great if you could give me any tips or alternative approaches.
package PackMain;
import javax.swing.*;
public class Password {
String[] contents = {"Name 1", "Name 2"};
protected JTextField newAdress;
protected JPanel panel1;
protected JComboBox pwSelection = new JComboBox(contents); // ?
protected JLabel title;
protected JTextField pwOutput;
protected JButton enc_btn;
protected JButton dec_btn;
public JFrame run(){
JFrame mainFrame= new JFrame ("Password");
mainFrame.setContentPane(new Password().panel1);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setSize(400, 200);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
pwSelection.addItem("Name 1");
dec_btn.setText("Example");
return mainFrame;
}
public static void main(String[] args){
new Password().run();
}
}
You're not adding any panel to the frame, also you didn't initialize any of the attributes...
package password;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class Password extends JFrame{
String[] contents = {"Name 1", "Name 2"};
protected JTextField newAdress;
protected JPanel panel1, panel2; //2 panels for a more organized approach...
protected JComboBox pwSelection;// ?
protected JTextField pwOutput;
protected JButton enc_btn;
protected JButton dec_btn;
public Password(){ //Constructor of the class, initialize stuff here...
super("Shinny title");
//1. Initialize all your atributtes...
newAdress = new JTextField();
panel1 = new JPanel();
panel2 = new JPanel();
pwSelection = new JComboBox(contents);
pwOutput= new JTextField();
enc_btn = new JButton("First button");
dec_btn = new JButton("Second Button");
//Set layouts..
panel1.setLayout(new GridLayout(3,1));
panel2.setLayout(new FlowLayout());
//Add items to panel 1...
panel1.add(new JLabel("Adress:")); //A more simple aproach for creating a label...
panel1.add(newAdress);
panel1.add(pwSelection);
panel1.add(enc_btn);
panel1.add(dec_btn);
panel1.add(pwOutput);
//Add items of panel 1 to panel 2...
panel2.add(panel1);
add(panel2);
setSize(300,300);
setVisible(true);
//Proper way of stop the application at closing...
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
//This is not necessary as everything should be implemented in the constructor.
/*
public JFrame run(){
JFrame mainFrame= new JFrame ("Password");
mainFrame.setContentPane(new Password().panel1);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setSize(400, 200);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
pwSelection.addItem("Name 1");
dec_btn.setText("Example");
setVisible(true);
return mainFrame;
}
*/
public static void main(String[] args){
//Initialize the constructor...
Password ps = new Password();
}
}
This will give you an idea of how the GUI on java can be implemented.
panel1 is never defined as a new JPanel(), so it's null, and all of your other components -- pwSelection, title, etc. -- have never been added to panel1.

add two JPanels to JFrame

I'm trying to add two JPanels to a Jframe, but it seems that they look like one. I'm trying tow stack them on top of each other like this image.
I thinking I may need to look at layout managers? I just need a little nudge in the right direction.
package projectTwo;
import javax.swing.*;
public class checkFrame
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Compose Message");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
checkPanel bob = new checkPanel();
//frame.add(bob);
frame.getContentPane().add(bob);
frame.setResizable(false);
frame.setSize(750, 500);
frame.setVisible(true);
}
}
package projectTwo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class checkPanel extends JPanel implements ActionListener
{
private JPanel entry, display;
private JLabel name, checkAmount, payOrderOf, numPrint, numWords;
private JTextField nameT, checkAmountT;
private JButton Submit;
public checkPanel()
{
entryComponents();
checkDisplay();
}
private void entryComponents(){
name = new JLabel("Name:");
checkAmount = new JLabel("Check Amount:");
nameT = new JTextField(20);
nameT.addActionListener(this);
checkAmountT = new JTextField(20);
checkAmountT.addActionListener(this);
Submit = new JButton("Submit");
Submit.addActionListener(this);
add(name);
add(nameT);
add(checkAmount);
add(checkAmountT);
add(Submit);
setPreferredSize(new Dimension(750, 75));
setBackground(new Color(200,200,200));
}
private void checkDisplay(){
payOrderOf = new JLabel("Pay to the Order of: ");
add(payOrderOf);
setBackground(new Color(220,255,225));
}
public void actionPerformed (ActionEvent event)
{
}
}
You should definitely take a look at layout managers. At the moment you are simply adding JPanels to each other without any specification on where they should be.
You have a few options in this case. You could use a GridLayout, but that leads to all the panels being the same size. If you just want two panels below each other, I would suggest using a BorderLayout. I've adjusted your code as follows:
public class checkPanel extends JPanel implements ActionListener
{
private JPanel entry, display;
private JLabel name, checkAmount, payOrderOf, numPrint, numWords;
private JTextField nameT, checkAmountT;
private JButton Submit;
public checkPanel()
{
this.setPreferredSize(new Dimension(750, 75));
entryComponents();
checkDisplay();
this.setLayout(new BorderLayout());
this.add(entry, BorderLayout.NORTH);
this.add(display, BorderLayout.CENTER);
}
private void entryComponents(){
entry = new JPanel();
// You should specify entry's layout as well FlowLayout are used by default
name = new JLabel("Name:");
checkAmount = new JLabel("Check Amount:");
nameT = new JTextField(20);
nameT.addActionListener(this);
checkAmountT = new JTextField(20);
checkAmountT.addActionListener(this);
Submit = new JButton("Submit");
Submit.addActionListener(this);
entry.add(name);
entry.add(nameT);
entry.add(checkAmount);
entry.add(checkAmountT);
entry.add(Submit);
entry.setBackground(new Color(200,200,200));
}
private void checkDisplay(){
display = new JPanel();
// You should specify display's layout as well FlowLayout are used by default
payOrderOf = new JLabel("Pay to the Order of: ");
display.add(payOrderOf);
display.setBackground(new Color(220,255,225));
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
It is in general a good idea to assign a layout to each JPanel you create. The choice of layout depends on how the panel should function.
using Gridbag Layout can help you a lot I would put a separator between panels as well

Constructing a class in java, adding labels to two seperate panels gui, driver class and main class

I am trying to add labels onto two different panels, using an oo method. But when i create the panels in my main class they cannot be seen in my driver class. I have just started to learn oo concepts. If i instantiate the panels in my driver class it works but not when I instantiate in the main class, which is the way I am being told.
Main Class
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class borderMain {
public static void main(String[] args) {
JFrame frame = new JFrame("Border Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
borderpanel p1 = new borderpanel();
borderpanel p2 = new borderpanel();
frame.getContentPane().add(p1, BorderLayout.NORTH);
frame.getContentPane().add(p2, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
Driver Class- When I do p1.add(lbl1); this is where I am getting the error
import java.awt.*;
import javax.swing.*;
public class borderpanel extends JPanel {
private JLabel lbl1, lbl2, lbl3;
private JTextField txt1;
public borderpanel(){
lbl1 = new JLabel("Hello");
lbl2 = new JLabel("Hi");
lbl3 = new JLabel("Hey");
txt1 = new JTextField("Hello");
p1.add(lbl1);
p2.add(lbl2);
p1.add(lbl3);
p2.add(txt1);
}
}
You are getting an error because you are trying to access variables in BorderMain class within the BorderPanel class. You cannot access variables in a one class from another class like this. According to your comment
I am trying to add lbl1, lbl2 to borderpanel p1 and the others to p2.
and if this is what you really need to do there is no need of having separate class as BorderPanel. You can do that like this.
BorderMain
public class BorderMain{
public static void main(String[] args){
JLabel lbl1, lbl2, lbl3;
JTextField txt1;
JFrame frame = new JFrame("Border Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
borderpanel p1 = new borderpanel();
borderpanel p2 = new borderpanel();
lbl1 = new JLabel("Hello");
lbl2 = new JLabel("Hi");
lbl3 = new JLabel("Hey");
txt1 = new JTextField("Hello");
p1.add(lbl1);
p2.add(lbl2);
p1.add(lbl3);
p2.add(txt1);
frame.getContentPane().add(p1, BorderLayout.NORTH);
frame.getContentPane().add(p2, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
BorderPanel
import java.awt.*;
import javax.swing.*;
public class BorderPanel extends JPanel {
public borderpanel(){}
}
But here BorderPanel is useless unless you are learning something regarding inheritance since it just a subclass of JPanel. You can do the same with JPanel also.
public borderpanel(String message, String message2){
lbl1 = new JLabel(message);
txt1 = new JTextField(message2);
}
Then you can have getters for the two fields lbl1 and txt1. Possibly then use the getters on the frame.getContentPane().add() method. Instead of having lbl1, lbl2 and lbl3, you can instead just instantiate the borderpanel; with p1 and p2.

Adding onto JPanel

I was wondering if it was possible to add dropdown menus to a main JPanel from a different class instead of calling it from that class itself. Mainly because a friend and I are working on a personal project trying to create different programs in different tabs.
Here's our main GUI:
public class GUI extends JFrame {
public GUI() {
setTitle("Andy and Jack's favorite programs");
JTabbedPane jtp = new JTabbedPane();
getContentPane().add(jtp);
JPanel jp1 = new JPanel();
JLabel label1 = new JLabel();
JPanel jp2 = new JPanel();
JLabel label2 = new JLabel();
jp1.add(label1);
jtp.addTab("Andy - Encryption Program");
jp2.add(label2);
jtp.addTab("Andy - Hello World Program");
}
public static void main(String[] args) {
GUI tp = new GUI();
tp.setVisible(true);
tp.setMinimumSize(new Dimension(400, 400));
}
Here's one of our tabs:
public class encryptionPrograms extends GUI {
String[] options = new String[] { "XOR", "RSA" };
ComboBox optionsList = new JComboBox(options);
jp1.add(optionsList, BorderLayout.CENTER);
}
I'm not sure if I'm doing it correctly or not. Just got into Java and we've have been playing around with the GUI buttons and such.
There is a lot of "wrong" here and without you saying what your intention is with adding a comboBox to your jPanel it's hard to tell you the right way to do it but yes it can be done.
But first of: Always declare your variables before you initialize them so that you can access them for other methods in the class:
public class GUI extends JFrame{
private JPanel jp1,jp2;
private JLabel label1,label2;
private JTabbedPane jtp;
public GUI() {
setTitle("Andy and Jack's favorite programs");
jtp = new JTabbedPane();
jp1 = new JPanel();
label1 = new JLabel();
jp2 = new JPanel();
label2 = new JLabel();
jp1.add(label1);
jtp.addTab("Andy - Encryption Program", jp1);
jp2.add(label2);
jtp.addTab("Andy - Hello World Program",jp2);
getContentPane().add(jtp);
}
If you need to access a variable from another class you can write a get method for it.
For example:
public JPanel getMainJPanel(){
return jp1;
}
Now you can call the getMainJPanel() from another class in order to, for instance, add components to it. Just remember to .revalidate() and .repaint() the main frame after adding more components.

Java syntax for separating action listeners

Please help me out to separate these ActionListeners in a periodic table that I am attempting to complete. When I execute the program and click on 'H', it opens all the other elements and when the others are clicked, it does not work. So I need a way to separate these using any method...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PeriodicTable
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Elements");
frame.setVisible(true);
frame.setSize(1000,1500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("H");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("He");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Li");
panel.add(button3);
button3.addActionListener (new Action2());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("H");
frame2.setVisible(true);
frame2.setSize(1000,1500);
JLabel label = new JLabel("Hydrogen");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("He");
frame3.setVisible(true);
frame3.setSize(1000,1500);
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Li");
frame4.setVisible(true);
frame4.setSize(1000,1500);
JLabel label = new JLabel("Lithium");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
}
Thanks in advance.
(note: only the first 3 elements are coded for...)
When I execute the program and click on 'H', it opens all other elements
Only one frame opens for me.
and when the others are clicked, it does not work.
Each button opens a single frame for me.
However, button 3 opens the wrong frame because you add the wrong listener to the button:
//button3.addActionListener (new Action2());
button3.addActionListener (new Action3());
Other issues:
You should add the components to the frame BEFORE making the frame visible.
Don't hardcode screen sizes, you never know what size screen other users will be using
So the order of your code might be something like:
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame("He");
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
And of course you really don't want to create dozens of separate ActionListeners. You want to make the listener more generic so it can be shared.
Something like:
static class Action implements ActionListener
{
public Action(String element, String description)
{
this.element = element;
this.description = description;
}
public void actionPerformed (ActionEvent e)
{
JLabel label = new JLabel(description);
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame(element);
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
}
}
Then when you create the listener you use:
button3.addActionListener (new Action("HE", "Helium"));

Categories

Resources