Getting text input without swing in Java - java

Hi I'm making a game in Java that randomly generates 100 numbers, and then
ask the user to memorize as many as then can and then try to recall as many as they can. My game uses a JPanel and a Graphics g object to do all the drawing. How do I "draw" a JTextfield or get one to work on a jpanel?

Add a ActionListener to JTextField and then add that JTextField to JPanel. Now add this JPanel to JFrame using this.add(jpnel, BorderLayout.SOUTH);
Create a new JPanel class Board where you draw things. Add that JPanel to JFrame as, this.add(new Board(), BorderLayout.CENTER);.
Here I coded one example for you. Now you should have an idea how to do that...
Board class
public class Board extends JPanel {
int[] numbers = {3, 25, 5, 6, 60, 100};
int index = 0;
static String num;
boolean once = true;
FontMetrics fm;
Board() {
setPreferredSize(new Dimension(400, 200));
setBackground(Color.decode("#ffde00"));
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
if (index < 6) {
num = numbers[index] + "";
} else {
num = "Game Ended.";
Window.ans.setEditable(false);
}
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Arial", Font.PLAIN, 50));
if(once){
fm = g2.getFontMetrics();
once = false;
}
int x = ((getWidth() - fm.stringWidth(num)) / 2);
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g2.drawString(num + "", x, y);
index++;
}
}
Window class
public class Window extends JFrame {
JPanel p = new JPanel();
JLabel lbl = new JLabel("Enter the number if you have seen it before, Else empty.");
JLabel res = new JLabel("....");
static JTextField ans = new JTextField(10);
Board board = new Board();
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(board, BorderLayout.CENTER);
p.setLayout(new BorderLayout(8, 8));
p.add(lbl, BorderLayout.WEST);
ans.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (ans.getText().equals(Board.num)) {
res.setText("Good");
} else {
res.setText("Bad");
}
ans.setText("");
board.repaint();
}
});
p.add(ans, BorderLayout.CENTER);
p.add(res, BorderLayout.EAST);
p.setBorder(new EmptyBorder(10, 10, 10, 10));
this.add(p, BorderLayout.SOUTH);
setResizable(false);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
}

Related

creating a paint Graphics g in my Square class is breaking my GUI

I'm trying to board game simulator. My squares are JButtons and they looked alright until the point where I added a Oval, using the fillOval function, to indicate where the player is on the board.
My board is build by square buttons, here the Square class:
public class Square extends JButton{
private boolean occupied;
private Player occupant;
private int position, num;
private Board board;
public Square (int position) {
this.setPreferredSize(new Dimension(85, 85));
this.setText(Integer.toString(position + 1));
this.setFont(new Font("Tempus Sans ITC", Font.BOLD, 20));
this.position = position;
occupied = false;
occupant = null;
}
public int getPosition() {
return position;
}
public boolean isOccupied() {
return this.occupied;
}
public Player getOccupant() {
if(this.isOccupied())
return this.occupant;
return null;
}
public void enter ( Player p) {
this . enter (p);
}
public void leave ( Player p) {
this . leave (p);
}
public void setOccupant(Player visitor) {
this.occupant = visitor;
this.occupied = true;
}
public void paint(Graphics g) {
if(this.isOccupied()) {
g.setColor(occupant.getColor());
g.fillOval(30,30,50,50);
}
}
And GUI class
* Create the application.
*/
public Game() {
initialize();
startGame();
players.add(human);
players.add(computer);
//restart();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
//Main window
frame = new JFrame();
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\X270\\eclipse-workspace\\Snakes and Ladders\\src\\org\\snakesandladders\\logo.png"));
frame.setBounds(100, 100, 600, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.setResizable(false);
//call panels
createGamePanel();
createControlPanel();
}
/**
* Creating Board Panel
*/
private void createGamePanel() {
gamePanel = new JPanel();
board = new Board();
addBoardToPanel(board, gamePanel);
frame.getContentPane().add(gamePanel, BorderLayout.CENTER);
}
public void addBoardToPanel(Board b, JPanel p) {
int rows = 5;
int cols = 6;
JPanel ContainerPanel = new JPanel(new GridLayout(5, 6));
for (int r=rows; r>0; r--){
if(r % 2 == 0) {
int rowLeft = r * cols;
for (int n = rowLeft, l = (rowLeft - cols); n>l; n--){
Square sq = b.getSquare(n-1);
ContainerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, BORDER_WIDTH));
ContainerPanel.add(sq);
}
}
else{
int rowLeft = ((r - 1) * cols) +1;
for (int n = rowLeft, l = (rowLeft + cols); n<l; n++){
Square sq =b.getSquare(n-1);
ContainerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, BORDER_WIDTH));
ContainerPanel.add(sq);
}
}
p.add(ContainerPanel, BorderLayout.CENTER);
}
}
/**
* Creating the control panel
*/
private void createControlPanel() {
controlPanel = new JPanel();
infoPanel = new JPanel();
playerPanel = new JPanel();
buttonPanel = new JPanel();
controlPanel.setLayout(new BorderLayout(20, 20));
controlPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
humanLabel = new JLabel(/*humanPlayer.getName()*/ " (You)");
humanLabel.setPreferredSize(new Dimension(175, 40));
humanLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
humanLabel.setHorizontalAlignment(SwingConstants.CENTER);
humanLabel.setBorder(new LineBorder(Color.DARK_GRAY, 2));
humanLabel.setBackground(Color.RED);
humanLabel.setOpaque(true);
humanLabel.setForeground(Color.WHITE);
playerPanel.add(humanLabel, BorderLayout.WEST);
diceButton = new JButton("Roll Dice");
diceButton.setPreferredSize(new Dimension(150, 40));
diceButton.setFont(humanLabel.getFont());
/*diceButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
playTurn(humanPlayer);
}
});*/
playerPanel.add(diceButton, BorderLayout.CENTER);
computerLabel = new JLabel(/*humanPlayer.getName() + */" (Computer)");
computerLabel.setPreferredSize(humanLabel.getPreferredSize()); //new Dimension(labelWidth, labelHeight)
computerLabel.setFont(humanLabel.getFont());
computerLabel.setHorizontalAlignment(SwingConstants.CENTER);
computerLabel.setBorder(humanLabel.getBorder());
computerLabel.setBackground(Color.BLUE);
computerLabel.setOpaque(true);
computerLabel.setForeground(humanLabel.getForeground());
playerPanel.add(computerLabel, BorderLayout.EAST);
diceLabel = new JLabel("Dice Value: ?");
diceLabel.setPreferredSize(new Dimension(515, 40));
diceLabel.setFont(humanLabel.getFont());
diceLabel.setHorizontalAlignment(SwingConstants.CENTER);
diceLabel.setBorder(humanLabel.getBorder());
diceLabel.setBackground(Color.CYAN);
diceLabel.setOpaque(true);
infoPanel.add(diceLabel, BorderLayout.NORTH);
startButton = new JButton("Start New Game");
startButton.setFont(humanLabel.getFont());
startButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent r){
restart();
}
});
buttonPanel.add(startButton);
exitButton = new JButton("Exit");
exitButton.setFont(humanLabel.getFont());
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
exit();
}
});
buttonPanel.add(exitButton);
controlPanel.add(infoPanel, BorderLayout.NORTH);
controlPanel.add(buttonPanel, BorderLayout.SOUTH);
controlPanel.add(playerPanel, BorderLayout.CENTER);
frame.getContentPane().add(controlPanel, BorderLayout.SOUTH);
}
This is how it looks before adding the fillOval
This is how the GUI looks after adding the fillOval
How could I fix this?
Thank you in advance
You have to call super.paint():
public void paint(Graphics g) {
super.paint(g);
if(this.isOccupied()) {
g.setColor(occupant.getColor());
g.fillOval(30,30,50,50);
}
}

Paint a parabola using JTextField values in Java

The program consists of drawing a parabola using the values from the A, B and C jtextfields every time the button is pressed:
It also has to be on two separate classes, the View which displays the menu and the Controller which takes the inputs from the first class and paints the parabola.
My actual code:
public static void main(String[] args) {
JFrame frame = new JFrame("Parabola");
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(50, 50));
JLabel labelA = new JLabel();
labelA.setText("a");
JTextField textA = new JTextField("0",3);
JLabel labelB = new JLabel();
labelB.setText("b");
JTextField textB = new JTextField("0",3);
JLabel labelC = new JLabel();
labelC.setText("c");
JTextField textC = new JTextField("0",3);
JButton draw = new JButton();
draw.setText("Draw");
draw.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
textA.getText();
textB.getText();
textC.getText();
}
});
panel1.add(labelA);
panel1.add(textA);
panel1.add(labelB);
panel1.add(textB);
panel1.add(labelC);
panel1.add(textC);
panel1.add(draw);
JPanel panel2 = new JPanel(){
double a=2, b=1, c=0;
public void section (Graphics g){
g.setColor(Color.blue);
g.drawLine(200,0,200,400);
g.drawLine(0,200,400,200);
for (int x=0; x<=400; x= x +40){
g.drawLine(x,195,x,205);
}
for (int y=0; y<=400; y=y+40){
g.drawLine(195,y,205,y);
}
}
public void graphic(Graphics g) {
g.setColor(Color.red);
for (double x=-100;x<=100;x = x+0.1){
double y = a * x * x + b * x + c;
int X = (int)Math.round(200 + x*20);
int Y = (int)Math.round(200 - y*20);
g.fillOval(X-2,Y-2,4,4);
}
}
public void paint (Graphics g){
section(g);
graphic(g);
}
};
panel2.setBackground(Color.WHITE);
frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
frame.getContentPane().add(panel2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setSize(420,490);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
I`ve managed to do it in one class without the textfields working and have no idea how to separate the graphic into another class so it can do the operations and send them back to the view class again.
Solved it:
Class View
public class View extends JFrame {
public View() {
JFrame frame = new JFrame("Equation");
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(50, 50));
JLabel labelA = new JLabel();
labelA.setText("a");
JTextField textA = new JTextField("0",3);
JLabel labelB = new JLabel();
labelB.setText("b");
JTextField textB = new JTextField("0",3);
JLabel labelC = new JLabel();
labelC.setText("c");
JTextField textC = new JTextField("0",3);
JButton draw = new JButton();
draw.setText("Draw");
draw.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Controller.a = Double.parseDouble(textA.getText());
Controller.b = Double.parseDouble(textB.getText());
Controller.c = Double.parseDouble(textC.getText());
repaint();
frame.pack();
frame.setSize(420,490);
}
});
panel1.add(labelA);
panel1.add(textA);
panel1.add(labelB);
panel1.add(textB);
panel1.add(labelC);
panel1.add(textC);
panel1.add(draw);
JPanel panel2 = new JPanel(){
public void paint(Graphics g){
super.paint(g);
Controller.grid(g);
Controller.Graphic1(g);
}
};
panel2.setBackground(Color.WHITE);
frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
frame.getContentPane().add(panel2, BorderLayout.CENTER);
frame.setVisible(true);
frame.setSize(420,490);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
View frame = new View();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Class Controller
public class Controller {
static double a=2, b=1, c=0;
public static void grid (Graphics g){
g.setColor(Color.blue);
g.drawLine(200,0,200,400);
g.drawLine(0,200,400,200);
for (int x=0; x<=400; x= x +40){
g.drawLine(x,195,x,205);
}
for (int y=0; y<=400; y=y+40){
g.drawLine(195,y,205,y);
}
}
public static void Graphic1(Graphics g) {
g.setColor(Color.red);
for (double x=-100;x<=100;x = x+0.1){
double y = a * x * x + b * x + c;
int X = (int)Math.round(200 + x*20);
int Y = (int)Math.round(200 - y*20);
g.fillOval(X-2,Y-2,4,4);
}
}
}

Trying to understand how Timer object works - JAVA SWING

I declare a Timer object at the start of my code, initialize it when a JButton is clicked but i can't stop it no matter what i do.
In my code i'm trying to stop the timer when the button print is clicked but it doesn't work.
Here's my Window.java class :
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time=0;
double temperature=0.0;
Timer chrono;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
ip.addActionListener(lForButton);
centerPanel.add(start);
north.add(centerPanel, BorderLayout.CENTER);
south = new JPanel();
legend = new JLabel("Legends are here");
south.add(legend);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
container.add(south, BorderLayout.SOUTH);
this.setContentPane(container);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==start)
{
time=Double.parseDouble(timeStep.getText());
System.out.println(time);
chrono = new Timer((int)(1000*time),pan);
chrono.start();
}
if(e.getSource()==ip)
{
JPanel options = new JPanel();
JLabel address = new JLabel("IP Address:");
JTextField address_t = new JTextField(15);
JLabel port = new JLabel("Port:");
JTextField port_t = new JTextField(5);
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
System.out.println(address_t.getText());
System.out.println(port_t.getText());
}
}
if(e.getSource()==print)
{
chrono.stop();
}
}
}
}
And here's my Panel.java class:
public class Panel extends JPanel implements ActionListener {
int rand;
int lastrand=0;
ArrayList<Integer> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255,0,0);
Color green = new Color(0,150,0);
Color blue = new Color (0,0,150);
Color yellow = new Color (150,150,0);
int max=0;
int min=0;
int i,k,inc = 0,j;
int total,degr,moyenne;
public Panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.8f));
g2.drawLine(20, 20, 20, this.getHeight()-50);
g2.drawLine(20, this.getHeight()-50, this.getWidth()-50, this.getHeight()-50);
g2.drawLine(20, 20, 15, 35);
g2.drawLine(20, 20, 25, 35);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-45);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-55);
if(!randL.isEmpty()){
g2.setColor(green);
g2.drawLine(15, this.getHeight()-50-max, this.getWidth()-50,this.getHeight()-50-max);
g2.setColor(blue);
g2.drawLine(15, this.getHeight()-50-min, this.getWidth()-50,this.getHeight()-50-min);
g2.setColor(yellow);
g2.drawLine(15, this.getHeight()-50-moyenne, this.getWidth()-50,this.getHeight()-50-moyenne);
}
for(i = 0; i<tL.size(); i++){
int temp = randL.get(i);
int t = tL.get(i);
g2.setColor(red);
g2.drawLine(20+t, this.getHeight()-50-temp, 20+t, this.getHeight()-50);
// Ellipse2D circle = new Ellipse2D.Double();
//circle.setFrameFromCenter(20+t, this.getHeight()-50, 20+t+2, this.getHeight()-52);
}
for(j=0;j<5;j++)
{
inc=inc+40;
g2.setColor(new Color(0,0,0));
g2.drawLine(18, this.getHeight()-50-inc, 22, this.getHeight()-50-inc);
}
inc=0;
}
#Override
public void actionPerformed(ActionEvent e) {
rand = (int)(50+((Math.random() * (80))));
lastT += 60;
randL.add(rand);
tL.add(lastT);
Object obj = Collections.max(randL);
max = (int) obj;
Object obj2 = Collections.min(randL);
min = (int) obj2;
if(!randL.isEmpty()) {
degr = randL.get(k);
total += degr;
moyenne=total/randL.size();
//System.out.println(moyenne);
}
k++;
if(randL.size()>=15)
{
randL.removeAll(randL);
tL.removeAll(tL);
//System.out.println(randL);
lastT = 0;
k=0;
degr=0;
total=0;
moyenne=0;
}
repaint();
}
}
Sorry this work is really messy, but if you succeed in finding the solution i'll thank you ! :D
Cheers!

drawing in swing Java

I'm making the game "Who is millionaire".
This is the help panel, which let user choose one of the options such as: calling friend, asking audience, etc.
But I have a problem, the options are ellipses, which are drawn in class Help_Option extends JComponent. When I test this class Help_Option individually, it works fine. But when I add the Help_Option object into the game panel, actually a sub-panel in the frame, it just displays a line on the panel, it doesn't draw my ellipse.
This is my code:
Note: a is JFrame, I don't copy the whole method initialize(JFrame a) cos it's quite long and I don't think that the error comes from there.
/******Helper panel**********/
JPanel help_area_container = new JPanel();
help_area_container.setBorder(BorderFactory.createLineBorder(Color.BLUE, 3));
help_area_container.setLayout(new GridLayout(4,0));
JPanel voting_container = new JPanel();
JPanel calling_container = new JPanel();
JPanel half_container = new JPanel();
JPanel take_container = new JPanel();
JPanel[] all_help_container = new JPanel[]{voting_container, calling_container, half_container, take_container};
for(int i = 0; i < all_help_container.length; i++){
all_help_container[i].setBorder(BorderFactory.createLineBorder(Color.RED));
all_help_container[i].setPreferredSize(new Dimension(350, help_area_container.getPreferredSize().height/4));
}
for(int j = 0; j < all_help_container.length; j++){
help_area_container.add(all_help_container[j]);
}
Help_Option voting_option = new Help_Option(all_help_container[0].getPreferredSize().width, all_help_container[0].getPreferredSize().height);
voting_option.setPreferredSize(new Dimension(all_help_container[0].getPreferredSize().width, all_help_container[0].getPreferredSize().height));
all_help_container[0].add(voting_option);
a.add(help_area_container, BorderLayout.EAST);
/*****************************/
This is the Help_Option class:
class Help_Option extends JComponent implements MouseMotionListener{
private static int x, y;
private Ellipse2D ellipse;
private Color c = Color.BLACK;
public Help_Option(int x, int y){
Help_Option.x = x;
Help_Option.y = y;
ellipse = new Ellipse2D.Double(0, 0, x, y);
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
g2d.draw(ellipse);
g2d.setColor(c);
g2d.fill(ellipse);
g2d.setColor(Color.RED);
g2d.setFont(new Font("TimesRoman", Font.BOLD, 20));
g2d.drawString("Here I am", 250, 100);
}
public void setColor(Color c){
this.c = c;
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
if(ellipse.contains(e.getX(), e.getY())){
setColor(Color.GREEN);
repaint();
}else{
setColor(Color.BLACK);
repaint();
}
}
}
And this is the class that i used to test Help_Option class:
public class Help extends JFrame{
public static void main(String [] agrs){
Help h = new Help();
h.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
h.init();
}
public void init(){
this.setLayout(new FlowLayout());
this.setSize(2000, 1000);
JPanel a = new JPanel();
a.setPreferredSize(new Dimension((int)a.getSize().width/3, (int)a.getSize().height/2));
a.setBorder(BorderFactory.createLineBorder(Color.yellow, 3));
Help_Option k = new Help_Option(a.getPreferredSize().width, a.getPreferredSize().height/2);
k.setPreferredSize(new Dimension(a.getPreferredSize().width, a.getPreferredSize().height));
a.add(k);
this.add(a);
this.setVisible(true);
}
}
EDIT
This is the link to my classes, please take a look at them. The error is described above.
It is that you haven't set values for your first couple of JPanels and they are returning preferred sizes of 0. Dimensions of 0,0
So you should add values to the JPanels there.
public static void main(String[] args) {
JPanel help_area_container = new JPanel();
help_area_container.setBorder(BorderFactory.createLineBorder(
Color.BLUE, 3));
help_area_container.setLayout(new GridLayout(4, 0));
//Should have set sizes below
JPanel voting_container = new JPanel();
//voting_container.setSize(50,50);
JPanel calling_container = new JPanel();
JPanel half_container = new JPanel();
JPanel take_container = new JPanel();
JPanel[] all_help_container = new JPanel[] { voting_container,
calling_container, half_container, take_container };
for (int i = 0; i < all_help_container.length; i++) {
all_help_container[i].setBorder(BorderFactory
.createLineBorder(Color.RED));
all_help_container[i].setPreferredSize(new Dimension(350,
help_area_container.getPreferredSize().height / 4));
}
for (int i = 0; i < all_help_container.length; i++) {
System.out.println(all_help_container[i].getSize());
}
}
// where you can change the size
all_help_container[0].setSize(50, 50);
System.out.println("----");
for (int i = 0; i < all_help_container.length; i++) {
System.out.println(all_help_container[i].getSize());
}
}
Hopefully this will help you with the sizing of your GUI.
You will have to adjust the different panels to suit your needs. As I'm guessing that this panels will contain some other stuff in them.
You may want to create custom JPanels for each of these, so that you can easily check if they are the right size.
public class VotingPanel extends JPanel {
public VotingPanel(){
//All your variables such as size and color schemes
}
}

The Button wont show and The Shape keep Disappearing when create new one

Thank you I finally got the button to work properly but now I'm stuck at making the shape I just create to stay on screen. Every time I click to create new shape I select the other shape I just create disappear. I look at custom paint but still confuse
public class ShapeStamps extends JFrame {
Random numGen = new Random();
public int x;
public int y;
private JPanel mousePanel, Bpanel;
private JButton circle, square, rectangle, oval;
private int choice = 0;
public ShapeStamps() {
super("Shape Stamps");
Bpanel = new JPanel();
circle = new JButton("Circle");
square = new JButton("Square");
rectangle = new JButton("Rectangle");
oval = new JButton("Oval");
circle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 1;
}
});
square.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 2;
}
});
rectangle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 3;
}
});
oval.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 4;
}
});
mousePanel = new JPanel();
mousePanel.setBackground(Color.WHITE);
MouseHandler handler = new MouseHandler();
setVisible(true);
addMouseListener(handler);
addMouseMotionListener(handler);
add(mousePanel);
Bpanel.add(circle);
Bpanel.add(square);
Bpanel.add(rectangle);
Bpanel.add(oval);
add(Bpanel, BorderLayout.SOUTH);
setSize(500, 500);
setVisible(true);
}
private class MouseHandler extends MouseAdapter implements
MouseMotionListener {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
}
public void paint(Graphics g) {
super.paintComponents(g);
setBounds(0, 0, 500, 500);
Graphics2D g2d = (Graphics2D) g;
if (choice == 0) {
g2d.setFont(new Font("Serif", Font.BOLD, 32));
g2d.drawString("Shape Stamper!", 150, 220);
g2d.setFont(new Font("Serif", Font.ITALIC, 16));
g2d.drawString("Programmed by: None", 150, 245);
}
if (choice == 1) {
Color randomColor1 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor1);
g2d.drawOval(x - 50, y - 50, 100, 100);
}
if (choice == 2) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.drawRect(x - 50, y - 50, 100, 100);
}
if (choice == 3) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.draw(new Rectangle2D.Double(x - 75, y - 50, 150, 100));
}
if (choice == 4) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.draw(new Ellipse2D.Double(x - 50, y - 25, 100, 50));
}
}
}
Everytime the JFrame gets repainted it will go through the drawing process, somif you stamp something on the screen you would have to have a data structure to hold the "objects" that were stamped. This way, each time the drawing process gets called it will repaint the objects on their correct position (and maybe colors with you decide to change this too)

Categories