Java PaintComponent: HowTo - java

So, I want to paint something on a Panel, using PaintComponent. But I want to do it in a Constructor. So, for example:
public class Interfata extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.drawOval(500, 500, 50, 40);
}
public Interfata()
{
// code here
}
public static void main(String[] args)
{
Interfata i = new Interfata();
}
The code should be like this model. The problem is that I don't know how to call the paintComponent method on a panel that create in the Constructor. ( Even though it may seem inefficient, I create the frame, panel and all the functions in the constructor, so, that I just have to instantiate that object in the main method). If I weren't clear enough, please do ask for any detail you may find suitable.
Edit: So to be more specific, this is how my Constructor looks like:
public Interfata()
{
// main interface
JFrame frame = new JFrame("Queue");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 450);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((d.getWidth() - frame.getWidth()) / 2);
int y = (int) ((d.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
//simulation interface
JFrame f = new JFrame("Simulare");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setSize(900, 800);
int x1 = (int) ((d.getWidth() - frame.getWidth()) / 2);
int y1 = (int) ((d.getHeight() - frame.getHeight()) / 2);
f.setLocation(x1, y1);
JPanel panel = new JPanel();
panel.setLayout(null);
JPanel panel1 = new JPanel();
panel1.setLayout(null);
JLabel l1 = new JLabel("Intervalul minim de asteptare: ");
JTextArea tf1 = new JTextArea();
panel.add(l1);
l1.setBounds(5,10,200,25);
panel.add(tf1);
tf1.setBounds(200,10,300,20);
JLabel l2 = new JLabel("Intervalul maxim de asteptare: ");
JTextArea tf2 = new JTextArea();
panel.add(l2);
l2.setBounds(5,50,200,25);
panel.add(tf2);
tf2.setBounds(200,50,300,20);
JLabel l3 = new JLabel("Duarata minima pentru serviciu: ");
JTextArea tf3 = new JTextArea();
panel.add(l3);
l3.setBounds(5,90,200,25);
panel.add(tf3);
tf3.setBounds(200,90,300,20);
JLabel l4 = new JLabel("Durata maxima pentru serviciu: ");
JTextArea tf4 = new JTextArea();
panel.add(l4);
l4.setBounds(5,130,200,25);
panel.add(tf4);
tf4.setBounds(200,130,300,20);
JLabel l5 = new JLabel("Numarul de cozi: ");
JTextArea tf5 = new JTextArea();
panel.add(l5);
l5.setBounds(5,170,100,25);
panel.add(tf5);
tf5.setBounds(200,170,300,20);
JLabel l6 = new JLabel("Intervalul de simulare: ");
JTextArea tf6 = new JTextArea();
panel.add(l6);
l6.setBounds(5,210,150,25);
panel.add(tf6);
tf6.setBounds(200,210,300,20);
JButton b1 = new JButton("Simulare");
panel.add(b1);
b1.setBounds(700,100,100,35);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f.setVisible(true);
}
});
frame.setContentPane(panel);
frame.setVisible(true);
f.setContentPane(panel1);
}
What I want to do exactly, is paint something in the panel of the NEW FRAME, or more specificaly, in the frame f.

Related

Can't change the output of paintComponent after assigned new variable (setter) and called repaint()

I was stucked in the same place for almost 1 day still I can't find where's the error on my code. Need your guys to help, this is my code. (Quite a bit lengthy)
My JFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CircleProject extends JFrame implements ActionListener{
JTextField xTextField1;
JTextField yTextField1;
JTextField textFieldRadiusLeft;
JTextField xTextField2;
JTextField yTextField2;
JTextField textFieldRadiusRight;
JButton redraw;
public static void main(String[] args) {
CircleProject frame = new CircleProject();
frame.setResizable(true);
frame.setVisible(true);
frame.setSize(580, 700);
frame.setTitle("YONG JING PING FINAL PROJECT");
}
public CircleProject() {
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel theTitle = new JLabel("Two Circles Intersect?");
JLabel intersection = new JLabel("");
titlePanel.add(theTitle);
titlePanel.add(intersection);
JPanel contentPanel = new JPanel(new GridLayout(2, 1));
JPanel userInputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JPanel gridPanel = new JPanel(new GridLayout(1, 2, 8, 0));
JPanel leftInputPanel = new JPanel(new GridLayout(4, 1));
JLabel inputTitle1 = new JLabel("Enter circle 1 info: ");
inputTitle1.setHorizontalAlignment(JLabel.CENTER);
JPanel xInputPanelLeft = new JPanel();
xTextField1 = new JTextField(5);
xInputPanelLeft.add(new JLabel("Center X: "));
xInputPanelLeft.add(xTextField1);
JPanel yInputPanelLeft = new JPanel();
yTextField1 = new JTextField(5);
yInputPanelLeft.add(new JLabel("Center Y: "));
yInputPanelLeft.add(yTextField1);
JPanel radiusLeft = new JPanel();
textFieldRadiusLeft = new JTextField(5);
radiusLeft.add(new JLabel("Radius: "));
radiusLeft.add(textFieldRadiusLeft);
leftInputPanel.add(inputTitle1);
leftInputPanel.add(xInputPanelLeft);
leftInputPanel.add(yInputPanelLeft);
leftInputPanel.add(radiusLeft);
leftInputPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JPanel rightInputPanel = new JPanel(new GridLayout(4, 1));
JLabel inputTitle2 = new JLabel("Enter circle 2 info: ");
inputTitle2.setHorizontalAlignment(JLabel.CENTER);
JPanel xInputPanelRight = new JPanel();
xTextField2 = new JTextField(5);
xInputPanelRight.add(new JLabel("Center X: "));
xInputPanelRight.add(xTextField2);
JPanel yInputPanelRight = new JPanel();
yTextField2 = new JTextField(5);
yInputPanelRight.add(new JLabel("Center Y: "));
yInputPanelRight.add(yTextField2);
JPanel radiusRight = new JPanel();
textFieldRadiusRight = new JTextField(5);
radiusRight.add(new JLabel("Radius: "));
radiusRight.add(textFieldRadiusRight);
rightInputPanel.add(inputTitle2);
rightInputPanel.add(xInputPanelRight);
rightInputPanel.add(yInputPanelRight);
rightInputPanel.add(radiusRight);
rightInputPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
gridPanel.add(leftInputPanel);
gridPanel.add(rightInputPanel);
userInputPanel.add(gridPanel);
contentPanel.add(new DrawPanel());
contentPanel.add(userInputPanel);
redraw = new JButton("Redraw Circles");
redraw.setEnabled(true);
redraw.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(redraw);
setLayout(new BorderLayout());
add(titlePanel, BorderLayout.NORTH);
add(contentPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
DrawPanel drawCircle = new DrawPanel();
#Override
public void actionPerformed(ActionEvent e) {
this.setVisible(false);
if (e.getSource() == redraw) {
CircleProject frame2 = new CircleProject();
frame2.setResizable(false);
frame2.setVisible(true);
frame2.setSize(580,700);
frame2.setTitle("YONG JING PING FINAL PROJECT");
String text = xTextField1.getText();
int x1 = Integer.parseInt(text);
String text1 = xTextField2.getText();
int x2 = Integer.parseInt(text1);
String text2 = yTextField1.getText();
int y1 = Integer.parseInt(text2);
String text3 = yTextField2.getText();
int y2 = Integer.parseInt(text3);
String text4 = textFieldRadiusLeft.getText();
int r1 = Integer.parseInt(text4);
String text5 = textFieldRadiusRight.getText();
int r2 = Integer.parseInt(text5);
drawCircle.setCenterColumn1(x1, y1, r1);
drawCircle.setCenterColumn2(x2, y2, r2);
}
}
}
My Drawpanel Class:
import javax.swing.*;
import java.awt.*;
public class DrawPanel extends JPanel{
// the coordinate's variables is the start point of it.
int coordinateX1=50, coordinateX2=300, coordinateY1=50, coordinateY2=50, radius1=0, radius2=0, length1=200, length2=200;
public void setCenterColumn1(int x, int y, int radius1){
this.coordinateX1 = x-radius1;
this.coordinateY1 = y-radius1;
this.radius1 = radius1;
length1 = radius1*2;
System.out.println(coordinateX1);
System.out.println(coordinateY1);
System.out.println(length1);
System.out.println(coordinateX2);
System.out.println(coordinateY2);
System.out.println(length2);
System.out.println("-------1-------");
repaint();
}
public void setCenterColumn2(int x, int y, int radius2){
this.coordinateX2=x-radius2;
this.coordinateY2=y-radius2;
this.radius2=radius2;
length2 = radius2*2;
System.out.println(coordinateX1);
System.out.println(coordinateY1);
System.out.println(length1);
System.out.println(coordinateX2);
System.out.println(coordinateY2);
System.out.println(length2);
System.out.println("-------2-------");
repaint();
}
public DrawPanel(){
setBackground(Color.WHITE);
}
// error from here, when redraw pressed this paintComponent does not
// show up the new circle.
#Override
public void paintComponent (Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
// Circle for column 1
g.drawOval(coordinateX1,coordinateY1,length1,length1);
// Circle for column 2
g.drawOval(coordinateX2,coordinateY2,length2,length2);
System.out.println(coordinateX1);
System.out.println(coordinateY1);
System.out.println(length1);
System.out.println(coordinateX2);
System.out.println(coordinateY2);
System.out.println(length2);
System.out.println("-------3-------");
}
}
My expected result is the circle will be changed after the user input the centre coordinate of the circle and clicked redraw btn.
The problem is that you are not using never your variable drawCircle (line:
DrawPanel drawCircle = new DrawPanel();)
And when you use inside actionPerformed method, you never use that variable because it's created another instance of Circle Project. (line: CircleProject frame2 = new CircleProject();)
The drawCircle variable is from the current class you are running,so, when you instance again CircleProject, the changes inside that variabe will not have effect.
To fix that, it's not necessary to instance again, you only must use that variable.
The first thing you will have to do inside the Constructor CircleProject():
....
userInputPanel.add(gridPanel);
contentPanel.add(drawCircle);
contentPanel.add(userInputPanel);
....
The change here was only one, because you have contentPanel.add(new DrawPanel()); and that's not correct (as I said, you never are using the variable drawCircle), so, instead, you have to change it for contentPanel.add(drawCircle);
On the other hand, to avoid instancing the CircleProject you will have to remove some lines in the actionPerformed method, like:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == redraw) {
String text = xTextField1.getText();
int x1 = Integer.parseInt(text);
String text1 = xTextField2.getText();
int x2 = Integer.parseInt(text1);
String text2 = yTextField1.getText();
int y1 = Integer.parseInt(text2);
String text3 = yTextField2.getText();
int y2 = Integer.parseInt(text3);
String text4 = textFieldRadiusLeft.getText();
int r1 = Integer.parseInt(text4);
String text5 = textFieldRadiusRight.getText();
int r2 = Integer.parseInt(text5);
drawCircle.setCenterColumn1(x1, y1, r1);
drawCircle.setCenterColumn2(x2, y2, r2);
}
}
I tried the program and it worked for me! I hope this also works for you :D

JFrame objects only show when mousedover

I'm trying to build my own calculator from scratch.
When i run my program as it is now, some of the buttons don't show up, until i hover over them with my cursor, and my bounds are all f'ed up. However when i move window.setVisible(true); to the beginning of my constructer, every bound of all the objects are placed correctly, but all my objects only show once moused-over.
package guitest;
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import static javax.swing.JFrame.*;
public class Frame implements ActionListener{
public static int Calculator(int n1, int n2){
return n1 + n2;
}
JTextField num1,num2,ans;
JButton calculate, add, sub, pro, div;
JPanel textFields, actions;
Frame(){
//Window is being created.
JFrame window = new JFrame("Calculator");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(false);
window.setSize(400, 400);
//Creating panel
textFields = new JPanel();
actions = new JPanel();
//Adjusting JPanel
textFields.setBounds(0, 0, 240, 400);
actions.setBounds(240, 0, 160, 400);
//Creating textfields.
num1 = new JTextField("Number 1");
num2 = new JTextField("Number 2");
ans = new JTextField("Answer");
ans.setEditable(false);
//Creating calculate button.
calculate = new JButton("Calclulate");
add = new JButton("+");
sub = new JButton("-");
pro = new JButton("*");
div = new JButton("/");
//adjusting TextFields to my window
num1.setBounds(30, 20, 200, 20);
num2.setBounds(30, 60, 200, 20);
ans.setBounds(30,100,200,20);
//adjusting Buttons to my window
calculate.setBounds(30, 140, 90, 30);
add.setBounds(20, 20, 50, 50);
sub.setBounds(75, 20, 50, 50);
pro.setBounds(20, 75, 50, 50);
div.setBounds(75, 75, 50, 50);
calculate.addActionListener(this);
//adding to my window
textFields.add(num1);textFields.add(num2);textFields.add(ans);textFields.add(calculate);
actions.add(add);actions.add(sub);actions.add(pro);actions.add(div);
window.add(textFields);window.add(actions);
window.setVisible(true);
//Setting everything visible
//textFields.setVisible(true);actions.setVisible(true);
//num1.setVisible(true);num2.setVisible(true);ans.setVisible(true);
//calculate.setVisible(true);add.setVisible(true);sub.setVisible(true);pro.setVisible(true);div.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String n1 = num1.getText();
String n2 = num2.getText();
int a = Integer.parseInt(n1);
int b = Integer.parseInt(n2);
int c;
c = Calculator(a,b);
String result = String.valueOf(c);
ans.setText(result);
}
public static void main(String[] args) {
new Frame();
}
}
when window.setVisible(true); is in the bottom.
when window.setVisible(true); is at the top.
How it is supposed to look. (i've hovered over all my objects manually.)
I changed your code and use layouts instead of setBouds().
Swing provide different LayoutManagers and these are used to arrange components in a particular manner. following classes are used to represents the layout managers in Swing:
1) java.awt.BorderLayout
2) java.awt.FlowLayout
3) java.awt.GridLayout
4) java.awt.CardLayout
5) java.awt.GridBagLayout
6) javax.swing.BoxLayout
7) javax.swing.GroupLayout
8) javax.swing.ScrollPaneLayout
9) javax.swing.SpringLayout etc.
each of them will arrange your components in specific order, which you can read more about it in here (more details...)
public class Frame implements ActionListener {
public static int Calculator(int n1, int n2) {
return n1 + n2;
}
JTextField num1, num2, ans;
JButton calculate, add, sub, pro, div;
JPanel textFields, actions;
Frame() {
// Window is being created.
JFrame window = new JFrame("Calculator");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(false);
window.setSize(400, 400);
window.setLayout(new BorderLayout());
// Creating panel
// Creating textfields.
num1 = new JTextField("Number 1");
num2 = new JTextField("Number 2");
ans = new JTextField("Answer");
ans.setEditable(false);
// Creating calculate button.
calculate = new JButton("Calclulate");
add = new JButton("+");
sub = new JButton("-");
pro = new JButton("*");
div = new JButton("/");
calculate.addActionListener(this);
textFields = new JPanel();
actions = new JPanel();
GridLayout txtBox = new GridLayout(4, 1);
txtBox.setVgap(20);
textFields.setLayout(txtBox);
GridLayout actionBox = new GridLayout(2, 2);
actions.setLayout(actionBox);
actions.setPreferredSize(new Dimension(100, 100));
// adding to my window
textFields.add(num1);
textFields.add(num2);
textFields.add(ans);
textFields.add(calculate);
actions.add(add);
actions.add(sub);
actions.add(pro);
actions.add(div);
window.setLayout(new FlowLayout());
window.add(textFields);
window.add(actions);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String n1 = num1.getText();
String n2 = num2.getText();
int a = Integer.parseInt(n1);
int b = Integer.parseInt(n2);
int c;
c = Calculator(a, b);
String result = String.valueOf(c);
ans.setText(result);
}
public static void main(String[] args) {
new Frame();
}
}

How to Add a panel to a JFrame

so im kinda new to programming and I'm having a weird problem. So I'm trying to add my 'Info' panel with labels in them to my 'JFrame' but when I run the program the panel doesn't show up. Also how would I make it to where the panel would appear in the top Left of the JFrame.
private Lilac player;
private int[] xPos;
private JLabel lblShowLives, lblShowScore, lblTimer;
private int lives, score, seconds, minutes;
private ImageIcon[] imgBackground;
private Timer backgroundTimer, cutsceneTimer, Timer;
private AudioStream auStream;
private AudioPlayer auPlayer;
private InputStream in;
private DecimalFormat df, df2;
public FreedomPlanet() {
df = new DecimalFormat("00");
df2 = new DecimalFormat("0000");
auPlayer = AudioPlayer.player;
// creates the player
player = new Lilac();
//
lives = 3;
score = 0;
seconds = 0;
minutes = 0;
imgBackground = new ImageIcon[2];
// gets the image for the background inside of a for loop
for (int i = 0; i < imgBackground.length; i++)
{
imgBackground[i] = new ImageIcon("Stage\\Forest.gif");
}
xPos = new int[] {0, imgBackground[0].getIconWidth()};
// sets the amount of time for each timer
backgroundTimer = new Timer(50, this);
Timer = new Timer(1000, this);
// creates a label that displays "TIME"
JLabel lblTime = new JLabel("TIME");
lblTime.setFont(new Font("Britannic Bold", Font.BOLD, 18));
// label that displays the time
lblTimer = new JLabel();
lblTimer.setPreferredSize(new Dimension(100, 30));
lblTimer.setFont(new Font("Britannic Bold", Font.BOLD, 18));
lblTimer.setHorizontalAlignment(SwingConstants.CENTER);
lblTimer.setText(df.format(minutes) + ":" + df.format(seconds));
// creates a label that says "SCORE"
JLabel lblScore = new JLabel("SCORE");
lblTime.setFont(new Font("Britannic Bold", Font.BOLD, 18));
// label that displays the users score
lblShowScore = new JLabel();
lblShowScore.setPreferredSize(new Dimension(100, 30));
lblShowScore.setFont(new Font("Britannic Bold", Font.BOLD, 18));
lblShowScore.setHorizontalAlignment(SwingConstants.CENTER);
lblShowScore.setText(df.format(score));
// creates a panel called Info and and adds components to them
JPanel Info = new JPanel();
Info.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
Info.setPreferredSize(new Dimension(270, 180));
Info.add(lblTime);
Info.add(lblTimer);
Info.add(lblScore);
Info.add(lblShowScore);
addKeyListener(this);
setFocusable(true);
setLayout(null);
JFrame frame = new JFrame();
frame.add(Info);
frame.add(this, BorderLayout.CENTER);
frame.setContentPane(this);
frame.setTitle("Freedom Planet");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(this);
frame.setResizable(false);
frame.setSize(500, 500);
frame.setSize(imgBackground[0].getIconWidth(), imgBackground[0].getIconHeight());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// starts the background timer
backgroundTimer.start();
//Timer.start();
// sets the location of the player
player.setLocation(170, 395);
Timer.start();
}

How to get a text from JTextfield and displaying it on a JTextArea

I am trying to get a text input from a JTextField and displaying it on a JTextField when a button is clicked. Can anyone help please?
I know I am supposed to use getText and setText but not quite sure how I can implement this when the button is clicked. Please have a look at the code below.
Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class CyberPet extends JFrame
implements ActionListener {
private JButton makePetButton,hungryButton, randomButton;
private JPanel panel;
private JLabel label, petName, flyLabel;
private JTextArea responseArea;
private JTextField textField;
int x =10;
int y=10;
int xMax = 700;
int yMax = 500;
public static void main (String[] args) {
CyberPet frame = new CyberPet();
frame.setSize(700, 500);
frame.createGUI();
frame.show();
frame.getContentPane().setBackground(Color.blue);
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout() );
JPanel buttonGUI = new JPanel();
panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 300));
panel.setLocation(500, 300);
panel.setBackground(Color.white);
panel.setLayout(null);
window.add(panel);
buttonGUI = new JPanel();
buttonGUI.setPreferredSize(new Dimension(400, 100));
buttonGUI.setLocation(200, 100);
buttonGUI.setBackground(Color.white);
window.add(buttonGUI);
label = new JLabel();
label.setBackground(Color.white);
Image img = new ImageIcon (this.getClass().getResource("/frog.gif")).getImage();
label.setIcon(new ImageIcon(img));
label.setLocation(400, 0);
label.setSize(80, 80);
panel.add(label);
flyLabel = new JLabel();
flyLabel.setBackground(Color.black);
Image img1 = new ImageIcon (this.getClass().getResource("/fly.gif")).getImage();
flyLabel.setIcon(new ImageIcon(img1));
flyLabel.setLocation(10, 10);
flyLabel.setSize(50, 50);
panel.add(flyLabel);
petName = new JLabel("Enter Pet Name!");
buttonGUI.add(petName);
textField = new JTextField("");
textField.setPreferredSize(new Dimension(100, 30));
textField.setLocation(200, 60);
textField.addActionListener(this);
buttonGUI.add(textField);
makePetButton = new JButton("Make Pet");
makePetButton.setLocation(160, 60);
makePetButton.addActionListener(this);
buttonGUI.add(makePetButton);
hungryButton = new JButton("Hungry!");
hungryButton.setLocation(280, 60);
hungryButton.setSize(100, 30);
hungryButton.addActionListener(this);
buttonGUI.add(hungryButton);
responseArea = new JTextArea("Pet Status");
buttonGUI.add(responseArea);
}
// ***** nb line of 4 spaces after insert
public void actionPerformed(ActionEvent event) {
//Move down
if (event.getSource() == makePetButton)
{
}
//Move Up
if (event.getSource() == hungryButton)
{
if (y > 10){
y=y-20;
label.setLocation(x, y);
}
}
//Makes the Pet
if (event.getSource() == makePetButton)
{
if (x > 10){
x=x-20;
label.setLocation(x, y);
}
}
//Move Right
if (event.getSource() == textField)
{
if (x < 280){
x=x+20;
label.setLocation(x, y);
}
}
//Move random
if(event.getSource() == randomButton)
{
Random rnd = new Random();
int xMax = panel.getWidth()-label.getWidth();
int yMax = panel.getHeight()-label.getHeight();
x = rnd.nextInt(xMax+10);
y = rnd.nextInt(yMax+10);
label.setLocation(x,y);
}
}
}
You have the eventHandler, so just call responseArea.setText(textField.getText()) when handling the click on the appropriate button.

Java swing, can't get a textfield to show like it supposed to

I am trying to make the text field for quiz_7 set up, however, it is not showning up like the remaning six, i tried putting an parameter as 360, no text field. Changed it 340, but i only see half a textfield.
import java.awt.Container;
import javax.swing.*;
public class QuizEntry {
JPanel textPanel,panelForTextFields;
JLabel Entry_for_Quizes, quiz1, quiz2, quiz3, quiz4, quiz5, quiz6;
JTextField quiz_1, quiz_2, quiz_3, quiz_4, quiz_5, quiz_6;
JTextField quiz_7;
private JLabel quiz7;
public JPanel createContentPane() {
// We create a bottom JPanel to place everything on.
JPanel totalGUI1 = new JPanel();
totalGUI1.setLayout(null);
Entry_for_Quizes = new JLabel("Quiz Entry ");
Entry_for_Quizes.setLocation(0, 0);
Entry_for_Quizes.setSize(400, 400);
Entry_for_Quizes.setHorizontalAlignment(4);
totalGUI1.add(Entry_for_Quizes);
// Creation of a Panel to contain the JLabels
textPanel = new JPanel();
textPanel.setLayout(null);
textPanel.setLocation(10, 35);
textPanel.setSize(100, 600);
totalGUI1.add(textPanel);
// Username Label
quiz1 = new JLabel("Quiz 1");
quiz1.setLocation(-20, 0);
quiz1.setSize(70, 40);
quiz1.setHorizontalAlignment(4);
textPanel.add(quiz1);
// Login Label
quiz2 = new JLabel("Quiz 2");
quiz2.setLocation(-20, 60);
quiz2.setSize(70, 40);
quiz2.setHorizontalAlignment(4);
textPanel.add(quiz2);
// Username Label
quiz3 = new JLabel("Quiz 3");
quiz3.setLocation(-20, 120);
quiz3.setSize(70, 40);
quiz3.setHorizontalAlignment(4);
textPanel.add(quiz3);
// Login Label
quiz4 = new JLabel("Quiz 4");
quiz4.setLocation(-20, 180);
quiz4.setSize(70, 40);
quiz4.setHorizontalAlignment(4);
textPanel.add(quiz4);
// Username Label
quiz5 = new JLabel("Quiz 5");
quiz5.setLocation(-20, 240);
quiz5.setSize(70, 40);
quiz5.setHorizontalAlignment(4);
textPanel.add(quiz5);
// L
quiz6 = new JLabel("Quiz 6");
quiz6.setLocation(-20, 300);
quiz6.setSize(70, 40);
quiz6.setHorizontalAlignment(4);
textPanel.add(quiz6);
quiz7 = new JLabel("Quiz 7");
quiz7.setLocation(-20, 350);
quiz7.setSize(70, 40);
quiz7.setHorizontalAlignment(4);
textPanel.add(quiz7);
//////////////////////////////////////////////////////////////
panelForTextFields = new JPanel();
panelForTextFields.setLayout(null);
panelForTextFields.setLocation(110, 40);
panelForTextFields.setSize(100, 350);
totalGUI1.add(panelForTextFields);
// quiz Textfield
quiz_1 = new JTextField(8);
quiz_1.setLocation(0, 0);
quiz_1.setSize(100, 30);
panelForTextFields.add(quiz_1);
quiz_2 = new JTextField(8);
quiz_2.setLocation(0, 60);
quiz_2.setSize(100, 30);
panelForTextFields.add(quiz_2);
quiz_3 = new JTextField(8);
quiz_3.setLocation(0, 120);
quiz_3.setSize(100, 30);
panelForTextFields.add(quiz_3);
quiz_4 = new JTextField(8);
quiz_4.setLocation(0, 180);
quiz_4.setSize(100, 30);
panelForTextFields.add(quiz_4);
quiz_5 = new JTextField(8);
quiz_5.setLocation(0, 240);
quiz_5.setSize(100, 30);
panelForTextFields.add(quiz_5);
quiz_6 = new JTextField(8);
quiz_6.setLocation(0, 300);
quiz_6.setSize(100, 30);
panelForTextFields.add(quiz_6);
quiz_7 = new JTextField(8);
quiz_7.setLocation(0, 340);
quiz_7.setSize(100, 30);
panelForTextFields.add(quiz_7);
return totalGUI1;
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Quiz Entry");
QuizEntry demo = new QuizEntry();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 700);
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Basically change size: for panelForTextFields. From 350 to 500 for example.
To make code a bit generic I would write something like:
panelForTextFields.setSize(100, 6*80);
where 6 is count of JTextFields.
If we will go further, I would create list of JTextField like:
List<JTextField> list = new ArrayList<JTextField>();
list.add(quiz_1);
list.add(quiz_2);
list.add(quiz_3);
list.add(quiz_4);
list.add(quiz_5);
list.add(quiz_6);
and after would write:
final int GAP = 40;
panelForTextFields.setSize(100, 6*( quiz_1.getHeight() + GAP));
Since you used the same logic to configure JTextfields you can use now list like:
quiz_1 = new JTextField(8);
panelForTextFields.add(quiz_1);
quiz_2 = new JTextField(8);
panelForTextFields.add(quiz_2);
quiz_3 = new JTextField(8);
panelForTextFields.add(quiz_3);
quiz_4 = new JTextField(8);
panelForTextFields.add(quiz_4);
quiz_5 = new JTextField(8);
panelForTextFields.add(quiz_5);
quiz_6 = new JTextField(8);
panelForTextFields.add(quiz_6);
quiz_7 = new JTextField(8);
panelForTextFields.add(quiz_7);
list.add(quiz_1);
list.add(quiz_2);
list.add(quiz_3);
list.add(quiz_4);
list.add(quiz_5);
list.add(quiz_6);
list.add(quiz_7);
for(int k = 0; k<list.size(); k++){
JTextField f = list.get(k);
f.setLocation(0, k*60);
f.setSize(100, 30);
}
final int GAP = 40;
panelForTextFields.setSize(100, 6*( quiz_1.getHeight() + GAP));

Categories

Resources