i am trying to make an UI in java and i am new in this so sorry if it's an easy question.
public class viewDeneme extends JFrame {
private static final long serialVersionUID = -7284396337557548747L;
private JTextField nameTxt = new JTextField(10);
private JTextField passwordTxt = new JTextField(10);
private JButton loginBtn = new JButton("Giriş");
private JLabel nameLbl = new JLabel("Kullanıcı adi:");
private JLabel passwordLbl = new JLabel("Şifre:");
public viewDeneme(){
JPanel loginPanel = new JPanel();
this.setSize(600,200);
this.setLocation(600, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nameLbl.setBounds(200, 200, 100, 50);
loginPanel.add(nameTxt);
loginPanel.add(passwordTxt);
loginPanel.add(loginBtn);
loginPanel.add(nameLbl);
loginPanel.add(passwordLbl);
this.setVisible(true);
this.add(loginPanel);
}
public static void main(String[] args) {
new viewDeneme();
}
}
here is my code.I am trying to set bounds for labels and textboxes but it's not changing anything.There isn't any error so i must missing something but i couldn't find it with searching in web.Thanks for your help
See What is setBounds and how do I use it?
JPanel layout must be null to use absolute positioning. JPanel object is initialized to use a FlowLayout, unless you specify differently when creating the JPanel. So you must write
loginPanel.setLayout(null);
Related
I am trying to create a GUI payroll calculator for a Java class I am taking. The requirements were that it must take the user inputs (one using a JComboBox), calculate the weekly pay and add the results to a JTable. The user should be able to continue calculating for other employees and have an exit button. I created the GUI in the main class and need two ActionListeners, one to exit and one to calculate and add to the JTable.
My problem is that when I start working on the calculate ActionListener, it is not recognizing the variables I set in the main class. I have tried making them public, using the main class name DOT variable name (PayrollCalc.empName), initializing them and nothing seems to work. The code is not complete, as I have not even started to add to the JTable until I can get the actual calculations done first. Does anyone have any suggestions?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PayrollCalc {
public static void main(String[] args) {
//Declare variables used
String empName = null, entDept = null, calcdPay = null;
String[] empDept = {"Marketing","IT","Accounting","Development","Payroll","Facilities"};
String columnNames[] = {"Name","Department","Pay Check"};
String dataValues [][] = {
{empName,entDept,calcdPay}
};
double wrkHours = 0;
double empRate = 0;
double wklyPay = 0;
//Create JTable and scrollPane for output
JTable table;
JScrollPane scrollPane;
table = new JTable (dataValues,columnNames);
scrollPane = new JScrollPane(table);
//Create JFrame object with title
JFrame frame = new JFrame("Employee Payroll Calculator");
//Create combo box for department choices
JComboBox combo = new JComboBox(empDept);
JTextField nameField = new JTextField(15);
JTextField hourField = new JTextField(10);
JTextField rateField = new JTextField(10);
//Create JLables for input fields
JLabel nameLbl = new JLabel ("Name:");
JLabel hourLbl = new JLabel ("Hours:");
JLabel rateLbl = new JLabel ("Rate:");
JLabel deptLbl = new JLabel ("Department:");
//Create buttons for ActionListners
JButton exitButton= new JButton("Exit");
exitButton.addActionListener(new exitApp());
exitButton.setSize(5,5);
JButton calcButton= new JButton("Calculate");
calcButton.addActionListener(new calcApp());
calcButton.setSize(5,5);
//Create panels
Panel panel1 = new Panel();
panel1.add(nameLbl);
panel1.add(nameField);
panel1.add(deptLbl);
panel1.add(combo);
panel1.add(hourLbl);
panel1.add(hourField);
panel1.add(rateLbl);
panel1.add(rateField);
panel1.add(rateField);
Panel panel2 = new Panel();
panel2.add(calcButton);
Panel panel3 = new Panel();
panel3.add(calcButton);
panel3.add(exitButton);
Panel panel4 = new Panel();
panel4.add(scrollPane, BorderLayout.CENTER);
//creates the frame
frame.setSize(950,200);
frame.add(panel1,BorderLayout.NORTH);
frame.add(panel2);
frame.add(panel3, BorderLayout.SOUTH);
frame.add(panel4);
frame.setVisible(true);
}
//ActionListner for Exit button
static class exitApp implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
//ActionListner for Calculate button
static class calcApp implements ActionListener
{
public void actionPerformed(ActionEvent c)
{
empName = nameField.getText();
entDept = combo.getName();
wrkHours = Double.parseDouble(hourField.getText());
empRate = Double.parseDouble(rateField.getText());
wklyPay = wrkHours * empRate;
calcdPay = new Double(wklyPay).toString();
}
}
}
Look , every variable has its Scope ... and you have not defined anything as a member class variable so nothing will act as a global variable .
you have defined variable inside main method () so their scope is limited to only main method thats the reason behind your problem .
Since the variables you're trying to access in your ActionListener are local to your main() they are not visible to your static class. Also, initializing your GUI inside the static main() is forcing the use of statics every where which as you can tell from the comments below is a bad practice.
So, move the initialization out to a constructor and the local variables as instance level member fields. Along with this you would need to switch from static nested classes to using inner classes instead.
Instance members of your class would then be available to your inner ActionListener classes.
public class PayrollCalc {
//Declare variables used
private String empName = null, entDept = null, calcdPay = null;
private double wrkHours = 0;
private double empRate = 0;
private double wklyPay = 0;
private JComboBox combo;
private JTextField nameField;
private JTextField hourField;
private JTextField rateField;
public static void main(String[] args) {
new PayrollCalc();
}
public PayrollCalc() {
// ...
combo = new JComboBox(empDept);
nameField = new JTextField(15);
hourField = new JTextField(10);
rateField = new JTextField(10);
// ...
}
// non-static ActionListener inner classes
}
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.
I'm trying to set the components of this application to a set location using setLocation so far i haven't been able to move the components. There is more code but its get calling and setting this code for the most part. any ideas?
import javax.swing.*;
public class HangmanPanel extends JPanel {
private static final long serialVersionUID = -5793357804828609325L;
public HangmanPanel(){
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//Button.addActionListener();
JLabel tfLable = new JLabel("Please Enter a Letter");
JTextField text = new JTextField(10);
String input = text.getText();
heading.setLocation(50, 20);
tfLable.setLocation(20, 100);
text.setLocation(320, 50);
Button.setLocation(230, 100);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
}
}
You should not use setLocation() to layout Swing components, it is much better to use a Layout. Please have a look at these Layout Tutorials.
I'm trying to make a simple menu for my game. I have 4 buttons in the center and I want to make them a little bit bigger and center them.
The last part worked but I can't seem to call any of my JButtons and do a .setSize / .setPreferedSize(new Dimension()) on it.
public class mainMenu extends JFrame {
private JButton start, highscore, help, stoppen;
public mainMenu() {
super("Master Mind");
maakComponenten();
maakLayout();
toonFrame();
}
private void maakComponenten() {
start = new JButton("Start");
start.setBackground(Color.gray);
highscore = new JButton("Higscores");
help = new JButton("Help");
stoppen = new JButton("Stoppen");
}
private void maakLayout() {
JPanel hoofdmenu = new JPanel();
hoofdmenu.setLayout(new BoxLayout(hoofdmenu, BoxLayout.Y_AXIS ));
hoofdmenu.add(start);
start.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(highscore);
highscore.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(help);
help.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(stoppen);
stoppen.setAlignmentX(CENTER_ALIGNMENT);
super.add(hoofdmenu);
}
private void toonFrame() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args) {
new mainMenu();
}
}
As an example, to change the size of the "Start" button,
change :
start1 = new JButton("Start");
to
start1 = new JButton("Start") {
{
setSize(150, 75);
setMaximumSize(getSize());
}
};
The problem is that JFrames use BorderLayout by default, which means that your JPanel will naturally fill the space.
Before adding your JPanel, call the following code to change the JFrame's layout to null and use the JPanel's settings instead.
this.setLayout(null);
JPanel hoofdmenu = new JPanel();
hoofdmenu.setBounds(0,0, 400, 100);
Alternatively, you could set the maximum size of the JButtons
Dimension maxSize = new Dimension(100, 100);
start.setMaximumSize(maxSize);
highscore.setMaximumSize(maxSize);
help.setMaximumSize(maxSize);
stoppen.setMaximumSize(maxSize);
Here's another example following behind the previous two - I'm making a soundboard program, and this is actually a sample from it - The JPanel actually is needed, agreeing to the second post.
JFrame frame = new JFrame();
JPanel menuPanel = new JPanel();
JButton Button1 = new JButton("<BUTTON NAME 1>");
Button1.setSize(80, 30);
Button1.setLocation(4, 4);
JButton Button2 = new JButton("<BUTTON NAME 2>");
Button2.setSize(80, 30);
Button2.setLocation(90, 4);
Ah, and another thing - You created the buttons in a different block from the second piece of code. Doing that causes the other blocks to not see it. You need to declare them outside the block so all the blocks can see them.
I am trying to create a form manually with code rather than the designer, I have already created using the designer.
This is the manual code that I came up with so far but I am having problem aligning the label and textfield side by side
mport java.awt.*;
import javax.swing.*;
/**
*
* #author jackandjill
*/
public class summinup_copy extends JFrame
{
private JLabel lblTitle, lblOctal, lblDecimal, lblMessage ;
private JTextField txtOctal, txtDecimal;
private JButton calculate_btn;
public summinup_copy()
{
JPanel panel = (JPanel)this.getContentPane();
panel.setLayout(new BorderLayout());
JPanel panCentre = new JPanel();
panCentre.setLayout(new GridLayout(3,3));
lblTitle = new JLabel("Area of Triangle");
lblTitle.setFont(new Font("Arial", 1, 20));
lblTitle.setHorizontalAlignment(JLabel.CENTER);
lblOctal = new JLabel("Octal");
lblOctal.setHorizontalAlignment(JLabel.CENTER) ;
//lblDecimal = new JLabel("Decimal");
//
//lblDecimal.setHorizontalAlignment(JLabel.CENTER);
lblMessage = new JLabel("Result will be displayed here");
lblMessage.setForeground(Color.red);
lblMessage.setHorizontalAlignment(JLabel.CENTER);
txtOctal = new JTextField("0", 5);
txtOctal.setHorizontalAlignment(JLabel.CENTER);
//txtDecimal = new JTextField("0", 5);
//
//txtDecimal.setHorizontalAlignment(JLabel.CENTER);
calculate_btn = new JButton("Calculate Area");
//AHandlerClass aListener = new AHandlerClass() ;
//btnOtoD.addActionListener(aListener);
//btnDtoO.addActionListener(aListener);
panCentre.add(lblOctal);
//panCentre.add(lblDecimal);
panCentre.add(txtOctal);
//panCentre.add(txtDecimal);
panCentre.add(calculate_btn);
//panCentre.add(btnDtoO);
panel.add(lblTitle, BorderLayout.NORTH);
panel.add(lblMessage,BorderLayout.SOUTH);
panel.add(panCentre, BorderLayout.CENTER);
}
public static void main(String args[]) {
summinup_copy myGui = new summinup_copy();
myGui.setTitle("Bharath");
myGui.setSize(400, 200);
myGui.setVisible(true);
}
}
As you have already figured out, you have to use LayoutManagers when coding a Swing GUI by hand. Here are some links that can help you figure out which LayoutManager is appropriate for a given look:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
In order to place a JLabel next to a JTextField or other component, I usually use GridLayout or GridBagLayout. I find that it takes a lot of trial and error trying to get components to look the way I want. Often you have to have layers of embedded JPanels to get it just right.