For my homework extra credit I am creating a JTabbedPane and adding two Jpanels. I feel like I am very close, but it still does not compile. When I run it, both JPanels open, but the JTabbedPane does not. I get a lot of Unknown Source errors. I suspect that at this point my issue in in the JPanels themselves because they started out being JFrames and I have tried (unsuccessfully I think) to convert the JFrames to JPanels.
JTabbedPaneAssignment is supposed to create the JTabbedPane and populate the two panes with the apps DayGui on one tab and OfficeAreaCalculator on the other. I only include the JTabbedPaneAssignment and DayGui classes here. I apologize if its too much code, I have trimmed off a lot of what I consider extraneous, but there may still be too much.
Here is the calling class JTabbedPaneAssignment
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTabbedPaneAssignment extends JPanel
{
public JTabbedPaneAssignment()
{
//super(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane();
DayGui pnlDay = new DayGui();
OfficeAreaCalculator pnlOffice = new OfficeAreaCalculator ();
this.add(tabbedPane);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
tabbedPane.add(panel1,"First panel");
tabbedPane.add(panel2,"Second panel");
//JComponent panel1 = makeTextPanel("Pane #1");
panel1.setPreferredSize(new Dimension(300, 150));
tabbedPane.addTab("DayGui", panel1);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
//JComponent panel2 = makeTextPanel("Pane #2");
panel2.setPreferredSize(new Dimension(410, 50));
tabbedPane.addTab("OfficeAreaCalculator", panel2);
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
add(tabbedPane);
}
protected JComponent makeTextPanel(String text)
{
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
// Create JTabbedPane
private static void createAndShowGUI()
{
// Create and set up the window.
JFrame frame = new JFrame("JTabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTabbedPaneAssignment(), BorderLayout.CENTER);
JTabbedPane DayGui = new JTabbedPane();
JTabbedPane OfficeAreaCalculator = new JTabbedPane();
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Here is DayGui class. It started out as a JFrame, but I am trying to convert it to a JPanel. I think my issue is in this section of code, but I don't know
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//public class DayGui extends JPanel
public class DayGui extends JPanel
{
private JPanel dayPanel;
private JButton cmdGood;
private JButton cmdBad;
public DayGui()
{
//dayPanel = new JPanel("Messages");
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
Container c = dayPanel.getRootPane();
c.setLayout(new FlowLayout());
c.add(cmdGood);
c.add(cmdBad);
dayPanel.setSize(300, 150);
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
dayPanel.setVisible(true);
dayPanel.getRootPane().setBackground(Color.CYAN);
}
class ButtonsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cmdGood)
JOptionPane.showMessageDialog(null, "Today is a good day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
if (e.getSource() == cmdBad)
JOptionPane.showMessageDialog(null, "Today is a bad day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
You have been very ambiguous with your question, and you've posted way more code than anyone here has time to trawl through.
I've made a very small but working JTabbedPane example for you to see the smallest amount of work you need to get it working.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class JTabbedPaneExample extends JFrame{
public JTabbedPaneExample(String title){
super(title);
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panelOne = new JPanel();
JPanel panelTwo = new JPanel();
tabbedPane.add(panelOne,"First panel");
tabbedPane.add(panelTwo,"Second panel");
add(tabbedPane);
}
public static void main(String[] args){
new JTabbedPaneExample("JTP Example").setVisible(true);
}
}
Then running, this code looks like:
If you repeat the same process in your code, and you've still got errors, then the problem is not with your JTabbedPane, but something else.
Okay, here goes a second time. Now you've got the DayGui class up, we notice that you're trying to use dayPanel before you've initialised it. i.e. nowhere do you say dayPanel = new JPanel();. This resulted in a NullPointerException being thrown in your code, screwing up your normal course of exection. Fix this and your DayGui class would run fine at runtime.
Among your codebase, you also do some very funky things, namely start using something but never getting around to finishing it up. An example of this is you extending JPanel, but resorting to using a member variable of type JPanel to do the rest of the work. The suggestion is to scrap the instance variable all together and use the methods you've inherited from extending JPanel.
Now lets move onto your JTabbedPaneAssignment class. Although not terrible, the code is not very readable and it repeats itself in many places (adding your tabbedpanel multiple times). If you were to take this code further into a larger project, maintenance and debugging would quickly become a problem.
For the purposes of showing you how much clutter you had in your code, I've quickly rewritten your provided code to be compilable, and should roughly do what you're working on.
JTabbedPaneAssignment:
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class JTabbedPaneAssignment extends JPanel
{
public JTabbedPaneAssignment()
{
final JTabbedPane tabbedPane = new JTabbedPane();
final DayPanel dayPanel = new DayPanel();
final JPanel officePanel = new JPanel();
tabbedPane.add("DayGui", dayPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
tabbedPane.add("OfficeAreaCalculator", officePanel);
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
add(tabbedPane);
}
// Create JTabbedPane
private static void createAndShowGUI()
{
// Create and set up the window.
JFrame frame = new JFrame("JTabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTabbedPaneAssignment(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
DayGui - renamed as DayPanel:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class DayPanel extends JPanel {
public DayPanel() {
super();
setBackground(Color.CYAN);
final JButton goodButton = new JButton("Good");
final JButton badButton = new JButton("Bad");
ActionListener listener = new DayPanel.ButtonsHandler();
goodButton.addActionListener(listener);
badButton.addActionListener(listener);
add(goodButton);
add(badButton);
}
class ButtonsHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
final String command = ((JButton) e.getSource()).getActionCommand();
if (command.equals("Good")) {
showMessage("Today is a good day!");
} else if (command.equals("Bad")) {
showMessage("Today is a bad day!");
}
}
// Show popup message
private void showMessage(String message) {
JOptionPane.showMessageDialog(null, message,
"Event Handler Message", JOptionPane.INFORMATION_MESSAGE);
}
}
}
So what is different in these? Basically, I've removed your NullPointerException you were getting in DayGui. Any other changes I've made are with the intention than you try and keep your code clutter free, so you really know what is going on in your code.
Hope this helps.
When I run it, both JPanels open, but the JTabbedPane does not. I get
a lot of Unknown Source errors.
Well, based on your code and your import section:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
This lines won't compile (unless DayGUI and OfficeAreaCalculator classes are in the same package than your JTabbedPaneAssignment class):
DayGui pnlDay = new DayGui();
OfficeAreaCalculator pnlOffice = new OfficeAreaCalculator ();
This is the only error I've got trying to compile and run your example. I changed lines below:
tabbedPane.addTab( "DayGui", new JPanel());
tabbedPane.addTab("Office Calculator", new JPanel());
And it worked like a charm.
Update
Based on your recent edit (adding your DayGui class, thank you) you have couple of mistakes in your code.
DayGui : this class extends of JPanel so you need to add your components directly on this class, you don't need this panel:
private JPanel dayPanel;
You need to set the layout manager, buttons and background directly on DayGuiclass, like this:
public DayGui() {
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
setLayout(new FlowLayout());
add(cmdGood);
add(cmdBad);
setSize(300, 150);
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
setBackground(Color.CYAN);
}
JTabbedPaneAssignment : I think you're trying to add panel1 and panel2 as tabs but you use add method instead addTab:
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
tabbedPane.add(panel1,"First panel");
tabbedPane.add(panel2,"Second panel");
Also this line:
tabbedPane.addTab("DayGui", panel1);
Should be:
tabbedPane.addTab("DayGui", pnlDay);
Finally in this line you are adding panel2 for a second time and that's not correct:
tabbedPane.addTab("OfficeAreaCalculator", panel2); //I'd comment this line
If you make suggested changes you'll see something like this (BTW the CYAN color almost made me blind :P):
Hope this be helpful and sorry for the extension.
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?
I have a JPanel (firstPanel) which is embedded into an other JPanel (secondPanel). I want to create a JTabbedPane with two tabs: one for the firstPanel and one for the secondPanel.
However, when I switch to secondPanel, the embedded firstPanel won't show up.
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Application extends JFrame
{
public Application()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setMinimumSize(new Dimension(300, 300));
JPanel firstPanel = new JPanel();
firstPanel.add(new JLabel("first"));
JPanel secondPanel = new JPanel();
// JPanel thirdPanel = new JPanel();
// thirdPanel.add(new JLabel("third"));
//
// secondPanel.add(thirdPanel);
secondPanel.add(firstPanel);
secondPanel.add(new JLabel("second"));
JTabbedPane mainPanel = new JTabbedPane();
mainPanel.addTab("First", firstPanel);
mainPanel.addTab("Second", secondPanel);
this.add(mainPanel);
}
public static void main(String[] args)
{
Application app = new Application();
app.pack();
app.setVisible(true);
}
}
When I add the thirdPanel instead of the first, it works as expected.
Am I missing something obvious?
Thanks you!
This is because you are trying to add a single panel to two different parents, one being your secondPanel, and the other being your tab. You can't do that.
Can I ask why you think you want to do this? There is probably a better solution out there for you.
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'.
I have a problem. Now I'm working with 3 panels, mainPanel and 2 others ( btnPanel and iconPanel).
So the problem is when I push button "reset" I delete iconPanel and add it again it moves slightly to right on its own. Maybe someone can check my code where the problem?
Also I dont want to create another question so I give 2 extra questions.
Do I delete JPanel properly?
If I delete JPanel with components inside they also will be removed from memory?
P.s. Im beginner so dont judge me :)
Main.java
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Made by Mac4s");
frame.setVisible(true);
frame.setSize(310, 654);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(false);
MainScreen screenObj = new MainScreen();
screenObj.setPreferredSize(new Dimension(310, 650));
frame.add(screenObj);
}
});
}
}
MainScreen.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainScreen extends JPanel {
private JButton resetBtn;
private JPanel btnPanel;
private JPanel iconPanel;
public MainScreen() {
JPanel mainPanel = new JPanel(new BorderLayout());
this.setBackground(Color.BLACK);
setBtnPanelAndComp();
setIconPanelAndComp();
add(mainPanel);
}
private void setBtnPanelAndComp() {
btnPanel = new JPanel(new BorderLayout());
btnPanel.setBackground(Color.GREEN);
btnPanel.setPreferredSize(new Dimension(295, 30));
setButtons();
this.add(btnPanel, BorderLayout.NORTH);
}
private void setButtons() {
resetBtn = new JButton("Reset");
resetBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
resetIconLabel();
}
});
btnPanel.add(resetBtn, BorderLayout.WEST);
}
private void resetIconLabel() {
this.remove(iconPanel);
this.repaint();
this.revalidate();
setIconPanelAndComp();
}
private void setIconPanelAndComp() {
iconPanel = new JPanel(new BorderLayout());
iconPanel.setBackground(Color.YELLOW);
iconPanel.setPreferredSize(new Dimension(295, 580));
this.add(iconPanel, BorderLayout.SOUTH);
}
}
"the problem is when I push button "reset" I delete iconPanel and add it again it moves slightly to right on its own."
The reason this happens is because a JPanel has a FlowLayout by default. You're trying add to a BorderLayout position that is non-existent.
this.add(iconPanel, BorderLayout.SOUTH);
The FlowLayout has default gaps on the edges, so when you set the size of the frame, those gaps aren't respected. To over come this, it is also preferable to pack() the frame, instead of setSize()
The reason BorderLayout works (doesn't shift) is because preferred sizes aren't respected.
If you set the layout in the constructor to this.setLayout(new BorderLayout()); You won't have the shift.
public MainScreen() {
JPanel mainPanel = new JPanel(new BorderLayout());
this.setLayout(new BorderLayout()); <----
setBtnPanelAndComp();
setIconPanelAndComp();
add(mainPanel);
}
Notes
You should setVisible() after adding components. That's why your frame jumps when you first open it. You are setting the frame visible, then moving it around with the location, and adding components.
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