Trying to make a JFrame with a JPanel containing two JButtons - java

I am a beginner here and I am trying to make a GUI that will display two buttons, addCard and deleteCard. However, the compiler is showing errors, and I cannot seem to find the error. Thank you in advance!
package studyfast;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Scratch{
JFrame projectFrame = new JFrame();
projectFrame.setSize(1000, 600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panelEditCard = new JPanel();
JButton addCard = new JButton();
JButton deleteCard = new JButton();
panelEditCard.add(addCard);
panelEditCard.add(deleteCard);
projectFrame.add(panelEditCard);
projectFrame.setVisible(true);
public static void main(String[] args){
new Scratch();
}
}

You need to move your code inside the Scratch class inside a constructor
package studyfast;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Scratch
{
JFrame projectFrame = new JFrame();
JPanel panelEditCard = new JPanel();
JButton addCard = new JButton();
JButton deleteCard = new JButton();
public Scratch()
{
projectFrame.setSize(1000, 600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
panelEditCard.add(addCard);
panelEditCard.add(deleteCard);
projectFrame.add(panelEditCard);
projectFrame.setVisible(true);
}
public static void main(String[] args)
{
new Scratch();
}
}

Related

I am having trouble implementing ActionListener, into a swing based GUI

I want to be able to detect when my button, ever so conveniently named button is clicked, I am having trouble making it be that way. here is some code
import java.awt.GridLayout;
import java.awt.event;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class Main implements ActionListener
//im having immense problems implementing the action listener.
{
public static void main(String[] args)
{
new GUI(); // calling in main.
System.out.print("test for bad wifi because my wifi hates me"); // I'm using a cloud based ide
}
JFrame frame1 = new JFrame();
JPanel panel1 = new JPanel();
JFrame frame2 = new JFrame(); //not in use yet
JPanel panel2 = new JPanel(); //""
public void GUI()
{
JButton button = new JButton("moment");
button.addActionListener(this);
panel1.setBorder(BorderFactory.createEmptyBorder( 30, 30, 30, 30 ));
panel1.setLayout(new GridLayout(0, 1));
panel1.add(button);
frame1.add(panel1, BorderLayout.CENTER); // frame is on the pannel or vice versa
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // funny close
frame1.setTitle("Final.");
frame1.pack();
frame1.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
}
}
Any help is appreciated
Download and use an IDE.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section.
The JFrame methods must be called in a specific order. This is the order I use for all my Swing applications.
Here's the complete runnable code I wound up with.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleJButtonExample implements ActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SimpleJButtonExample().createAndShowGUI(); // calling in main.
}
});
// I'm using a cloud based ide
System.out.println("test for bad wifi because my wifi hates me");
}
JFrame frame1 = new JFrame();
JPanel panel1 = new JPanel();
JFrame frame2 = new JFrame(); // not in use yet
JPanel panel2 = new JPanel(); // ""
public void createAndShowGUI() {
JButton button = new JButton("moment");
button.addActionListener(this);
panel1.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
panel1.setLayout(new GridLayout(0, 1));
panel1.add(button);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // funny close
frame1.setTitle("Final");
frame1.add(panel1, BorderLayout.CENTER); // panel is within the frame
frame1.pack();
frame1.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
}

Window displayed but not the buttons

I wrote this code to display a window with three buttons. However, the window appears but not the buttons. Here is the code:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.*;
public class Test3 extends JFrame{
public Test3() {
JFrame frame = new JFrame("Exemple");
JButton button1 = new JButton("Règles");
button1.setBounds(100, 60, 100, 30);
JButton button2 = new JButton("Jouer");
JButton button3 = new JButton("Scores");
JPanel pane1 = new JPanel(new GridLayout(0, 1));
this.setVisible(true);
pane1.add(button1);
pane1.add(button2);
pane1.add(button3);
frame.getContentPane().add(pane1, BorderLayout.EAST);
this.setVisible(true);
setSize(800, 600);
}
public static void main(String[] args) {
Test3 test3 = new Test3();
}
}
Does anyone have an idea on how to fix this ?
Thanks for your help !
Agnès
You have two windows...
public class Test3 extends JFrame{
public Test3() {
JFrame frame = new JFrame("Exemple");
You're adding content to frame, but showing Test3...
As a general rule of thumb, you should avoid extending from top level containers like JFrame and instead, create an instance when you need it. This unlocks you from a given implementation and allows you flexibility in deciding how you might re-use given components, as an example.
public class Test3 {
public Test3() {
JFrame frame = new JFrame("Exemple");
JButton button1 = new JButton("Règles");
JButton button2 = new JButton("Jouer");
JButton button3 = new JButton("Scores");
JPanel pane1 = new JPanel(new GridLayout(0, 1));
pane1.add(button1);
pane1.add(button2);
pane1.add(button3);
frame.getContentPane().add(pane1, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
Runnable example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test3 {
public Test3() {
JFrame frame = new JFrame("Exemple");
JButton button1 = new JButton("Règles");
button1.setBounds(100, 60, 100, 30);
JButton button2 = new JButton("Jouer");
JButton button3 = new JButton("Scores");
JPanel pane1 = new JPanel(new GridLayout(0, 1));
pane1.add(button1);
pane1.add(button2);
pane1.add(button3);
frame.getContentPane().add(pane1, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Test3 test3 = new Test3();
}
});
}
}
Please try like this, I have corrected
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.*;
public class Test3 extends JFrame{
public Test3() {
super("Exemple");
JButton button1 = new JButton("Règles");
button1.setBounds(100, 60, 100, 30);
JButton button2 = new JButton("Jouer");
JButton button3 = new JButton("Scores");
JPanel pane1 = new JPanel(new GridLayout(0, 1));
this.setVisible(true);
pane1.add(button1);
pane1.add(button2);
pane1.add(button3);
getContentPane().add(pane1, BorderLayout.EAST);
this.setVisible(true);
setSize(800, 600);
}
public static void main(String[] args) {
Test3 test3 = new Test3();
}
}

External JPanels called from a JFrame

A while back I started a project that soon built up a shed load of code, most of the code was made up of components and their properties. All was going well until I hit an error. Off the top of head, the error was something on the line of exceeding the code limit of a constructor, roughly 65000 bytes.
This error has literally bought me and my project to halt. At the same time I have also found major problems in my understanding of SWING.
What I tried was to break my game code into logical sections, putting each section into a different class. For example, a jpanel which dealt with buying and selling would be its own .java file. Another jpanel that dealt with shipping would be in another .java file.
What I hoped to achieve was a JFrame that called each of these jpanels when the user requested it at the press of a jbutton. However, this didn't quite work as I wished, putting me in a position where I need help.
What I have done is simplified my problem by creating an example framework, hoping that somebody could point out what I need to be looking at, possibly even a solution.
I have created a JFrame which holds a panel called bg, which itself holds 2 JButtons (btn1 and btn2). In a different class file I have created a JPanel called panel1, and in another class again I have created another JPanel called panel2.
When the user opens the application they are presented with a frame and the option of two buttons, when any of these buttons are pressed I would like for either panel1 or
panel2 to open. How would this be done?
Any help would be greatly appreciated. Thanks in advance.
////////////// frame
package panel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame implements ActionListener {
public JPanel bg;
public static JButton btn1, btn2;
public Frame(){
JFrame f = new JFrame();
f.setSize(308, 205);
f.setLayout(null);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
bg = new JPanel();
bg.setSize(300, 200);
bg.setLocation(0, 0);
bg.setLayout(null);
bg.setBackground(Color.black);
bg.setVisible(true);
btn1 = new JButton("open 1");
btn1.setSize(135, 30);
btn1.setLocation(10, 10);
btn1.addActionListener(this);
btn2 = new JButton("open 2");
btn2.setSize(135, 30);
btn2.setLocation(155, 10);
btn2.addActionListener(this);
bg.add(btn1);
bg.add(btn2);
f.add(bg);
}
public static void main(String[] args) {
new Frame();
}
#Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == btn1){
}
if (a.getSource() == btn2){
}
}
}
////////////////////// panel1
package panel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class panel1 implements ActionListener {
public JButton btn3;
public panel1(){
JPanel a = new JPanel();
a.setSize(280, 110);
a.setLocation(155, 10);
a.setBackground(Color.red);
a.setVisible(true);
btn3 = new JButton("open bb");
btn3.setSize(100, 30);
btn3.setLocation(10, 10);
btn3.addActionListener(this);
a.add(btn3);
}
#Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == btn3){
}
}
}
//////////////////////////// panel2.java
package panel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class panel2 implements ActionListener {
public JButton btn4;
public panel2(){
JPanel b = new JPanel();
b.setSize(280, 110);
b.setLocation(155, 10);
b.setBackground(Color.blue);
b.setVisible(true);
btn4 = new JButton("open");
btn4.setSize(100, 30);
btn4.setLocation(10, 10);
btn4.addActionListener(this);
b.add(btn4);
}
#Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == btn4){
}
}
}
You don't need to split your panels into different classes for something this simple. Try keeping everything together:
package panel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame implements ActionListener {
public JPanel bg,panel1,panel2;
public static JButton btn1, btn2;
public Frame(){
JFrame f = new JFrame();
f.setSize(308, 205);
f.setLayout(null);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
bg = new JPanel();
bg.setSize(300, 200);
bg.setLocation(0, 0);
bg.setLayout(null);
bg.setBackground(Color.black);
bg.setVisible(true);
btn1 = new JButton("open 1");
btn1.setSize(135, 30);
btn1.setLocation(10, 10);
btn1.addActionListener(this);
btn2 = new JButton("open 2");
btn2.setSize(135, 30);
btn2.setLocation(155, 10);
btn2.addActionListener(this);
bg.add(btn1);
bg.add(btn2);
f.add(bg);
panel1 = new JPanel();
panel1.setSize(280, 110);
panel1.setLocation(155, 10);
panel1.setBackground(Color.red);
panel1.setVisible(false);
bg.add(panel1);
panel2 = new JPanel();
panel2.setSize(280, 110);
panel2.setLocation(155, 10);
panel2.setBackground(Color.blue);
panel2.setVisible(false);
bg.add(panel2);
}
public static void main(String[] args) {
new Frame();
}
#Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == btn1){
panel1.setVisible(true);panel2.setVisible(false);
}
if (a.getSource() == btn2){
panel1.setVisible(false);panel2.setVisible(true);
}
}
}

How to add JPanel to JFrame from different classes

How do i add the JPanel to JFrame? It is really confusing me. I want to add the JPanel to the JFrame. I've tried all sorts of things including the extend but I cant get it to work.
events
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class events {
public static void main (String args[]) {
Time timeObject = new Time();
JFrame mainJFrame;
mainJFrame = new JFrame();
mainJFrame.setLayout(BorderLayout());
mainJFrame.setVisible(true);
mainJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainJFrame.setSize(600,400);
mainJFrame.setVisible(true);
mainJFrame.setLayout(new BorderLayout());
mainJFrame.setTitle("Travel Agent System");
mainJFrame.setBackground(Color.BLUE);
timeObject.selectButton();
}
}
Time
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Time{
public static void selectButton()
JButton timeButton = new JButton("Time");
JButton moneyButton = new JButton("Money");
JButton hotelButton = new JButton("Hotel");
JButton exitButton = new JButton("Exit");
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.RED);
buttonPanel.add(timeButton,moneyButtons,hotelButton,exitButton);
}
Have a look over this source. Note the comments.
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class events {
public static void main (String args[]) {
Time timeObject = new Time();
JFrame mainJFrame;
mainJFrame = new JFrame();
// Coding by magic!
//mainJFrame.setLayout(BorderLayout());
mainJFrame.setLayout(new BorderLayout());
mainJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// don't do this, just call pack() later
//mainJFrame.setSize(600,400);
mainJFrame.setLayout(new BorderLayout());
mainJFrame.setTitle("Travel Agent System");
mainJFrame.setBackground(Color.BLUE);
timeObject.selectButton();
mainJFrame.add(timeObject.getGUI());
mainJFrame.pack();
// should be last.
mainJFrame.setVisible(true);
}
}
class Time {
private JPanel buttonPanel;
// don't use static unless necessary - it is not necessary.
//public static void selectButton() {
public void selectButton() {
JButton timeButton = new JButton("Time");
JButton moneyButton = new JButton("Money");
JButton hotelButton = new JButton("Hotel");
JButton exitButton = new JButton("Exit");
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.RED);
buttonPanel.add(timeButton);
buttonPanel.add(moneyButton);
buttonPanel.add(hotelButton);
buttonPanel.add(exitButton);
}
public JComponent getGUI() {
return buttonPanel;
}
}
Pass JFrame object to selectButton() :
timeObject.selectButton(mainJFrame);
Then use that JFrame object to add JPanel to it.
public static void selectButton(JFrame frame)
{
JButton timeButton = new JButton("Time");
JButton moneyButton = new JButton("Money");
JButton hotelButton = new JButton("Hotel");
JButton exitButton = new JButton("Exit");
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.RED);
buttonPanel.add(timeButton,moneyButtons,hotelButton,exitButton);
frame.getContentPane().add(buttonPanel,BorderLayout.CENTER); // i've added to CENTER.
}
This will add JPanel to CENTER of your JFrame.
Here is a good example of implementing a JFrame class and then adding JPanels to the JFrame and to other JPanels.
Link to another StackOverflow question/answer

Java - Program will not Compile/method getText(double)

My program is suppose to make a GUI that calculates the square root of a number that is entered. I can not figure out why this code will not compile. I keep getting the following error message:
cannot find symbol
symbol : method getText(double)
What am I doing wrong?
import java.awt.event.ActionEvent; //Next group of lines import various Java classes
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.text.*;
public class SquareRoot extends JFrame
{
public static void main(String[] args) {
//Creates Window
JFrame frame = new JFrame();
frame.setSize(450, 300);
frame.setTitle("Find the Square Root");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel Numberlbl = new JLabel("Enter a number:");
final JTextField NumberField = new JTextField(10);
NumberField.setText("");
JLabel Answerlbl = new JLabel("Square Root of your number is:");
final JTextField AnswerField = new JTextField(10);
AnswerField.setText("");
JLabel ButtonLabel = new JLabel("Calculate Square Root");
JButton button = new JButton("√");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(Numberlbl);
panel.add(NumberField);
panel.add(ButtonLabel);
panel.add(button);
panel.add(Answerlbl);
panel.add(AnswerField);
frame.add(panel);
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double NumberX = Double.parseDouble(NumberField.getText());
double Answer = Math.sqrt(NumberX);
AnswerField.setText(Answer);
}
}
ActionListener listener = new CalculateListener();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
The only compilation error I got was for the AnswerField.setText() line - if you look at the API reference for setText() it takes a string, but you are trying to pass it a double.
Have a look at the NumberFormat class for converting the double to a string correctly. A simpler option is to use a Double object (as opposed to the double data type, note capitalization), and use its toString() method. A down-and-dirty method is to write it as ("" + Answer), since it will auto-convert it for you.
The code will not compile because the method setText(String text) expects a String parameter, and you are giving it a double.
To make your code work, use:
AnswerField.setText(String.valueOf(Answer));
final Double answer = Math.sqrt(NumberX);
AnswerField.setText(answer.toString());
This one compiles. Here you go:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SquareRoot extends JFrame
{
public static void main(String[] args) {
//Creates Window
JFrame frame = new JFrame();
frame.setSize(450, 300);
frame.setTitle("Find the Square Root");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel numberlbl = new JLabel("Enter a number:");
final JTextField numberField = new JTextField(10);
numberField.setText("");
JLabel answerlbl = new JLabel("Square Root of your number is:");
final JTextField answerField = new JTextField(10);
answerField.setText("");
JLabel buttonLabel = new JLabel("Calculate Square Root");
JButton button = new JButton("√");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(numberlbl);
panel.add(numberField);
panel.add(buttonLabel);
panel.add(button);
panel.add(answerlbl);
panel.add(answerField);
frame.add(panel);
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double numberX = Double.parseDouble(numberField.getText());
double answer = Math.sqrt(numberX);
answerField.setText(""+answer);
}
}
ActionListener listener = new CalculateListener();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Categories

Resources