I am a beginner Java-coder and a few days ago I felt confident enough in my skills to start my first "big" project. It was basically a calculator, a GUI(only JFrame, JPanels, JLabels and Buttons) that would display data, accept user input, grab some more data from other classes, then calculate stuff and finally update the GUI with the new JLabel values. However I never managed to get the update part done properly, whenever I would press the 'process'-button it would create a new JFrame with the new values, while the old one was still up.
I tried the obvious stuff (repaint(), revalidate(), etc) but that didn't work at all, then I started to shift things around, put parts of the code into new classes, copied code from the net until it eventually worked. However the code was a total mess and I didn't even really understand what went exactly wrong in the first place, so I trashed the entire thing.
Here is a very simplified version of my code before things went downhill:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test_1 extends JFrame {
public static class clicks{
static int clicks = 0;
public int getclicks(){
return clicks;
}
public void setclicks(){
clicks = clicks+1;
}
}
public Test_1(){
clicks getNumber = new clicks();
int x = getNumber.getclicks();
//FRAME AND LAYOUT
JFrame window = new JFrame();
window.getContentPane().setBackground(Color.darkGray);
window.getContentPane().setLayout(new BorderLayout(20,10));
window.setTitle("Test Frame 1");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(true);
// Top JPanel
JPanel northpanel = new JPanel();
LayoutManager northlayout = new FlowLayout();
northpanel.setLayout(northlayout);
// Top JPanel content
JLabel nlabel1 = new JLabel("Hello North");
nlabel1.setPreferredSize(new Dimension(100,20));
northpanel.add(nlabel1);
JPanel westpanel = new JPanel();
LayoutManager westlayout = new BoxLayout(westpanel, BoxLayout.Y_AXIS);
westpanel.setLayout(westlayout);
JLabel wlabel1 = new JLabel("Hello West");
wlabel1.setPreferredSize(new Dimension(100,20));
westpanel.add(wlabel1);
JPanel eastpanel = new JPanel();
LayoutManager eastlayout = new BoxLayout(eastpanel, BoxLayout.Y_AXIS);
eastpanel.setLayout(eastlayout);
JLabel elabel1 = new JLabel ("Hello East");
elabel1.setPreferredSize(new Dimension(100,20));
eastpanel.add(elabel1);
JButton southbutton = new JButton("start");
southbutton.setPreferredSize(new Dimension(400,50));
southbutton.addActionListener(new Action());
JPanel centralpanel = new JPanel();
JLabel clabel1 = new JLabel("Clicks: " + x);
centralpanel.add(clabel1);
window.add(centralpanel, BorderLayout.CENTER);
window.add(southbutton, BorderLayout.SOUTH);
window.add(eastpanel, BorderLayout.EAST);
window.add(westpanel, BorderLayout.WEST);
window.add(northpanel, BorderLayout.NORTH);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
Test_1 window_start = new Test_1();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e){
clicks Numbers = new clicks();
Numbers.setclicks();
int test = Numbers.getclicks();
System.out.println("Button works, Number of clicks: "+test);
Test_1 updateData = new Test_1();
}
}
}
I know that the ActionListener creates a new instance of my JFrame, however that was the closest I ever came to "updating the JFrame" before I turned the code into Spaghetti. I assume that the way I build my code is the cause of my problem but creating the Frame and its content it different classes didn't work at all.
So my questions are:
Is there something really obvious I missing? Would it be possible to make this run the way I want to without completely changing it?
Is there a more efficient way to create a GUI? I get the feeling that the way I made this is total garbage.
I read other questions that dealt with similar problems but maybe it's because I am still pretty bad at Java but I couldn't really tell if they were related to my problem. Also I really want to understand this, so copying someone elses code wouldn't help at all.
Any help or comments are appreciated.
btw, the class click is something I just put there as a placeholder.
Alrighty I managed to get it to work. It's probably against the Etiquette to answer to his own question but I thought it might be useful for some beginners(like me yesterday). So here is my new code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test_1 extends JFrame {
public static class clicks{
static int clicks = 0;
public int getclicks(){
return clicks;
}
public void setclicks(){
clicks = clicks+1;
}
}
clicks getNumber = new clicks();
int x = getNumber.getclicks();
JPanel northpanel, westpanel, eastpanel, southpanel, centralpanel;
static JLabel nlabel1, nlabel2, nlabel3, nlabel4, nlabel5;
static JLabel wlabel1, wlabel2, wlabel3, wlabel4, wlabel5;
static JLabel elabel1, elabel2, elabel3, elabel4, elabel5;
static JLabel clabel1;
JButton southbutton;
String TextnL, TextwL, TexteL;
public Test_1(){
setBackground(Color.darkGray);
setLayout(new BorderLayout(20,10));
setTitle("Test Frame 1");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
nlabel1 = new JLabel("North_1");
nlabel2 = new JLabel("North_2");
nlabel3 = new JLabel("North_3");
nlabel4 = new JLabel("North_4");
nlabel5 = new JLabel("North_5");
wlabel1 = new JLabel("West_1 ");
wlabel2 = new JLabel("West_2 ");
wlabel3 = new JLabel("West_3 ");
wlabel4 = new JLabel("West_4 ");
wlabel5 = new JLabel("West_5 ");
elabel1 = new JLabel("East_1");
elabel2 = new JLabel("East_2");
elabel3 = new JLabel("East_3");
elabel4 = new JLabel("East_4");
elabel5 = new JLabel("East_5");
clabel1 = new JLabel("START");
southbutton = new JButton("Process");
southbutton.addActionListener(new Action());
northpanel = new JPanel();
northpanel.add(nlabel1);
northpanel.add(nlabel2);
northpanel.add(nlabel3);
northpanel.add(nlabel4);
northpanel.add(nlabel5);
add(northpanel, BorderLayout.NORTH);
westpanel = new JPanel();
LayoutManager wBox = new BoxLayout(westpanel, BoxLayout.Y_AXIS);
westpanel.setLayout(wBox);
westpanel.add(wlabel1);
westpanel.add(wlabel2);
westpanel.add(wlabel3);
westpanel.add(wlabel4);
westpanel.add(wlabel5);
add(westpanel, BorderLayout.WEST);
eastpanel = new JPanel();
LayoutManager eBox = new BoxLayout(eastpanel, BoxLayout.Y_AXIS);
eastpanel.setLayout(eBox);
eastpanel.add(elabel1);
eastpanel.add(elabel2);
eastpanel.add(elabel3);
eastpanel.add(elabel4);
eastpanel.add(elabel5);
add(eastpanel, BorderLayout.EAST);
centralpanel = new JPanel();
centralpanel.add(clabel1);
add(centralpanel, BorderLayout.CENTER);
add(southbutton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
Test_1 window_start = new Test_1();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e){
clicks Numbers = new clicks();
Numbers.setclicks();
int test = Numbers.getclicks();
clabel1.setText("clicks: "+test);
}
}
}
And again, any comments/suggestions are welcome.
Related
Hi though i did complete the basics of java which im fairly new of, i keep getting errors when i try to add buttons on a new Frame/Panel. Care to educate me on what the problem might be?
import javax.swing.*;
import java.awt.*;
class MainClass {
String cont_orders;
private JFrame frame1;
private JPanel mainpanel;
JButton bt1, bt2, bt3, bt4, bt5;
private JButton btotal = new JButton("Order");
private JButton clearOr = new JButton("Clear");
private JTextField pricetotal = new JTextField();
private JTextField list_of_orders = new JTextField();
public MainClass(){
gui();
}
private void gui(){
frame1 = new JFrame("Order");
frame1.setSize(500,430);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setResizable(false);
mainpanel = new JPanel();
mainpanel.setBackground(Color.BLUE);
mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");
frame1.add(mainpanel,BorderLayout.CENTER);
}
public static void main (String[]args){
new MainClass();
}
}
im trying to practice on coding normally instead of relying on that automatic one in NetBeans [JFrame Form/JPanel Form]
care to help?
Now this cannot be done in java
mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");
Turn it around.
Explanation: the field bt1 is at that time a variable holding the null object.
That object (value) is added, not some variable address as in other languages.
Reverse it bt1 = new JButton("M-Item 1 [Soda]"
mainpanel.add(bt1);
Because if not the value of bt1 would be null so you must fill it first then use it .
Or
mainpanel.add(new JButton("..."));
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 changed the code again. But now when I run the code, The text box is very small. Only whn I choose either of the left, center or the right alignment, will the text box size change.
Where did I make the mistake.
I have written the below program. When I click on the left, right or the center button, the program should also read the value in the column size textbox and then automatically resize the message textfield. BUt I cannot seem to do it. Any insight will be greatly appreciated.
package workingwithjtextfields;
package workingwithjtextfields;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.border.*;
public class WorkingwithJTextFields extends JFrame
{
// private int size = 100;
private JTextField jtfMessage = new JTextField(100);
private JTextField jtfColumn = new JTextField(5);
private JRadioButton jrbLeft,jrbCenter,jrbRight;
public static void main(String[] args) //Main program begins here.
{
JFrame frame = new WorkingwithJTextFields();//Instantiating an object.
frame.setTitle("Exercise 17.11");//Setting the frame title.
frame.setSize(470,110);//Setting the size.
frame.setLocationRelativeTo(null);//Setting the location.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// Default closing options.
frame.setVisible(true);//Setting visibility to true.
}//End of main program
public WorkingwithJTextFields()
{
// jtfMessage.setColumns(100);
final JPanel parent = new JPanel();
parent.setLayout(new GridLayout(2,1,3,3));
final JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT,30,0));
p1.add(new JLabel("TextField",SwingConstants.CENTER));
jtfMessage= new JTextField("Type anything",SwingConstants.RIGHT);
jtfMessage.setHorizontalAlignment(SwingConstants.CENTER);
p1.add(jtfMessage);
parent.add(p1);
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(1,3));
jpRadioButtons.add(jrbLeft= new JRadioButton("Left"));
jpRadioButtons.add(jrbCenter = new JRadioButton("Center"));
jpRadioButtons.add(jrbRight = new JRadioButton("Right"));
jpRadioButtons.setBorder(new TitledBorder("Horizontal Border"));
final JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,2,1,1));
p2.add(jpRadioButtons);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(1,1,1,1));
p3.add(new JLabel("Column Size"));
jtfColumn= new JTextField("60",SwingConstants.RIGHT);
jtfColumn.setHorizontalAlignment(SwingConstants.CENTER);
p3.add(jtfColumn);
Border lineBorder = new LineBorder(Color.LIGHT_GRAY,1);
p3.setBorder(lineBorder);
p2.add(p3);
parent.add(p2);
add(parent);
jrbLeft.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jtfMessage.setHorizontalAlignment(SwingConstants.LEFT);
jrbCenter.setSelected(false);
jrbRight.setSelected(false);
jtfMessage.setColumns(Integer.parseInt(jtfColumn.getText()));
// p1.revalidate();
// p1.repaint();
}
}
);
jrbCenter.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jtfMessage.setHorizontalAlignment(SwingConstants.CENTER);
jrbLeft.setSelected(false);
jrbRight.setSelected(false);
jtfMessage.setColumns(Integer.parseInt(jtfColumn.getText()));
}
}
);
jrbRight.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jtfMessage.setHorizontalAlignment(SwingConstants.RIGHT);
jrbCenter.setSelected(false);
jrbLeft.setSelected(false);
jtfMessage.setColumns(Integer.parseInt(jtfColumn.getText()));
}
}
);
}
}
The main problem is with GridLayout.
GridLayout, by design, gives equal width and height to the components in the column/width based on the available space of the parent container.
Instead, try using something like FlowLayout or GridBagLayout which work with the components preferred size instead
I am trying to open a New Window by pressing the JButton. Now my actionPerformed method for the Jbutton is just closing the window after pressing it. I want it to open a new window as the old window closes. I know, this question is already had been asked, but I tried lot of things, no one seems to work perfectly.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.Random;
public class secondTab extends JFrame
{
static JTabbedPane Pane = new JTabbedPane();
static JPanel Second = new JPanel();
static JPanel second = new JPanel(); // This Panel is inside the Second Panel
static JButton guess1 = new JButton();
static String words[] = new String[9];
static Random getRandomWord = new Random();
static int rr;
static JButton Labels[] = new JButton[10];
public static void main(String args[])
{
//construct frame
new secondTab().show();
}
public secondTab()
{
// code to build the form
setTitle("Shopping Cart");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridBagLayout());
// position tabbed pane
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
Pane.setForeground(Color.YELLOW);
Pane.setBackground(Color.MAGENTA);
getContentPane().add(Pane, gridConstraints);
getContentPane().setLayout(new GridBagLayout());
// Tabs Starts From Here
Second.setLayout(new GridBagLayout());
words[1] = "JAVA";
words[2] = "FLOAT";
words[3] = "VOID";
words[4] = "MAIN";
words[5] = "STATIC";
words[6] = "FINAL";
words[7] = "PRIVATE";
words[8] = "CHAR";
words[9] = "IF";
rr = getRandomWord.nextInt(10);
for(int i = 1; i <=words[rr].length(); i++)
{
Labels[i] = new JButton();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
second.add(Labels[i]);
}
gridConstraints.gridx= 0;
gridConstraints.gridx= 0;
Second.add(second, gridConstraints);
guess1.setText("New Word");
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
Second.add(guess1, gridConstraints);
Here is my button's Action Performed method
// Action Performed method for the JButton guess1
guess1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
Pane.addTab("Game ", Second);
pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 *
(screenSize.height - getHeight())), getWidth(), getHeight());
}
}
Just add your new panel statement after the dispose(). for example : add
guess1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
new JFrame("New Window").show();
}
});
and one more point - you have created array of 9 element and you are trying to insert at 10 index that throws ArrayIndexOutOfBound exception.
You have to remove static keyword for your button and other controls, then you can do this
JTabbedPane Pane = new JTabbedPane();
JPanel Second = new JPanel();
JPanel second = new JPanel(); // This Panel is inside the Second Panel
JButton guess1 = new JButton();
String words[] = new String[10];
Random getRandomWord = new Random();
int rr;
JButton Labels[] = new JButton[10];
You have to create new instance of same class and show it
guess1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
new secondTab().show();
}
});
So, rather then closing the current window and creating a new instance of the window, which is just annoying (and a little lazy).
You should provide a means by which you can reset the state of your UI.
You should do this via some method call that resets the internal state and updates the UI.
You could accomplish the same thing by removing the "game" panel, creating a new instance of it and adding it back to the frame.
Blinking frames is a bad idea - IMHO
Hi,
Please try like this.. It may help..
guess1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
new AnotherJFrame();
}
}
---------------------------------------------
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AnotherJFrame extends JFrame
{
public AnotherJFrame()
{
super("Another GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Empty JFrame"));
pack();
setVisible(true);
}
}
I see your question has been answered, so this does not address your problem. I just thought I'd share some things you might want to condider fixing:
Don't use show()/hide(), because they are deprecated. [More info]
Use setVisible(true/false) respectively. [More info]
You don't have to add a new 'GridBagLayout()' before adding each component into the same container. I.e., you can remove the second getContentPane().setLayout(new GridBagLayout()); [More info]
Just make sure you understand that array-indices in Java (and all programming languages I know od - which isn't that much...but still) are zero-based ! [More info]
In order to find the center of the "usable" screen size Toolkit.getDefaultToolkit().getScreenSize(); isn't enough, since it includes screen-insets (e.g. non-visible margins, taskbars etc). You need to also use Toolkit.getDefaultToolkit().getScreenInsets(GraphicsConfiguration); and substract left and right insets from screen-width as well as top and bottom insets from screen-height.
If all you need is center a JFrame on the screen, you can simply use setLocationRelativeTo(null). [More info]
see the below link... It may help for you..
Java swing application, close one window and open another when button is clicked
So I need to used two classes for my GUI, one class is called "UI" and has a main method and the other is UIControls which will contain all the JPanels/Buttons and eventually the GridLayout. The only issue is my JFrame will not show any buttons or JPanels but before I made a seperate class for them everything worked fine.
Anyway thanks in advance =]
Regards -SKENG-
//EDIT: I already had "application.add(MP);" in the code I removed it before I posted it on this site. Cant remeber why I was just trying some things I've re-added it again now and It still doesnt work. Also the gridlayout was just a experiment I'm creating a different panel for that later ;)
UI - Main
import java.awt.*;
import javax.swing.*;
public class UI {
public static JFrame application;
public static void main(String []args) {
//=================FRAME SETTINGS=================
application = new JFrame("Despatch Depot Simulator");
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setLocation(500,200);
application.setSize(640,480);
application.setLayout(null);
application.setBackground(Color.WHITE);
application.setVisible(true);
application.setResizable(false);
}
}
UIControls
import java.awt.*;
import javax.swing.*;
public class UIControls extends UI {
public UIControls() {
//=================PANEL LAYOUT=================
JPanel MP = new JPanel(); //Main UI's Panel (MP = MainPanel)
MP.setBounds(1,1,640,480);
MP.setBackground(Color.WHITE);
MP.setLayout(null);
application.add(MP);
//=================JBUTTONS=================
JButton AddBox = new JButton("Add Box"); {MP.add(AddBox);}
AddBox.setBounds(505,2,125,30);
JButton AddTube = new JButton("Add Tube"); {MP.add(AddTube);}
AddTube.setBounds(505,34,125,30);
JButton AddEnvelope = new JButton("Add Envelope"); {MP.add(AddEnvelope);}
AddEnvelope.setBounds(505,66,125,30);
JButton ClearAll = new JButton("Clear All"); {MP.add(ClearAll);}
ClearAll.setBounds(505,98,125,30);
JButton CurrentCharge = new JButton("Current Charge"); {MP.add(CurrentCharge);}
CurrentCharge.setBounds(505,418,125,30);
JButton TotalCharge = new JButton("Total Charge"); {MP.add(TotalCharge);}
TotalCharge.setBounds(378,418,125,30);
JButton Save = new JButton("Save"); {MP.add(Save);}
Save.setBounds(2,418,125,30);
JButton Load = new JButton("Load"); {MP.add(Load);}
Load.setBounds(130,418,125,30);
//=================IMAGES=================
ImageIcon imageB = new ImageIcon ("..\\Images\\box.png");
ImageIcon imageBL = new ImageIcon ("..\\Images\\box-large.png");
ImageIcon imageEL = new ImageIcon ("..\\Images\\envelope-large.png");
ImageIcon imageEM = new ImageIcon ("..\\Images\\envelope-medium.png");
ImageIcon imageES = new ImageIcon ("..\\Images\\envelope-small.png");
ImageIcon imageT = new ImageIcon ("..\\Images\\tube.png");
ImageIcon imageTL = new ImageIcon ("..\\Images\\tube-large.png");
//=================LABELS=================
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel();
JLabel label4 = new JLabel();
JLabel label5 = new JLabel();
JLabel label6 = new JLabel();
JLabel label7 = new JLabel();
GridLayout experimentLayout = new GridLayout(4,3);
MP.setLayout(experimentLayout);
}
}
You are not adding your JPanel to your JFrame nor adding any JLabel or JButton to your JPanel.
Try :
add(MP); //somewhere in your UIControls constructor
Then, but this is another problem, why are you doing :
MP.setLayout(null);
First of all you should avoid null layout, then this method call is completely unuseful because after in your code you are setting MP layout to be a GridLayout (MP.setLayout(experimentLayout);)
In addition to that you are not constructing anywhere UIControls class.
In addition to 0verbose answer, I don't see why UIControl extends the UI class.
What you should do is organize your classes in a better way. One main class that "launch" and create the JFrame. For the UIControl class, you can add it as an attribute of the UI class, then instantiate it when the UI object is created, and add it to the panel/
public class Launcher {
public static void main(String[] args)
{
UI uiFrame = new UI();
}
}
public class UI extends JFrame {
// the panel that will be added to the JFrame
private UIControl uiControlPanel;
public UI()
{
super("JFrame title");
// set size, layout, and other stuffs here
//
this.uiControlPanel = new UIControl();
this.add(this.uiControlPanel);
// make the window visible
this.setVisible(true);
}
}
By the way, you might wanna name your classes with more explicit names than "UI", call them "MainFrame", "MainFramePanel", and so on so you can guess the type of the component just reading its name.
I think you should go through Swing tutorials of (Sun) Oracle again.