how to include diferrent swing items to main class from another class - java

I am quite new to java. I have created a GUI window with some jlabel , jtextfield. But recently for a project I need to create another class with those jlabel and jtextfield and need to display them to main class. But I dont know how to do that. I have seen this tutorial , but it has covered only with jmenu (not jtext field and jlabel) .
Adding Swing components from another class
my code is below,
public class common_items extends JFrame {
public void item_gui(String labelForMatrix) {
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JLabel lbl = new JLabel(labelForMatrix);
lbl.setBounds(5, 5, 424, 14);
lbl.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lbl);
JTextField txt2 = new JTextField();
txt2.setBounds(178, 117, 86, 20);
contentPane.add(txt2);
txt2.setColumns(10);
JTextField txt1 = new JTextField();
txt1.setColumns(10);
txt1.setBounds(178, 64, 86, 20);
contentPane.add(txt1);
JLabel lblRowNumber = new JLabel("Row number");
lblRowNumber.setBounds(189, 39, 67, 14);
contentPane.add(lblRowNumber);
JLabel lblColumnNumber = new JLabel("column number");
lblColumnNumber.setBounds(155, 95, 119, 14);
contentPane.add(lblColumnNumber);
}
}
I have tried to display them to main class but it fails . my main class code is below
common_items itm=new common_items();
itm.item_gui();
Plzz suggest me what should I do .

If I understood correctly what you are trying to do, you are trying to make a main JFrame class that includes components from other classes like the JLabel or the JTextArea that connect to the class and use them as normal components.
So what you need to do is just create a main class (not the JFrame) and make a JFrame class (call it mainFrame for example) and then just create the components class (e.g textArea JLabel ...) and then you just represent these classes as variables in the frame class (which we will be executing from the main class).
and maybe you just understand code better than speech:
Main class to start the program (load the frame class which contains everything)
public class Main {
public Main(){
//execute the frame
new Frame();
}
public static void main(String[] args) {
new Main(); //execute the function that launches the JFrame
}
}
Frame class which (obviously) contains the frame
import javax.swing.JFrame;
public class Frame extends JFrame{
private static final long serialVersionUID = -5151041547543472432L; //ignore this it is just the serial id of the JFrame you can omit this line from your code
ComponentsStorage cs = new ComponentsStorage(); //display class as variable so we can use it more efficnent
public Frame(){
launch(); //execute function
}
public void launch() { //launch
setTitle("Frame Demo");//title
setSize(640, 480);//size (width * height)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//close when close button is pressed
//you can just do ComponentStorage.tf.blah blah blah... but it is much easier as a variable
cs.label.setSize(500, 500); // you can mess up witht the components you stored there
cs.tf.setSize(40, 5); //as you can see here I am just adding the components by
//add them here
add(cs.label);
add(cs.tf);
setLocationRelativeTo(null);//by setting this you place the screen always in the middle of the screen
setVisible(true);//there is no point of creating JFrames if they aren't visible
}
}
And just another class that stores the components (JLabel, JTextField...) that you want to use (it can be any class that just contains these things even if there are other functions in it I named it ComponentStorage)
import javax.swing.JTextField;
import javax.swing.JLabel;
public class ComponentsStorage {
JLabel label = new JLabel();
JTextField tf = new JTextField();
}

Related

Java popup sending multiple action

The first popup would only send one action, the second would send two, third will be three so and so forth. I was able to narrow it down to it being the button sending action multiple time.
At first, I was using jframe for all my window, so I tried using jdialog, the problem persists. tried making it so that when the user clicks on the button the window is disposed, still don't fix it.
public class BoothDetails extends JDialog implements ActionListener{
FloorPlanGUI floorPlan = new FloorPlanGUI();
static JLabel bname = new JLabel();
JTextArea details = new JTextArea();
static JButton addsche = new JButton("ADD TO SCHEDULE");
JPanel northPanel = new JPanel();
public BoothDetails(String name, String detail) {
setVisible(true);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
bname.setText(name);
details.setText(detail);
setLayout(new BorderLayout());
northPanel.setLayout(new FlowLayout(0, 10, 10));
northPanel.add(bname);
northPanel.add(addsche);
addsche.addActionListener(floorPlan);
addsche.addActionListener(this);
add(northPanel, BorderLayout.NORTH);
add(details, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent a) {
dispose();
}
}
static JLabel bname = new JLabel();
JTextArea details = new JTextArea();
static JButton addsche = new JButton("ADD TO SCHEDULE");
Don't use the static keyword. This means the variable is shared by all instances of the class.
So every time you create a new instance of the class you execute the following code:
addsche.addActionListener(floorPlan);
which adds another ActionListener to the button.
The static keyword is should generally only be used when you create constant variables in your class, it should NOT be used for components which need to be unique for each class.

JFrame not working properly when I use methods to change its elements

I'm pretty new at Java and doing a basic college project. So I first made this class called ScreenDefiner, with an initialized JFrame called mainscreen as a field, and some JButtons and a JLabel (to set the background image), and other irrelevant stuff. Then I made a method called initializeScreen to set the JFrame's main properties, which would never change. Then another method, setScreenBeginning, which would add the buttons to mainscreen and change them, same with any other element in mainscreen that I wanted to change. The idea was to use various setScreen[something] to change what the user sees. But this really isn't working properly. I can't really describe what is happening, it's just bugging pretty hard. The screenshot below shows the most basic error: setScreenBeginning not making anything visible, but still changing the background (so the screenbg.setIcon line inside it must be working... right? Why isn't anything else working then?)
Btw, it works pretty well if I'm initializing and changing the interface in the same method, but my professor wouldn't like that (would be a gigantic method). So I guess there's some java definition/limitation that I don't know of and that keeps me from altering that stuff with outer methods?
Anyone who helps will get sent a photo of a happy strawberry.
The fail:
This is the code(I'm importing javax.swing.* and java.awt.*, but I couldn't paste that part here, guess I'm just a bit tired already):
public class ScreenDefiner {
JFrame mframe = new JFrame();
JLabel screenbg = new JLabel();
JButton pickClassButton = new JButton();
JButton pickClassBrute = new JButton();
JButton pickClassDetective = new JButton();
JButton pickStats = new JButton();
JButton start = new JButton();
JButton help = new JButton();
public void initializeScreen(){
screenbg.setLayout(new BorderLayout());
mframe.setSize(1280, 720);
mframe.setLayout(null);
mframe.setVisible(true);
mframe.setResizable(false);
mframe.setContentPane(screenbg);
mframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setScreenBeginning() {
screenbg.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\bg_basic.png"));
pickClassButton.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_pickclass.png"));
pickClassBrute.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_brute.png"));
pickClassDetective.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_detective.png"));
help.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_help.png"));
pickStats.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_pickstats.png"));
start.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_start.png"));
pickClassButton.setEnabled(true);
pickClassBrute.setEnabled(false);
pickClassDetective.setEnabled(false);
help.setEnabled(true);
pickStats.setEnabled(false);
start.setEnabled(true);
pickClassButton.setVisible(true);
pickClassBrute.setVisible(false);
pickClassDetective.setVisible(false);
help.setVisible(true);
pickStats.setVisible(false);
start.setVisible(false);
pickClassButton.setBounds(970, 159, 200, 96);
pickClassBrute.setBounds(970, 255, 200, 96);
pickClassDetective.setBounds(970, 351, 200, 96);
help.setBounds(970, 447, 200, 96);
pickStats.setBounds(970, 159, 200, 96);
start.setBounds(970, 159, 200, 96);
mframe.add(pickClassButton);
mframe.add(pickClassBrute);
mframe.add(pickClassDetective);
mframe.add(help);
mframe.add(pickStats);
mframe.add(start);
}
public class Main {
public static void main(String[] args) {
ScreenDefiner mainWindow = new ScreenDefiner();
mainWindow.initializeScreen();
mainWindow.setScreenBeginning();
}

Java Swing layout not appearing

I'm just getting into creating GUIs in Java, and with this basic setup, I can't get anything to appear in my JFrame:
public class Main extends JFrame {
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.setSize(400,400); // setting size
jframe.setVisible(true); // Allow it to appear
jframe.setTitle("Lab 7");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main init = new Main();
}
public Main() {
Container pane = getContentPane();
pane.setBackground(Color.BLUE);
pane.setLayout(new FlowLayout());
JButton add = new JButton("Add");
JButton close = new JButton("Close");
JTextArea area = new JTextArea();
JScrollPane scroll = new JScrollPane(area);
add.setBounds(70, 125, 80, 20);
close.setBounds(70, 115, 80, 20);
pane.add(add);
pane.add(close);
pane.add(scroll);
AddClick added = new AddClick();
add.addActionListener(added);
}
}
I also tried moving all the JFrame stuff into public Main() but it caused an infinite amount of windows opening and I had to end the program each time.
You're creating two separate JFrames: one is your Main class, and the other is an unrelated JFrame. Most of the customization, including adding components, happens to the Main in its constructor. But you only ever set the other JFrame to be visible.
Use your Main instance as the JFrame instead of creating another one, and the problem will be fixed.
public static void main(String[] args) {
JFrame jframe = new Main(); //Use an instance of Main as your JFrame
jframe.setSize(400,400); // setting size
jframe.setVisible(true); // Allow it to appear
jframe.setTitle("Lab 7");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Why are the contents of my JFrame not displaying correctly?

For the sake of less code, I am taking out code that is unrelevant to the problem, such as addActionListener(); etc.
My main class is public class TF2_Account_Chief
I have my main Jframe f; and its contents:
private static JFrame f = new JFrame("TF2 Account C.H.I.E.F.");
private JLabel runnableTogetherLabel = new JLabel("How many idlers would you like to run at a time?");
private static JTextField runnableTogetherInput = new JTextField();
private JButton runButton = new JButton("Run!");
private JButton stopButton = new JButton("Stop!");
private JButton resetButton = new JButton("Reset!");
private JButton exitButton = new JButton("Exit!");
and I set the properties of all the contents:
public void launchFrame() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
f.add(runnableTogetherInput);
f.add(runnableTogetherLabel);
f.add(runButton);
f.add(stopButton);
f.add(resetButton);
f.add(exitButton);
f.setSize(625, 500);
runnableTogetherInput.setSize(35, 20);
runnableTogetherLabel.setSize(275, 25);
runButton.setSize(60, 25);
stopButton.setSize(65, 25);
resetButton.setSize(70, 25);
exitButton.setSize(60, 25);
f.setLocation(0, 0);
runnableTogetherInput.setLocation(285, 3);
runnableTogetherLabel.setLocation(5, 0);
runButton.setLocation(330, 0);
stopButton.setLocation(395, 0);
resetButton.setLocation(465, 0);
exitButton.setLocation(540, 0);
}
then I have my main() method:
public static void main(String[] args) throws IOException {
TF2_Account_Chief gui = new TF2_Account_Chief();
gui.launchFrame();
Container contentPane = f.getContentPane();
contentPane.add(new TF2_Account_Chief());
}
And then I have my second JFrame iF which is not displaying the contents correctly:
private void invalidInput() {
JFrame iF = new JFrame("Invalid Input!");
JLabel iL = new JLabel("The input you have entered is invalid!");
JButton iB = new JButton("Exit!");
Container contentPane2 = iF.getContentPane();
contentPane2.add(new TF2_Account_Chief());
iF.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iF.pack();
iF.setVisible(true);
iF.add(iL);
iF.add(iB);
iF.setSize(500, 300);
iL.setSize(125, 25);
iB.setSize(60, 25);
iF.setLocation(0, 0);
iL.setLocation(0, 15);
iB.setLocation(0, 45);
}
Now, JFrame iF is launched when the invalidInput() method is called, but you can't see that because that part of the code is unrelevant to the problem. What does matter is that the JFrame iF is launched.
The new frame looks like this:
Any ideas on why the contents are not displaying properly?
(By improperly, I mean the JButton iB takes up the whole frame and the frame is a light blue instead of the normal grey.)
You are using absolute positions without using a null layout, that's why you see a large button.
To see every component, you have to use
iF.setLayout(null);
but it's not a good practice, I'd suggest you to learn how to use Layouts and leave all the work to the layout manager
The default layout of JFrame is BorderLayout, in which there are "5" locations you can put your components to
CENTER
PAGE_START
PAGE_END
LINE_START
LINE_END
So, iF.add(component) will add the component to the CENTER, you can specify the location like this:
iF.add(component, BorderLayout.PAGE_END);
//You can also put PAGE_START, LINE_START, LINE_END, CENTER
Take my advice and read more about BorderLayout, because if you refuse to learn Layout Managers, you probably go to Absolute Positioning( null layout) which is not a good way and must not be used.

Unable to set button's location in java swing application

I am new to Java and was trying to develop a basic swing application. I wanted to set the location of the button on the JFrame. I tried to do this but was unable to do this this is my code. I am using eclipse for development
public class MyUI extends JFrame {
JButton button1 = new JButton("Click");
JTextField tb1 = new JTextField(5);
JPanel panel1 = new JPanel();
public MyUI() {
super("Test");
setVisible(true);
this.setLayout(null);
panel1.setLayout(null);
panel1.setVisible(true);
button1.setVisible(true);
panel1.add(button1);
add(panel1);
panel1.setLocation(10, 10);
button1.setLocation(10, 10);
setDefaultCloseOperation(EXIT_ON_CLOSE);
button1.addActionListener(this);
}
public static void main(String[] args) {
MyUI gui = new MyUI();
gui.setSize(400, 300);
}
}
1.why you put two JComponents to the same Bounds
panel1.setLocation(10, 10);
button1.setLocation(10, 10);
2.have look at Initials Thread
3.public class MyUI extends JFrame {
should be
public class MyUI extends JFrame implements ActionListener{
4.don't extend JFrame, create a local variable
5.setVisible(true); should be (in this form) only last code line into MyUI() constructor
6.setVisible(true); is important issue, you visibled JFrame and then to add JComponent(s)
7.don't use NullLayout, use proper LayoutManager, in the case that you remove this.setLayout(null); and panel1.setLayout(null); added JComponents could be visible
8.use pack() before setVisible(true) as last two code lines in constructor
EDIT (by using built_in LayoutManagers, BorderLayout for JFrame and FlowLayout for JPanel)
import java.awt.event.*;
import javax.swing.*;
public class MyUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton button1 = new JButton("Click");
private JTextField tb1 = new JTextField(5);
private JPanel panel1 = new JPanel();
public MyUI() {
super("Test");
panel1.add(tb1);
panel1.add(button1);
add(panel1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
button1.addActionListener(this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyUI testing = new MyUI();
}
});
}
}
Your panel and button are not seen because they have zero size. Add something like:
panel1.setSize(100, 100);
button1.setSize(80, 30);
or use the setBounds method which is more convenient to set location and size simultaneously:
panel1.setBounds(10, 10, 100, 100);
button1.setBounds(10, 10, 80, 30);
Would like to suggest something, though its not the direct immediate answer to your question, but still its important from my point of view....
You can use Group Layout which was developed by NetBeans team back in 2005, its awesome to work with.... Try using the Windows Builder Pro which is provided by Google for free now... You can get your application up and running in no time......

Categories