JFrame objects only show when mousedover - java

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

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

JButtons for my hangman game are not appearing even after setting button visibility to true

Hi I am creating a hangman game with GUI in Java and I had a problem when I added the JButtons for the letters to the GUI because they were not appearing. Not sure why. The code where I start adding the buttons is in the is in the GamePanel class and the Game, GameWord, GameMain and GameFrame classes and parts of the GamePanel class are not shown because they are not needed to understand and answer the question.
GamePanel class:
//some imports were omitted because they are irrelevant to the post
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JButton;
public class GamePanel extends JPanel implements ActionListener
{
//some declarations were omitted because they are irrelevant to the post
private JButton a;
private JButton b;
private JButton c;
private JButton d;
private JButton e;
private JButton f;
private JButton g;
private JButton h;
private JButton i;
private JButton j;
private JButton k;
private JButton l;
private JButton m;
private JButton n;
private JButton o;
private JButton p;
private JButton q;
private JButton r;
private JButton s;
private JButton t;
private JButton u;
private JButton v;
private JButton w;
private JButton x;
private JButton y;
private JButton z;
public GamePanel(Game aGame)
{
// certain initialization's were omitted because they are irrelevant
this.addLetters();
}
public void paint(Graphics g)
{
//paint code goes here some parts were omitted as they are irrelevant to the post
repaint();
}
public void addLetters()
{
a = new JButton("A");
b = new JButton("B");
c = new JButton("C");
d = new JButton("D");
e = new JButton("E");
f = new JButton("F");
g = new JButton("G");
h = new JButton("H");
i = new JButton("I");
j = new JButton("J");
k = new JButton("K");
l = new JButton("L");
m = new JButton("M");
n = new JButton("N");
o = new JButton("O");
p = new JButton("P");
q = new JButton("Q");
r = new JButton("R");
s = new JButton("S");
t = new JButton("T");
u = new JButton("U");
v = new JButton("V");
w = new JButton("W");
x = new JButton("X");
y = new JButton("Y");
z = new JButton("Z");
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
f.addActionListener(this);
g.addActionListener(this);
h.addActionListener(this);
i.addActionListener(this);
j.addActionListener(this);
k.addActionListener(this);
l.addActionListener(this);
m.addActionListener(this);
n.addActionListener(this);
o.addActionListener(this);
p.addActionListener(this);
q.addActionListener(this);
r.addActionListener(this);
s.addActionListener(this);
t.addActionListener(this);
u.addActionListener(this);
v.addActionListener(this);
w.addActionListener(this);
x.addActionListener(this);
y.addActionListener(this);
z.addActionListener(this);
a.setBounds(340, 250, 5, 5);
b.setBounds(350, 250, 5, 5);
c.setBounds(360, 250, 5, 5);
d.setBounds(370, 250, 5, 5);
e.setBounds(380, 250, 5, 5);
f.setBounds(390, 250, 5, 5);
g.setBounds(400, 250, 5, 5);
h.setBounds(410, 250, 5, 5);
i.setBounds(420, 250, 5, 5);
j.setBounds(430, 250, 5, 5);
k.setBounds(440, 250, 5, 5);
l.setBounds(450, 250, 5, 5);
m.setBounds(460, 250, 5, 5);
n.setBounds(340, 350, 5, 5);
o.setBounds(350, 350, 5, 5);
p.setBounds(360, 350, 5, 5);
q.setBounds(370, 350, 5, 5);
r.setBounds(380, 350, 5, 5);
s.setBounds(390, 350, 5, 5);
t.setBounds(400, 350, 5, 5);
u.setBounds(410, 350, 5, 5);
v.setBounds(420, 350, 5, 5);
w.setBounds(430, 350, 5, 5);
x.setBounds(440, 350, 5, 5);
y.setBounds(450, 350, 5, 5);
z.setBounds(460, 350, 5, 5);
a.setVisible(true);
b.setVisible(true);
c.setVisible(true);
d.setVisible(true);
e.setVisible(true);
f.setVisible(true);
g.setVisible(true);
h.setVisible(true);
i.setVisible(true);
j.setVisible(true);
k.setVisible(true);
l.setVisible(true);
m.setVisible(true);
n.setVisible(true);
o.setVisible(true);
p.setVisible(true);
q.setVisible(true);
r.setVisible(true);
s.setVisible(true);
t.setVisible(true);
u.setVisible(true);
v.setVisible(true);
w.setVisible(true);
x.setVisible(true);
y.setVisible(true);
z.setVisible(true);
this.add(a);
this.add(b);
this.add(c);
this.add(d);
this.add(e);
this.add(f);
this.add(g);
this.add(h);
this.add(i);
this.add(j);
this.add(k);
this.add(l);
this.add(m);
this.add(n);
this.add(o);
this.add(p);
this.add(q);
this.add(r);
this.add(s);
this.add(t);
this.add(u);
this.add(v);
this.add(w);
this.add(x);
this.add(y);
this.add(z);
}
public void actionPerformed(ActionEvent e)
{
//actionPerformed code omitted because it is irrelevant
}
}
(Not actually an answer; just to show you how much easier it is to implement the existing logic with a loop)
int x = 340;
for (char c = 'A'; c <= 'Z'; ++c, x += 10) {
JButton button = new JButton(Character.toString(c));
final char lower = Character.toLowercase(c);
button.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
game.checkGuess(lower);
}
});
button.setBounds(x, 250, 5, 5);
button.setVisible(true);
this.add(button);
}
Note that I have defined an anonymous per-button ActionListener, so there is no need to keep the references to the buttons in an array.
I figured it out you must call super.paint(g); it order to make the buttons appear and than in void addLetters() you must call this.setLayout(null); which will allow you to set the size and location of the button. I also added the buttons via a loop to get rid of unnecessary repetition. my paint() and addLetters() methods are below
paint() method
/**
* paint the graphics to the screen
*/
public void paint(Graphics g)
{
//paint code goes here some parts were omitted as they are irrelevant to the post
super.paint(g);
repaint();
}
addLetters() method
/**
* add the letter buttons to the screen
*/
public void addLetters()
{
int x = (this.getWidth()/2)-60;
int y = 300;
int btnSize =20;
int btnsAdded = 0;
for (Character c : game.getAlphabet())
{
this.setLayout(null);
JButton letter = new JButton(Character.toString(c).toUpperCase());
letter.setLayout(null);
letter.setSize(btnSize, btnSize);
letter.setLocation(x,y);
letter.setFont(new Font("Calibri",Font.PLAIN,10));
letter.setMargin(new Insets(0,0,0,0));
letter.setVisible(true);
this.add(letter);
char guess = Character.toLowerCase(c);
letter.addActionListener(new ActionListener()
{
#Override public void actionPerformed(ActionEvent e)
{
//actionPerformed code omitted because it is irrelevant
}
});
x += 25;
btnsAdded++;
if(btnsAdded == 13)
{
x=(this.getWidth()/2)-60;
y+=50;
}
}
}
I second what Andy Turner mentioned in comment: your code has much unnecessary repetition because you are not using arrays and/or collections such as ArrayLists, but as he noted, that's not the cause of your trouble.
One problem is that you're using setBounds(...) on components but forgetting that layout managers usually ignore bounds, location and size properties. Remember that JPanels use FlowLayout by default and so will place and size components based on this layout manager and the component's preferred size and will ignore your bounds. One solution is to use null layouts, but this leads to ugly GUI's that look terrible on all but one platform and are difficult to debug and maintain. No, learn to use and then use the layout managers. Remember that you can nest JPanels, each using its own layout and thereby achieve complex layouts with simple layout managers.
Also you're overriding JPanel's paint method but not calling the super's method, something that can cause serious side effects. Instead override paintComponent, not paint, and call the super's method in your override.
Note on testing your code, calling super.paint(g); as the first line of the paint method showed the buttons, though in the wrong place.
Note that rather than painting directly on the JPanel, one option instead is to create BufferedImages with your hangman on it, create ImageIcons of the images, and then draw them in a JLabel by calling setIcon(...) on the JLabel.
For example you could hold the buttons in a GridLayout-using JPanel:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Hangman2 extends JPanel {
private static final int GAP = 5;
// best to create ImageIcons where you draw your Hangman in, and
// then display it in a JLabel by calling setIcon(...) on the label.
private JLabel imageLabel = new JLabel();
private List<Icon> iconList = createIcons();
public Hangman2() {
JLabel titleLabel = new JLabel("Welcome to Hangman", SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 40f));
JPanel buttonPanel = createButtonPanel();
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(titleLabel, BorderLayout.PAGE_START);
add(buttonPanel, BorderLayout.PAGE_END);
// placeholder component just to show something in the center of the GUI
add(Box.createRigidArea(new Dimension(200, 200)), BorderLayout.CENTER);
}
private List<Icon> createIcons() {
List<Icon> iconList = new ArrayList<>();
// TODO: create hangman drawing icons and place into array
return iconList;
}
private JPanel createButtonPanel() {
int rows = 2;
int cols = 16;
JPanel buttonPanel = new JPanel(new GridLayout(rows, cols, GAP, GAP));
// number of empty JLabels in the beginning and end of the bottom row
int labelCount = (2 * 16 - ('Z' - 'A' + 1)) / 2;
for (char c = 'A'; c <= 'Z'; c++) {
if (c - 'A' == cols) { // at 2nd row, add empty JLabels
for (int i = 0; i < labelCount; i++) {
buttonPanel.add(new JLabel());
}
}
JButton button = new JButton("" + c);
buttonPanel.add(button);
}
for (int i = 0; i < labelCount; i++) {
buttonPanel.add(new JLabel());
}
return buttonPanel;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Hangman2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Java PaintComponent: HowTo

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.

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