Jbutton disappears in design view - java

I'm using WindowBuilder in Eclipse. I Created the following method to apply the same properties to certain types of buttons in my application.
In design view, my btn_Subscribe is invisible, but it appears when debugging.
However my btn_Login is visible in design view... I don't get it. I'm using my method when I add the JButton to the content
// ************************ LOGIN BUTTON ************************ \\
JButton btn_Login = new JButton("");
btn_Login.setIcon(new ImageIcon(DietProject.class.getResource("/images/img_login.png")));
btn_Login.setBounds(226, 89, 91, 32);
frmDietPlanner.getContentPane().add(setupCustomButton(btn_Login));
// ************************ SUBSCRIBE BUTTON ************************ \\
JButton btn_Subscribe = new JButton("");
btn_Subscribe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btn_Subscribe.setIcon(new ImageIcon(DietProject.class.getResource("/images/img_subscribe.png")));
btn_Subscribe.setBounds(10, 11, 103, 32);
frmDietPlanner.getContentPane().add(setupCustomButton(btn_Subscribe));
private JButton setupCustomButton(JButton jb)
{
// Remove the ugly border and background on the button
jb.setBorderPainted(false);
jb.setBorder(null);
jb.setContentAreaFilled(false);
jb.setCursor(new Cursor(Cursor.HAND_CURSOR));
return jb;
}

I assume frmDietPlanner is a JFrame which has by default BorderLayout manager.
By
frmDietPlanner.getContentPane().add(setupCustomButton(btn_Login));
frmDietPlanner.getContentPane().add(setupCustomButton(btn_Subscribe));
You are adding two buttons to the same location.
If you want to use setBounds set layout manager to null.
An MCVE for the problem and the solution looks like this:
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame {
Frame()
{
/////////////////////////////
setLayout(null);
////////////////////////////
setSize(400,400);
JButton btn_Login = new JButton("A");
btn_Login.setBounds(226, 89, 91, 32);
getContentPane().add(btn_Login);
JButton btn_Subscribe = new JButton("B");
btn_Subscribe.setBounds(10, 11, 103, 32);
getContentPane().add(btn_Subscribe);
setVisible(true);
}
public static void main(String[] args)
{
new Frame();
}
}

If I do the following, it shows up in the designer just fine. I don't get why using a method to apply the same properties would cause the designer not to display the button.... and at the same time it works perfectly fine for my login button! I really don't feel like doing this code for every single button I plan on using....
//frmDietPlanner.getContentPane().add(setupCustomButton(btn_Subscribe));
frmDietPlanner.getContentPane().add(btn_Subscribe);
btn_Subscribe.setBorderPainted(false);
btn_Subscribe.setBorder(null);
btn_Subscribe.setContentAreaFilled(false);
btn_Subscribe.setCursor(new Cursor(Cursor.HAND_CURSOR));

Related

Eclipse project wont run

I'm new to eclipse and java, I'm trying to switch between two panels with the use of a button. i want to test my project but when i try to run it it launches, gives no errors and then nothing happens.
Have i missed something that i need to do before to make this run?
This is the version i have and i downloaded it earlier today.
Eclipse IDE for Java Developers
Version: 2019-09 R (4.13.0)
Build id: 20190917-1200
And below is my code if there is anything stopping it from working in there.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Music_Test {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Music_Test window = new Music_Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Music_Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel Menu = new JPanel();
Menu.setBounds(6, 6, 438, 266);
frame.getContentPane().add(Menu);
Menu.setLayout(null);
Menu.setVisible(true);
JPanel Select_Level = new JPanel();
Select_Level.setBounds(6, 6, 438, 266);
frame.getContentPane().add(Select_Level);
Select_Level.setVisible(false);
JButton btnSelectLevel = new JButton("Select Level");
btnSelectLevel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.setVisible(false);
Select_Level.setVisible(true);
}
});
btnSelectLevel.setBounds(158, 45, 117, 29);
Menu.add(btnSelectLevel);
JLabel lblMenu = new JLabel("Menu");
lblMenu.setFont(new Font("Comic Sans MS", Font.BOLD, 22));
lblMenu.setBounds(187, 17, 61, 29);
Menu.add(lblMenu);
JLabel lblSelectLevel = new JLabel("Select Level");
lblSelectLevel.setFont(new Font("Comic Sans MS", Font.BOLD, 22));
lblSelectLevel.setBounds(187, 17, 61, 29);
Select_Level.add(lblSelectLevel);
}
}
Start by using a different layout manager, FlowLayout or GridBagLayout might work better
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
These layouts will honour the preferred sizes of your buttons
As for opening another window, well, you've already create one, so the process is pretty much the same. Having said that, you might consider having a look at The Use of Multiple JFrames: Good or Bad Practice? before you commit yourself to far.
A better approach might be to use a JMenuBar and JMenuItems to act as the "open" and "exit" actions. Take a look at How to Use Menus then you could use a CardLayout to switch between views instead, for example
From a pure design perspective (I know it's only practice, but perfect practice makes perfect), I wouldn't extend anything from JFrame and instead would rely on building your main GUIs around something like JPanel instead.
This affords you the flexibility to decide how to use these components, as you could add them to frames, applets or other components...
AND
Although you have implemented the actionPerformed method as per the ActionListener interface, you class is not of that that type as you haven't implemented the interface. Once you implement that interface and register it with the JButton btnAdd,
btnAdd.addActionListener(this);
the method will be called.
A more compact alternative might be to use an anonymous interface:
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle button ActionEvent & display dialog...
}
});
Side notes:
Using more than one JFrame in an application creates a lot of overhead
for managing updates that may need to exist between frames. The
preferred approach is to use a modal JDialog if another window is
required. This is discussed more Here

Scroll Bar not appearing along with JTextArea

okay, so I recently made a java console application that brute forced your password so now I was working on a similar app but with a gui.
So I have all the code and its running but for some reason, a scroll bar I added to a textArea is not appearing and when I run the program iI get neither the scroll bar nor the text area.
Please tell me where I am going wrong and help me solve this issue.
package swinggui;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class BruteForce {
static JFrame frameObject;
static JPanel panelObject;
JLabel lblPassword;
JTextField txtPassword;
JTextArea txtStatus;
JScrollPane scrollbar;
JButton btn;
BruteForce() {
panelObject = new JPanel();
frameObject.getContentPane().add(panelObject);
panelObject.setLayout(null);
txtStatus = new JTextArea("Status: ");
txtStatus.setBounds(10,95,260,160);
panelObject.add(txtStatus);
lblPassword = new JLabel("Password: ");
txtPassword = new JTextField();
Font dialog = new Font("Dialog", Font.PLAIN, 14);
lblPassword.setBounds(10,10,100,30);
lblPassword.setFont(dialog);
panelObject.add(lblPassword);
txtPassword.setBounds(80,10,190,30);
panelObject.add(txtPassword);
scrollbar = new JScrollPane(txtStatus);
panelObject.add(scrollbar);
btn = new JButton("Test Password Strength");
btn.setBounds(10,50,260,30);
panelObject.add(btn);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int password = Integer.parseInt(txtPassword.getText());
int guess_password = 0;
while(guess_password != password) {
txtStatus.append("\n [+] Password Attempt: " + guess_password);
guess_password = guess_password + 1;
}
if(guess_password == password) {
txtStatus.append("\n \n [-] Password Found: " + guess_password);
}
}
});
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frameObject = new JFrame("Brute Force Tool");
frameObject.setVisible(true);
frameObject.setSize(300,300);
frameObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BruteForce gui = new BruteForce();
}
}
Please tell me where I am going wrong and correct my code.
Any help will be appreciated and thanks in advance.
First of all an important hint: Don't use null layout. Please learn all standard layout manager and use them to fill your UI. Also you can use some third-party layout manager like MigLayout or FormLayout (use Google to find them). These managers are often better then the standard.
Why is it better than null-layout? because Java-UI is cross-platform and some components can require different size on different OSs. The same can occur when the user uses some OS-features (like font scaling). Also layout manager defines the resize behavoir (what should happen when user changes the size of the window).
And here is the corrected version of your code (without layout manager change).
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class BruteForce {
static JFrame frameObject;
JPanel panelObject;
JLabel lblPassword;
JTextField txtPassword;
JTextArea txtStatus;
JScrollPane scrollbar;
JButton btn;
BruteForce() {
panelObject = new JPanel();
frameObject.getContentPane().add(panelObject);
panelObject.setLayout(null);
txtStatus = new JTextArea("Status: ");
// set bounds not required here. it's required for scrollbar
// txtStatus.setBounds(10,95,260,160);
panelObject.add(txtStatus);
lblPassword = new JLabel("Password: ");
txtPassword = new JTextField();
Font dialog = new Font("Dialog", Font.PLAIN, 14);
lblPassword.setBounds(10, 10, 100, 30);
lblPassword.setFont(dialog);
panelObject.add(lblPassword);
txtPassword.setBounds(80, 10, 190, 30);
panelObject.add(txtPassword);
scrollbar = new JScrollPane(txtStatus);
// set the scroll bar bounds
scrollbar.setBounds(10, 95, 260, 160);
panelObject.add(scrollbar);
btn = new JButton("Test Password Strength");
btn.setBounds(10, 50, 260, 30);
panelObject.add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int password = Integer.parseInt(txtPassword.getText());
int guess_password = 0;
while (guess_password != password) {
txtStatus.append("\n [+] Password Attempt: " + guess_password);
guess_password = guess_password + 1;
}
if (guess_password == password) {
txtStatus.append("\n \n [-] Password Found: " + guess_password);
}
}
});
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frameObject = new JFrame("Brute Force Tool");
BruteForce gui = new BruteForce();
frameObject.add(gui.panelObject); // don't forget to place your panel in the window
frameObject.setSize(300, 300);
frameObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameObject.setLocationRelativeTo(null); // center location for window
frameObject.setVisible(true);
}
}
You do realize that you don't need an application to figure out that if you supply an integer password value (like 55673) and if you iterate through each value one at a time in a loop that it will take the password number of attempts (55673 iterations) to get to that password. We'll just chalk it up as an example. :/
In my opinion there are a number of issues with your particular project that needs some attention:
For a little easier coding, set the BruteForce Class so that it extends JFrame: public class BruteForce extends javax.swing.JFrame {. You won't need the static JFrame variable (frameObject) and it cleans things up somewhat.
Take out all that code related to the JFrame out of the main() method. Do your JFrame setup within a initialization method instead. In my opinion, I think your main() method would be better if you have:
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new BruteForce().setVisible(true);
}
});
}
And your initialization method might look like this:
private void initializeComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Brute Force Tool");
setResizable(false);
setAlwaysOnTop(true);
// Size the Form
// Slightly different from original size since
// form has been made non-resizable. Makes the
// form more uniformed.
setPreferredSize(new Dimension(285, 325));
setSize(getPreferredSize());
// Center Form to screen. Should always be after sizing
setLocationRelativeTo(null);
panelObject = new JPanel();
panelObject.setLayout(null);
// Password Box Label
Font dialog = new Font("Dialog", Font.PLAIN, 14);
lblPassword = new JLabel("Password: ");
lblPassword.setBounds(10, 10, 100, 30);
lblPassword.setFont(dialog);
panelObject.add(lblPassword);
// Password Entry Text Field
txtPassword = new JTextField();
txtPassword.setBounds(80, 10, 190, 30);
panelObject.add(txtPassword);
// Text Area with Scroll Pane to display
// Brute Force process.
txtStatus = new JTextArea("Status: ");
scrollbar = new JScrollPane(txtStatus);
scrollbar.setBounds(10, 125, 260, 160);
panelObject.add(scrollbar);
// Button to start Brute Force Process
btn = new JButton("Test Password Strength");
btn.setBounds(10, 50, 260, 30);
panelObject.add(btn);
// Display Progress CheckBox
chkUpdateStatus = new JCheckBox("Display Progress");
chkUpdateStatus.setBounds(10, 85, 150, 30);
panelObject.add(chkUpdateStatus);
// Scroll Progress CheckBox
chkScrollUpdate = new JCheckBox("Scroll Progress");
chkScrollUpdate.setBounds(160, 85, 150, 30);
panelObject.add(chkScrollUpdate);
// Add filled JPanel to JFrame
panelObject.setBounds(this.getBounds());
getContentPane().add(panelObject);
// Add Button Action Listener
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!workThreadIsRunning) {
// Clear the TextArea
txtStatus.setText(null);
new Thread(workThread).start();
}
if (btn.getText().equals("Cancel Test")) {
shutDownThread = true;
}
}
});
}
Which then means that your class constructor (BruteForce()) simply contains:
public BruteForce() {
initializeComponents();
}
If you are not going to use JFrame#pack() so that JFrame is automatically sized according to all its contents at or above their preferred sizes then the setSize() method to size the JFrame on its own won't help you much. You will also need to use the setPreferredSize() method as well in this case.
When creating your form, you want to add JTextArea into the JScrollPane, not the JPanel. It will then be the JScrollPane you add into the JPanel.
The setBounds() for JTextArea is not required since it will be filling the entire JScrollPane container. With the null layout you are using it will be the JScrollPane which will need the setBounds() supplied.
Since you are using the Null layout and your application window is
indeed small enough, and you've set boundries for all the components, you should also ensure that the JFrame window can not be resized (setResizable(false);) since the form would look ridiculous if it was. I'm sure you've been preached to enough to know why Null Layout is not necessarily a good choice. But if that isn't enough for you then Google this: Why is null layout in Swing frowned upon?. It does however have its place in the world especially when utilizing multiple layouts.
On a side note:
Understandably, when processing something like this it is usually nice to see the progress of that process while it is being carried out. The sad reality is that speed is seriously hampered when trying to do so.
To effectively update the JTextArea by appending a line to it indicating the brute force attempt (iteration) processed you need to use a new thread to carry out that updating. This of course means that the processing (attempts) are carried out in a separate Thread and not done within the Event Dispatch Thread (EDT) which will not update the JTextArea until all the processing is complete (which is what you are doing in your code). By placing the processing code within its own thread that updates the JTextArea immediatly is really the only viable option but it does takes time to write that update to the JTextArea...considerable time as a matter of fact.
As an example if you run the supplied runnable code (your code modified) below and supply a password of 222222, on my system it will take about 2147 milliseconds (around 2 seconds) to complete the task. If you were to comment out the textStatus.append(...) within the loop you would find that it only takes about 6 milliseconds (around 0.006 seconds) to complete the task. This is a very significant difference in processing time and if you're doing something like Brute Force you want every scrap of speed you can get. If you want the JTextArea to automatically scroll so as to display each update within the view port then speed is hampered much much more.
Progress display should be made optional with the use of Check Boxes which I did implement in the sample runnable code below and because the brute force processing is done within its own thread rather than the EDT, any changes to the Check Boxes takes immediate affect. The button also has a more toggle effect so that brute force processing can be canceled.
Here's the full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BruteForce extends javax.swing.JFrame {
JPanel panelObject;
JLabel lblPassword;
JTextField txtPassword;
JTextArea txtStatus;
JScrollPane scrollbar;
JButton btn;
JCheckBox chkUpdateStatus;
JCheckBox chkScrollUpdate;
Runnable workThread;
boolean workThreadIsRunning = false;
volatile boolean shutDownThread = false;
public BruteForce() {
initializeComponents();
workThread = new Runnable() {
#Override
public void run() {
long startTime = System.currentTimeMillis();
workThreadIsRunning = true;
int password = Integer.parseInt(txtPassword.getText());
btn.setText("Cancel Test");
int guess_password = 0;
while (guess_password != password & !shutDownThread) {
if (chkUpdateStatus.isSelected()) {
txtStatus.append("\n [+] Password Attempt: " + String.valueOf(guess_password + 1));
if (chkScrollUpdate.isSelected()) {
// Update The JTextArea to show immediate processing.
// (Slows down processing considerably)
txtStatus.setCaretPosition(txtStatus.getText().length() - 1);
}
}
guess_password++;
}
long duration = System.currentTimeMillis() - startTime;
if (guess_password == password) {
txtStatus.append("\n \n [-] Password Found: " + guess_password);
txtStatus.append("\n [-] It took " + duration + " milliseconds\n "
+ "(just over " + String.valueOf(duration / 1000) + " seconds) "
+ "to\n accomplish.");
txtStatus.setCaretPosition(txtStatus.getText().length() - 1);
}
workThreadIsRunning = false;
btn.setText("Test Password Strength");
shutDownThread = false;
}
};
}
private void initializeComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Brute Force Tool");
setResizable(false);
setAlwaysOnTop(true);
// Size the Form
// Slightly different from original size since
// form has been made non-resizable. Makes the
// form more uniformed.
setPreferredSize(new Dimension(285, 325));
setSize(getPreferredSize());
// Center Form to screen. Should always be after sizing
setLocationRelativeTo(null);
panelObject = new JPanel();
panelObject.setLayout(null);
// Password Box Label
Font dialog = new Font("Dialog", Font.PLAIN, 14);
lblPassword = new JLabel("Password: ");
lblPassword.setBounds(10, 10, 100, 30);
lblPassword.setFont(dialog);
panelObject.add(lblPassword);
// Password Entry Text Field
txtPassword = new JTextField();
txtPassword.setBounds(80, 10, 190, 30);
panelObject.add(txtPassword);
// Text Area with Scroll Pane to display
// Brute Force process.
txtStatus = new JTextArea("Status: ");
scrollbar = new JScrollPane(txtStatus);
scrollbar.setBounds(10, 125, 260, 160);
panelObject.add(scrollbar);
// Button to start Brute Force Process
btn = new JButton("Test Password Strength");
btn.setBounds(10, 50, 260, 30);
panelObject.add(btn);
// Display Progress CheckBox
chkUpdateStatus = new JCheckBox("Display Progress");
chkUpdateStatus.setBounds(10, 85, 150, 30);
panelObject.add(chkUpdateStatus);
// Scroll Progress CheckBox
chkScrollUpdate = new JCheckBox("Scroll Progress");
chkScrollUpdate.setBounds(160, 85, 150, 30);
panelObject.add(chkScrollUpdate);
// Add filled JPanel to JFrame
panelObject.setBounds(this.getBounds());
getContentPane().add(panelObject);
// Add Button Action Listener
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!workThreadIsRunning) {
// Clear the TextArea
txtStatus.setText(null);
new Thread(workThread).start();
}
if (btn.getText().equals("Cancel Test")) {
shutDownThread = true;
}
}
});
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new BruteForce().setVisible(true);
}
});
}
}

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();
}

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

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();
}

My JButton action listener is not working

My ActionListener codes for a JButton to go to another JPanel, but it's not working properly, though it used to work before. My code is as follows:
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JPanel contentPane = new ListofDuties2(myFrame);
myFrame.getContentPane().removeAll();
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnNext.setBounds(194, 381, 89, 23);
add(btnNext);
I'm not really sure what's wrong with it.
When adding/removing components from a visible GUI the basic code is:
panel.remove(...);
panel.add();
panel.revalidate(); // to invoke the layout manager
panel.repaint();
The question is why are you using removeAll()? Any time I see code like that it means you should probably be using a Card Layout and then just swap panels.
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JPanel contentPane = new ListofDuties2(myFrame);
myFrame.getContentPane().removeAll();
myFrame.setContentPane(contentPane);
myFrame.getContentPane().revalidate();
myFrame.setVisible(true);
}} );
You forgot a ); in the end
Also call revalidate()

Categories