add cannot be resolved to a variable - java

Please let me state that this is for a homework assignment and any help would be appreciated.
I am am writing a program using Eclipse (Juno) that creates a frame, places a ball in the top of the frame and places a row of buttons on the 'south' of the border frame. The issue I am having is in the class that adds the buttons, called Btns.java, I am receiving some errors.
Error 1: add cannot be resolved to a variable
Error 2: Constructor call must be the first statement in a constructor
Error 3: Syntax error on token ".", super expected after this token
The code looks correct to me never the less.
The code for the Btns class is below.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Btns extends JFrame
{
public Btns()
{
JButton jbtL = new JButton("Left");
JButton jbtR = new JButton("Right");
JButton jbtU = new JButton("Up");
JButton jbtD = new JButton("Down");
JButton jbtRd = new JButton("Red");
JButton jbtG = new JButton("Green");
add.(jbtL);
add.(jbtR);
add.(jbtU);
add.(jbtD);
add.(jbtRd);
add.(jbtG);
}
}
Lab2.java Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Lab2 extends JFrame {
public Lab2()
{
setLayout(new BorderLayout());
add(new Ball(), BorderLayout.CENTER);
add(new Btns(), BorderLayout.SOUTH);
}
public static void main (String[] args) {
Lab2 frame = new Lab2();
frame.setTitle("Move The Ball");
frame.setSize(450, 700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

You have extra dots here before the method parenthesis:
Replace:
add.(jbtL);
add.(jbtR);
add.(jbtU);
...
with
add(jbtL);
add(jbtR);
add(jbtU);
...

add()
is a inherited method from the Component & Container class, so you remove the dots and choose the correct implementation for your case, See javadocs

Have you even written a Java code?
public Btns()
{
JButton jbtL = new JButton("Left");
JButton jbtR = new JButton("Right");
JButton jbtU = new JButton("Up");
JButton jbtD = new JButton("Down");
JButton jbtRd = new JButton("Red");
JButton jbtG = new JButton("Green");
super.add(jbtL);
super.add(jbtR);
this.add(jbtU);
super.add(jbtD);
add(jbtRd);
add(jbtG);
}
The dot is used as a resolution scope operator to indicate that something is a member of a class. super above indicate the super class JFrame, which has the method add derived from Component. this indicate the current object, which is of type Btns, which also has the method add derived from JFrame.
this and super are not necessary qualifiers in most cases, therefore the last two calls don't use super.
Also, if you are adding object of type Btns to your main frame, then you should extend JInternalFrame instead of JFrame.
public class Btns extends javax.swing.JInternalFrame {
Then is constructor:
public Lab2() {
JDesktopPane p = new JDesktopPane();
add(p);
p.add(new Btns());
}

Related

How to make a JButtons appear

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?

Java GUI, transitioning from one class to another

I am stumped and desperate for help. Been able to figure everything else out until I got into GUI's. What I am trying to do is go from the LogInPane (Log In Page) to JobSelectionGUI (Job Selection Page);
When I compile it runs how I want it to, but I can't figure out how to get my JFrame from LogInPaneGUI to close when it opens JobSelectionGUI, Tons of reading and videos and picking GUI's/Applying them is rough! I started with a GridLayout then switched to GridBagLAyout, then tried CardLayout and now back to GBL.
I don't use an IDE; I use SublimeText, so if something looks extremely elongated in my code, its because I had to write it out long for Sublime (or because I'm bad). All my code is separated into different classes so it stays neat and easy to debug. Every class has its own package, and every package has no more than 2 Methods. I work my butt off to keep my main completely empty!
Taking all criticism and advice!
MAIN:
package com.hallquist.kurtis.leigh.srcmain;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.text.*;
// Class imports;
import JobSelection.*;
import LogInPane.*;
// My Main function. Used to pull packages and methods and compile them here;
public class SrcMainUserInformation{
public static void main(String[] args){
LogInPaneGUI logInGUI = new LogInPaneGUI();
logInGUI.logInPaneMainGUI();
}
}
First Class:
package LogInPane; // package name;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import JobSelection.*; //import for next GUI when LogInButton is clicked;
public class LogInPaneGUI{
private static final JFrame frame = new JFrame();
private static final int COLS = 10; // Max columns;
private static final JPanel panelForm = new JPanel(new GridBagLayout()); // layout
private static final JTextField fieldLogInName = new JTextField(COLS); //login
private static final JPasswordField logInPassword = new JPasswordField(COLS); //pw
private static final JButton logInButton = new JButton("Log In"); //login button
private static final JButton exitButton = new JButton("EXIT"); //system.exit button
private static final JButton newUser = new JButton("New User? Click here to sign up!"); // new user button
// Wigits on login page;
public LogInPaneGUI(){
GridBagConstraints c = new GridBagConstraints();
// Creates the panel that goes ontop of the JFrame;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_END;
panelForm.add(new JLabel("Account Name: "), c);
c.gridy ++;
panelForm.add(new JLabel("Password: "), c);
c.gridy ++;
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_START;
panelForm.add(fieldLogInName, c);
c.gridy++;
panelForm.add(logInPassword, c);
c.gridy++;
panelForm.add(logInButton, c);
c.gridy++;
panelForm.add(newUser, c);
c.gridy++;
panelForm.add(exitButton, c);
// Goes to fourm/website on newUser click;
newUser.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
System.out.println("Fourm/Website to sign up for game");
}
});
// Exits program on exitButton click;
exitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
// Goes to JobSelectionGUI on logInButton Click;
logInButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JobSelectionGUI jobSelecting = new JobSelectionGUI();
jobSelecting.jobSelectionJFrameGUI();
// frame.dispose();
// System.out.println("Will log you in when I set it up");
}
});
}
// Actual JFrame that everything goes ontop of;
public static void logInPaneMainGUI(){
JFrame frame = new JFrame("FirstProject");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(panelForm);
}
}
Second Class:
package JobSelection;
import java.awt.*;
import java.awt.event.ActionEvent.*;
import javax.swing.*;
import javax.swing.text.*;
// Mass import from JobSelection package; All base job information;
import JobSelection.JobInformationIndex.JobAmazonData.*;
import JobSelection.JobInformationIndex.JobBanditData.*;
import JobSelection.JobInformationIndex.JobLancerData.*;
import JobSelection.JobInformationIndex.JobSorcererData.*;
import JobSelection.JobInformationIndex.JobWitchData.*;
import LogInPane.*; // to return to login screen;
import JobSelection.*; // dont know if needed;
public class JobSelectionGUI{
private static JFrame frame = new JFrame();
private static JSplitPane jSplitPane = new JSplitPane();
private static JPanel leftPane = new JPanel();
private static JLabel logInCharacterName = new JLabel();
private static JTextField userCharacterName = new JTextField();
private static JButton logInAccept = new JButton("Accept");
private static JButton logInBack = new JButton("Back");
private static JTextArea firstGameIntroduction = new JTextArea();
private static JTextArea descriptionIntroduction = new JTextArea();
private static JTextArea jobSelectedInformation = new JTextArea();
private static JPanel allWidgits = new JPanel();
public JobSelectionGUI(){
JTextArea firstGameIntroduction = new JTextArea("\ Text.");
firstGameIntroduction.setLineWrap(true);
firstGameIntroduction.setWrapStyleWord(true);
JScrollPane areaScrollPane = new JScrollPane(firstGameIntroduction);
areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(250, 250));
areaScrollPane.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Introduction"),
BorderFactory.createEmptyBorder(5,5,5,5)),
areaScrollPane.getBorder()));
leftPane.add(areaScrollPane);
JTextArea descriptionIntroduction = new JTextArea(" Text.\n");
descriptionIntroduction.setLineWrap(true);
descriptionIntroduction.setWrapStyleWord(true);
JScrollPane areaScrollPaneTwo = new JScrollPane(descriptionIntroduction);
areaScrollPaneTwo.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPaneTwo.setPreferredSize(new Dimension(250, 250));
areaScrollPaneTwo.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("What to expect"),
BorderFactory.createEmptyBorder(5,5,5,5)),
areaScrollPaneTwo.getBorder()));
leftPane.add(areaScrollPaneTwo);
}
public static void jobSelectionJFrameGUI(){
JFrame frame = new JFrame("FirstProject");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(leftPane);
}
}
You grossly overuse the static modifier and most of your fields should not in fact be static. I would venture to state that most if not all of your class's fields should be private instance fields.
The log-in window should not be a JFrame but rather a blocking or "modal" dialog, and for Swing that means using a modal JDialog or JOptionPane (which creates a modal JDialog behind the scenes)
A modal dialog will block the calling code when it is displayed
And if the dialog is modal, then you know when it is no longer visible since the calling code is unblocked. This is when you would query the state of the dialog's fields (using public getter methods, not calling static fields directly), and decide if the login was successful or not. If so, show your main GUI window or JFrame.
Another option is to yes, use CardLayout, but for this to work, all your major GUI classes should be geared towards creating JPanels, not JFrames. This way you can insert the panels where and when needed, including within top-level windows such as JFrames or JDialogs, within or JPanels, or swapped using a CardLayout.
Note that frame.dispose() isn't working for you because you shadow the frame field by re-declaring it logInPaneMainGUI() method.
public static void logInPaneMainGUI() {
// ***** this creates a new local JFrame variable called frame
JFrame frame = new JFrame("FirstProject");
// so calling frame.dispose() elsewhere will have no effect on this window
Don't do this, and the .dispose() method call will close the first window.
public static void logInPaneMainGUI() {
frame = new JFrame("FirstProject"); // this initializes the frame field
// so calling frame.dispose() elsewhere will have no effect on this window
Of course frame would have to be non-final or not-initialized previously. I still would recommend using a JDialog however, as well as moving out of the static world and into the instance world
Unrelated criticism:
Less chatty text in your question, text that is completely unrelated to your actual problem at hand, and more text that tells us useful information that helps us to understand your problem and your code, and thereby helping us solve the problem.

Nothing is appearing when i switch JPanels

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

Java GUI - JButton opens another frame from another class

i'm having trouble to get the 2nd frame to display the GUI Components. i've opened the frame using the JButton from the 1st frame.
Here's the screen shot
This is the first frame - ClientModule.java
2nd frame - ClientMenu.java
Here's the codes i've tried
ClientModule.java
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ClientModule extends JFrame implements Runnable{
private JPanel panel;
private JFrame frame;
private JLabel titleLbl, userLbl, passLbl, hostLbl, portLbl, ipLbl;
private JTextField userTxt, hostTxt, portTxt, ipTxt;
private JPasswordField passTxt;
private JButton loginBtn;
public static void main(String[] args)
{
new ClientModule().run();
}
public ClientModule()
{
frame = new JFrame("DMS(Drawing Message System)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setPreferredSize(new Dimension(500,500));
panel.setLayout(new FlowLayout());
titleLbl = new JLabel("LogIn to Drawing Message System(DMS)");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
userLbl = new JLabel("Username:");
passLbl = new JLabel("Password:");
hostLbl = new JLabel("Hostname:");
portLbl = new JLabel("Port No.:");
ipLbl = new JLabel("IP Address:");
userTxt = new JTextField();
userTxt.setPreferredSize(new Dimension(100,30));
passTxt = new JPasswordField();
passTxt.setEchoChar('*');
passTxt.setPreferredSize(new Dimension(100,30));
portTxt = new JTextField();
portTxt.setPreferredSize(new Dimension(100,30));
ipTxt = new JTextField();
ipTxt.setPreferredSize(new Dimension(100,30));
hostTxt = new JTextField();
hostTxt.setPreferredSize(new Dimension(100,30));
loginBtn = new JButton("Login!");
loginBtn.setPreferredSize(new Dimension(90,30));
loginBtn.addActionListener(new LoginBtnListener());
panel.add(titleLbl);
panel.add(userLbl);
panel.add(userTxt);
panel.add(passLbl);
panel.add(passTxt);
panel.add(hostLbl);
panel.add(hostTxt);
panel.add(portLbl);
panel.add(portTxt);
panel.add(ipLbl);
panel.add(ipTxt);
panel.add(loginBtn);
frame.add(panel);
}
private class LoginBtnListener implements ActionListener
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
//thinking this frame will close after ClientMenu's frame is open
ClientModule client = new ClientModule();
client.setVisible(false);
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
}
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
ClientMenu.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class ClientMenu extends JFrame{
JFrame frame;
JPanel panel;
JLabel titleLbl;
JButton sendBtn,receiveBtn,logoutBtn;
public ClientMenu()
{
frame = new JFrame("Drawing Message System(DMS)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(500,500));
titleLbl = new JLabel("Main Menu");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
sendBtn = new JButton("Send a Drawing");
sendBtn.setPreferredSize(new Dimension(100,30));
receiveBtn = new JButton("Receive a Drawing");
receiveBtn.setPreferredSize(new Dimension(100,30));
logoutBtn = new JButton("Logout");
logoutBtn.setPreferredSize(new Dimension(100,30));
logoutBtn.addActionListener(new LogoutBtnListener());
panel.add(titleLbl);
panel.add(sendBtn);
panel.add(receiveBtn);
panel.add(logoutBtn);
frame.add(panel);
}
private class LogoutBtnListener implements ActionListener
{
//#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
ClientModule client = new ClientModule();
client.setVisible(true);
ClientMenu menu = new ClientMenu();
menu.setVisible(false);
}
}
public static void main(String[] args)
{
new ClientMenu().run();
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
I'm not sure if i'm missing something, or coded something wrong, or something else. I've already searched and tried..
any help and understanding is appreciated (:
I managed to get the second frame displayed (including its contents) by adding a call to the run() method:
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
menu.run();
That being said, there are quite some problems with your code:
You have a main method in each of your classes. You should have only 1 main method per application. Since ClientModule seems to be the first Frame you want to have opened, your might want to keep the main method there and remove the one in the other class.
You have a run() method in each class. Personally, I tend to avoid naming methods like this, since it might cause confusion with the run() method which needs to be overridden when dealing with threads. You are clearly attempting to do some multi threading in your ClientModule, but will not work. Please look into this concurrency tutorial to better understand threads. You should also understand that you should never call run() yourself. The tutorial should make that clear.
Swing applications are started a little bit differently that other applications. Please refer to this tutorial for more information.
You have both your classes extend JFrame but then, provide your own. This results in other JFrames being created, which is what happened in my case (I get 2 JFrames per instantiation). If you want your class to behave like a JFrame, consider extending it, if you want to use a JFrame, then compose your class of one, not both (at least not in this case).
Lastly, to get rid of the previous JFrame you could call dispose() on the it. That being said, the approach usually is to use the Card Layout. This would allow you to have 1 frame with multiple content.
Sorry for the long post, but please consider re factoring as per the above prior to continuing.
You can use the setVisible property to 'true' or 'false'.

How can I correctly place a JPanel onto a JFrame?

I'm currently studying Software Engineering at Uni and I'm struggling to come to terms with how to add a JPanel onto a JFrame properly. My JPanel has a couple of buttons as well as a JLabel which changes by clicking on one of the buttons and using an ActionListener.
I know there are several ways to do it, and here is what I've been trying but I can't for the life of me figure it out!
I know I am doing loads wrong but what is it?
Here is my code:
UIPanelOne:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;
public class UIPanelOne extends JPanel implements ActionListener {
private JButton yes, no, cancel;
private JPanel panel;
private JLabel l1, l2;
UIPanelOne() {
super();
setVisible(true);
//label dec
panel = new JPanel();
//buttons
yes = new JButton("Yes");
no = new JButton("No");
cancel = new JButton("Cancel");
//label dec
l1 = new JLabel("Hello");
//button dec
panel.setLayout(new BorderLayout());
panel.add(yes);
panel.add(no);
panel.add(cancel);
panel.add(l1);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == yes) {
l1.setText("OK then!");
}else if (e.getSource() == no){
l1.setText("Goodbye then!");
}else if(e.getSource() == cancel){
System.exit(0);
}
}
public JComponent getGUI(){
return panel;
}
}
UIFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UIFrame extends JFrame{
//constructor
public UIFrame(){
//layout
super("Can I help you?");
setSize(400,600);
setLayout(new BorderLayout());
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
UIPanelOne hello = new UIPanelOne();
getContentPane().add(hello.getGUI());
}
}
UITest:
public class UITest {
public static void main(String[] args){
UIFrame frame = new UIFrame();
frame.pack();
}
}
I know alot of this is probably wrong and I'm a total amateur but I'm hoping to get better with some help!
Since your UIPanelOne extends JPanel class you can add your component's on that panel (no need for creation of new panel), create a new instance and pass that instance to add method of JFrame:
add(new UIPanelOne());
or
UIPanelOne hello = new UIPanelOne();
add(hello,BorderLayout.CENTER);
or
setContentPane(hello);
Avoid extending your classes with swing component's unless you want to define new method's for them (creation of custom component's) or if you wan't to override some of their method's.
You don't have to set BorderLayout for JFrame since it's default layout for JFrame (aleady set).
Call setVisible method for JFrame AFTER you add component's.
Also, read about Concurrency in Swing

Categories

Resources