I am trying to program a basic 2d shooter game, I took the code from an open source project and edited it to fit my criteria but now when I try to run the game from the main menu window, the game screen open but doesn't take any input anymore and the game wont start without pressing a button.
this is the code for the game loop and the home menu:
`
public void gameLoop() {
long lastLoopTime = System.currentTimeMillis();
// keep looping round til the game ends
while (gameRunning) {
// work out how long its been since the last update, this
// will be used to calculate how far the entities should
// move this loop
long delta = System.currentTimeMillis() - lastLoopTime;
lastLoopTime = System.currentTimeMillis();
// Get hold of a graphics context for the accelerated
// surface and blank it out
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.blue);
g.fillRect(0,0,800,600);
Random rd = new Random(); // creating Random object
boolean dir = rd.nextBoolean();
// cycle round asking each entity to move itself
if (!waitingForKeyPress) {
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
if(entity instanceof AlienEntity) {
if(entity.getX() <= 10 || entity.getY() <= 0 || entity.getX() >= 800) {
removeEntity(entity);
initAliens();
}
}
entity.move(delta,dir);
}
}
// cycle round drawing all the entities we have in the game
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.draw(g);
}
// brute force collisions, compare every entity against
// every other entity. If any of them collide notify
// both entities that the collision has occured
for (int p=0;p<entities.size();p++) {
for (int s=p+1;s<entities.size();s++) {
Entity me = (Entity) entities.get(p);
Entity him = (Entity) entities.get(s);
if (me.collidesWith(him)) {
me.collidedWith(him);
him.collidedWith(me);
initAliens();
score++;
scoreLabel.setText("Score="+Integer.toString(score));
}
}
}
// remove any entity that has been marked for clear up
entities.removeAll(removeList);
removeList.clear();
// if a game event has indicated that game logic should
// be resolved, cycle round every entity requesting that
// their personal logic should be considered.
if (logicRequiredThisLoop) {
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.doLogic();
}
logicRequiredThisLoop = false;
}
// if we're waiting for an "any key" press then draw the
// current message
if (waitingForKeyPress) {
g.setColor(Color.white);
g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250);
g.drawString("Press any key to start, and click X to go back to main menu",(800-g.getFontMetrics().stringWidth("Press any key to start, and click X to go back to main menu"))/2,300);
}
// finally, we've completed drawing so clear up the graphics
// and flip the buffer over
g.dispose();
strategy.show();
// resolve the movement of the ship. First assume the ship
// isn't moving. If either cursor key is pressed then
// update the movement appropraitely
ship.setHorizontalMovement(0);
if ((leftPressed) && (!rightPressed)) {
ship.setHorizontalMovement(-moveSpeed);
} else if ((rightPressed) && (!leftPressed)) {
ship.setHorizontalMovement(moveSpeed);
}
// if we're pressing fire, attempt to fire
if (firePressed) {
tryToFire();
}
// finally pause for a bit. Note: this should run us at about
// 100 fps but on windows this might vary each loop due to
// a bad implementation of timer
try { Thread.sleep(10); } catch (Exception e) {}
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.nio.channels.IllegalBlockingModeException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.security.auth.x500.X500Principal;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Home extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Home frame = new Home("ddd",1);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Home(String username, int highscore) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Play");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Game game = new Game();
game.main(null);
}
});
btnNewButton.setFont(new Font("Times New Roman", Font.BOLD, 17));
btnNewButton.setBounds(107, 118, 111, 55);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel(username);
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
lblNewLabel.setBounds(140, 11, 196, 36);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("HighScore = " + Integer.toString(highscore));
lblNewLabel_1.setFont(new Font("Times New Roman", Font.BOLD, 15));
lblNewLabel_1.setBounds(10, 10, 120, 36);
contentPane.add(lblNewLabel_1);
JButton btnNewButton_1 = new JButton("Change Password");
btnNewButton_1.setFont(new Font("Times New Roman", Font.BOLD, 13));
btnNewButton_1.setBounds(228, 118, 141, 55);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Quit");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnNewButton_2.setBounds(341, 232, 85, 21);
contentPane.add(btnNewButton_2);
}
}
`
I tried creating a new instance of game and calling the main function but it didn't work, I also tried calling a normal function, I tried calling the gameloop itself on the game instance but it didn't work.
Related
I'm trying to make an ActionListener for a specific JComponent, but in my code, there are two JComponents which have ActionListeners.
Here's my code:
/**
* This is a Java Swing program that lets you play Minesweeper! Make sure to play it in fullscreen or else it's not going to work.
* #author Joshua Diocares
* #version JDK14.0
* #since Still in development!
*/
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
/**
* A class that shows the xy coordinates near the mouse cursor.
*/
class AlsXYMouseLabelComponent extends JComponent {
public int x;
public int y;
/**
* Uses the xy coordinates to update the mouse cursor label.
*/
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
String coordinates = x + ", " + y; // Get the cordinates of the mouse
g.setColor(Color.red);
g.drawString(coordinates, x, y); // Display the coordinates of the mouse
}
}
public class Minesweeper implements ActionListener {
private static JComboBox < String > gameModeDropdown;
private static JComboBox < String > difficultyDropdown;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame = new JFrame();
frame.setSize(1365, 767);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Tic Tac Toe");
frame.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
frame.setVisible(true);
frame.add(panel);
panel.setLayout(null);
AlsXYMouseLabelComponent alsXYMouseLabel = new AlsXYMouseLabelComponent();
/**
* Add the component to the DRAG_LAYER of the layered pane (JLayeredPane)
*/
JLayeredPane layeredPane = frame.getRootPane().getLayeredPane();
layeredPane.add(alsXYMouseLabel, JLayeredPane.DRAG_LAYER);
alsXYMouseLabel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
/**
* Add a mouse motion listener, and update the crosshair mouse cursor with the xy coordinates as the user moves the mouse
*/
frame.addMouseMotionListener(new MouseMotionAdapter() {
/**
* Detects when the mouse moved and what the mouse's coordinates are.
* #param event the event that happens when the mouse is moving.
*/
#Override
public void mouseMoved(MouseEvent event) {
alsXYMouseLabel.x = event.getX();
alsXYMouseLabel.y = event.getY();
alsXYMouseLabel.repaint();
}
});
JLabel title = new JLabel("Minesweeper");
title.setBounds(500, 100, 550, 60);
title.setFont(new Font("Verdana", Font.PLAIN, 50));
panel.add(title);
JLabel gameModePrompt = new JLabel("Game Mode: ");
gameModePrompt.setBounds(280, 335, 300, 25);
gameModePrompt.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(gameModePrompt);
String[] gameModes = {
"Normal"
};
JComboBox < String > gameModeDropdown = new JComboBox < String > (gameModes);
gameModeDropdown.setBounds(415, 335, 290, 25);
gameModeDropdown.setFont(new Font("Verdana", Font.PLAIN, 20));
gameModeDropdown.addActionListener(new Minesweeper());
panel.add(gameModeDropdown);
JLabel difficultyPrompt = new JLabel("Difficulty: ");
difficultyPrompt.setBounds(800, 335, 240, 25);
difficultyPrompt.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(difficultyPrompt);
String[] difficulties = {
"Medium"
};
JComboBox < String > difficultyDropdown = new JComboBox < String > (difficulties);
difficultyDropdown.setBounds(910, 335, 120, 25);
difficultyDropdown.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(difficultyDropdown);
JButton playButton = new JButton("Play");
playButton.setBounds(530, 480, 220, 25);
playButton.setFont(new Font("Verdana", Font.PLAIN, 20));
playButton.addActionListener(new Minesweeper());
panel.add(playButton);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Any suggestions would be really helpful
I cleaned up your code. I added a PlayListener class as the ActionListener to your Play button. You don't need an ActionListener for either dropdown. You can get the selected dropdown values when you need them in the PlayListener class.
I added a call to the SwingUtilities invokeLater method. This method ensures that your Swing components are created and executed on the Event Dispatch Thread.
I rearranged your JFrame method calls. I don't know if you noticed, but you made the JFrame visible before you created the components. You have to create all the components before you display your JFrame.
Using a null layout and absolute positioning are discouraged. Swing GUIs have to run on different operating systems with different screen monitor pixel sizes. Your GUI barely fit on my monitor. I left your absolute positioning code alone, but in the future, you should learn to use Swing layout managers.
I made the AlsXYMouseLabelComponent class an inline class. You can have as many inline classes as you want. Generally, though, each class should be in a separate file. I made the classes inline to show you how inline classes are defined, and also so I can paste a runnable example file.
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Minesweeper implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Minesweeper());
}
private JComboBox<String> gameModeDropdown;
private JComboBox<String> difficultyDropdown;
#Override
public void run() {
JPanel panel = new JPanel();
JFrame frame = new JFrame("Minesweeper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
panel.setLayout(null);
AlsXYMouseLabelComponent alsXYMouseLabel =
new AlsXYMouseLabelComponent();
/**
* Add the component to the DRAG_LAYER of the layered pane (JLayeredPane)
*/
JLayeredPane layeredPane = frame.getRootPane().getLayeredPane();
layeredPane.add(alsXYMouseLabel, JLayeredPane.DRAG_LAYER);
alsXYMouseLabel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
/**
* Add a mouse motion listener, and update the crosshair mouse cursor with the
* xy coordinates as the user moves the mouse
*/
frame.addMouseMotionListener(new MouseMotionAdapter() {
/**
* Detects when the mouse moved and what the mouse's coordinates are.
*
* #param event the event that happens when the mouse is moving.
*/
#Override
public void mouseMoved(MouseEvent event) {
alsXYMouseLabel.x = event.getX();
alsXYMouseLabel.y = event.getY();
alsXYMouseLabel.repaint();
}
});
JLabel title = new JLabel("Minesweeper");
title.setBounds(500, 100, 550, 60);
title.setFont(new Font("Verdana", Font.PLAIN, 50));
panel.add(title);
JLabel gameModePrompt = new JLabel("Game Mode: ");
gameModePrompt.setBounds(280, 335, 300, 25);
gameModePrompt.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(gameModePrompt);
String[] gameModes = { "Normal" };
gameModeDropdown = new JComboBox<String>(gameModes);
gameModeDropdown.setBounds(415, 335, 290, 25);
gameModeDropdown.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(gameModeDropdown);
JLabel difficultyPrompt = new JLabel("Difficulty: ");
difficultyPrompt.setBounds(800, 335, 240, 25);
difficultyPrompt.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(difficultyPrompt);
String[] difficulties = { "Easy", "Medium", "Hard" };
difficultyDropdown = new JComboBox<String>(difficulties);
difficultyDropdown.setSelectedIndex(1);
difficultyDropdown.setBounds(910, 335, 120, 25);
difficultyDropdown.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(difficultyDropdown);
JButton playButton = new JButton("Play");
playButton.setBounds(530, 480, 220, 25);
playButton.setFont(new Font("Verdana", Font.PLAIN, 20));
playButton.addActionListener(new PlayListener());
panel.add(playButton);
frame.add(panel);
frame.setSize(1365, 767);
frame.setVisible(true);
}
public class PlayListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
}
}
/**
* A class that shows the xy coordinates near the mouse cursor.
*/
public class AlsXYMouseLabelComponent extends JComponent {
private static final long serialVersionUID = 1L;
public int x;
public int y;
/**
* Uses the xy coordinates to update the mouse cursor label.
*/
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
String coordinates = x + ", " + y; // Get the cordinates of the mouse
g.setColor(Color.red);
g.drawString(coordinates, x, y); // Display the coordinates of the mouse
}
}
}
I am making autoclicker as a project and when i open now the window design thingy its shows me just a blank.
im trying to ask from the user to write a number in the spinner
the spinner sending it to the delay.
than you press a key to run the autoclicker and stop him
but i still didnt put the keylistener now im just trying to get output which is the delay from the spinner, not work well till now.
package autoclicker;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.InputEvent;
import java.util.*;
import javax.swing.JFormattedTextField;
public class auto {
static Scanner console = new Scanner(System.in);
private Robot robot;
private int delay;
public void AutoClicker1() {
try
{
robot = new Robot();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void clickMouse(int button)
{
try {
robot.mousePress(button);
robot.delay(10);
robot.mouseRelease(button);
robot.delay(delay);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void setDelay(int delayy)
{
this.delay = delayy;
}
}
THIS IS THE MAIN
package autoclicker;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.lang.Thread;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class autoclicker {
private static KeyEvent e;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
JFrame frame = new JFrame("AutoClicker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setVisible(true);
frame.setResizable(false);
JPanel Panel = new JPanel();
Panel.setBackground(Color.DARK_GRAY);
Panel.setLayout(null);
JLabel AutoClicker = new JLabel("delay\r\n in ms");
AutoClicker.setBounds(10, 80, 151, 30);
AutoClicker.setForeground(Color.WHITE);
AutoClicker.setFont(new Font("Secular One", Font.PLAIN, 20));
JLabel label = new JLabel("AutoClicker");
label.setForeground(Color.CYAN);
label.setFont(new Font("Secular One", Font.PLAIN, 30));
label.setBounds(10, 11, 200, 57);
Panel.add(label);
JSpinner spinner = new JSpinner();
int Delayy = (int) spinner.getValue();
spinner.setBounds(128, 87, 69, 20);
Panel.add(spinner);
frame.add(Panel);
auto clicker = new auto();
System.out.println("----Auto Clicker----");
System.out.println("Enter delay in ms:");
while(Delayy==0)
{
}
clicker.setDelay(Delayy);
System.out.println("Program will start in 3 seconds.");
try {
System.out.println(3);
Thread.sleep(1000);
System.out.println(2);
Thread.sleep(1000);
System.out.println(1);
Thread.sleep(1000);
}
catch (Exception e)
{
e.printStackTrace();
}
clicker.AutoClicker1();
for(int i = 0; i<100; i++)
{
clicker.clickMouse(InputEvent.BUTTON1_DOWN_MASK);
}
}
}
You need to add your panel to your JFrame.
frame.add(Panel);
Once you add components to your JFrame you then need to setVisibility() to true in order for it to show.
frame.setVisible(true);
I am having a problem with Java's Swing library. I added an Admission Class to JTabbedPane. The Button and ComboBox components on the first tab appear not to be working but, but when I remove setLayout(null) it seems to work, but this leads to other problems with the layout...
Below is what I have tried thus far:
DBProjectPractice.java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
public class DBProjectPractice extends JFrame {
private Container contentPane;
private String User = null;
public String getUser() {
String user = this.User;
return user;
}
public DBProjectPractice() {
// TODO Auto-generated constructor stub
init();
}
JTabbedPane pane = new JTabbedPane();
JTabbedPane createTabbedPane() { // tab pane init
pane.addTab("text", new Admission()); // 입사 탭의 레이아웃.
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
pane.addTab("text", new JLabel("text.", JLabel.CENTER));
return pane;
}
public void init() {
contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout(30, 30));
setTitle("text");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane jtabbedpane = createTabbedPane();
contentPane.add(new Top(), BorderLayout.NORTH);
contentPane.add(jtabbedpane, BorderLayout.CENTER);
setLocationByPlatform(true);
setSize(1600, 1000); // 사이즈 설정 // 가로 세로
setVisible(true); // 표시
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new DBProjectPractice();
}
}
Top.java
import java.awt.Font;
import java.awt.Graphics;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JPanel;
class Top extends JPanel{
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Date date = new Date();
SimpleDateFormat text = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
Font f = new Font("Times", Font.BOLD, 15);
g.setFont(f);
g.drawString("text : " , 100, 25);
g.drawString("text : " + text.format(date), 1200, 25);
this.setSize(1600, 30);
}
}
Admission.java
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
public class Admission extends JPanel {
private Container pane;
public Admission() {
// TODO Auto-generated constructor stub
setLayout(null);
Admission_Button();
FixLable_JLabel();
ComboBox();
}
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Font f = new Font("Times", Font.BOLD, 15); // 글꼴 설정
g.setFont(f); // 글꼴 지정
g.drawString(":::: text ::::", 100, 100);
g.drawString(":::: text ::::", 100, 500);
this.setSize(1600, 30);
}
private void Admission_Button() { // 입사 탭의 레이아웃의 버튼
JButton[] Button = new JButton[3];
Button[0] = new JButton(" text ");
Button[1] = new JButton(" text ");
Button[2] = new JButton(" text ");
for(int i = 0; i < 3; i++) {
Button[i].setSize(100,40);
Button[i].setLocation(1065 + i * 120, 130);
add(Button[i]);
}
}
private void FixLable_JLabel() {
JLabel[] FixLabel = new JLabel[15]; // 고정된 label;
String[] FixLabelName = { "text", "text", "text","text","text","text","text","text","text","text",
"text","text","text","text","text"};
EtchedBorder eb = new EtchedBorder(Color.BLACK, Color.GRAY); // 테두리를 넣는다.
int FixLableIndex = 0;
for (String name : FixLabelName) {
FixLabel[FixLableIndex] = new JLabel(name);
FixLabel[FixLableIndex].setHorizontalAlignment(SwingConstants.CENTER); // 가운대 정렬
FixLabel[FixLableIndex].setBorder(eb); // 테두리 추가
FixLabel[FixLableIndex++].setSize(120, 30);
}
for(int i = 0 ; i < 7 ; i++) {
FixLabel[i].setLocation(100,200 + i * 30);
}
int t = 0;
for(int i = 7 ; i < 10 ; i++) {
FixLabel[i].setLocation(550,230 + t++ * 30);
}
FixLabel[10].setLocation(550, 350);
t = 0;
for(int i = 11 ; i < 14 ; i++) {
FixLabel[i].setLocation(1050,230 + t++ * 30);
}
FixLabel[14].setLocation(1050, 350);
for(int i = 0 ; i < 15; i++) {
add(FixLabel[i]);
}
}
private void ComboBox() {
String[] type = {"text", "text","text","text"};
JComboBox<String> typeCombo = new JComboBox<String>();
int num = type.length;
for(int i = 0 ; i < num ; i++) {
typeCombo.addItem(type[i]);
}
typeCombo.setBounds(220, 200, 1200, 30);
typeCombo.setSelectedItem(2);
add(typeCombo);
setVisible(true);
}
}
Your biggest problem (to me) seems to be that you're calling setSize(...) on your component within its own paintComponent method, a painting method:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Font f = new Font("Times", Font.BOLD, 15);
g.setFont(f);
g.drawString(":::: text ::::", 100, 100);
g.drawString(":::: text ::::", 100, 500);
this.setSize(1600, 30); // **** HERE ****
}
This is not correct and in fact dangerous, because it may try to change the component's size on any repaint, which then calls repaint almost recursively. Also the size that you're setting it to is unreasonable as a height of 30 can't possibly display the GUI that this JPanel holds. Don't do this.
Better:
to set size once via setSize(...) within the components constructor.
Better still to instead set preferred size by calling setPreferredSize(Dimension d) within the constructor.
Even better still is to instead override the component class's getPreferredSize().
Your other problem is that you're using null layouts. Again, while null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
i would like to know how can i see the components in my JDialog when calling it from another one.
I have one jDialog called Cargando1 which has a ProgressBar inside,this jDialog runs a method called iterate() when loading.
Otherwise i have another jDialog called login1, it has a button called btnIngresar, it validates some user and password stuff and then it should call Cargando1.
Also cargando1 calls a Frame called Principal after the progressbar has reach 100% but it doesn't matter.
I would like to know why when i called Cargando1 from Login1 it runs but i can't see the components on it.
Thank you for helping me!
This is the Jdialog called Login1
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login1 extends JDialog implements ActionListener {
private JLabel lblUsuario;
private JTextField txtUsuario;
private JPasswordField jpassContrasena;
private JLabel lblContrasena;
private JButton btnIngresar;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Login1 dialog = new Login1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Login1() {
setBounds(100, 100, 225, 157);
getContentPane().setLayout(null);
lblUsuario = new JLabel("Usuario:");
lblUsuario.setFont(new Font("Courier New", Font.PLAIN, 11));
lblUsuario.setBounds(10, 12, 80, 20);
getContentPane().add(lblUsuario);
txtUsuario = new JTextField();
txtUsuario.setColumns(10);
txtUsuario.setBounds(101, 11, 95, 20);
getContentPane().add(txtUsuario);
jpassContrasena = new JPasswordField();
jpassContrasena.setBounds(101, 43, 95, 20);
getContentPane().add(jpassContrasena);
lblContrasena = new JLabel("Contrase\u00F1a:");
lblContrasena.setFont(new Font("Courier New", Font.PLAIN, 11));
lblContrasena.setBounds(10, 44, 80, 20);
getContentPane().add(lblContrasena);
btnIngresar = new JButton("Ingresar");
btnIngresar.addActionListener(this);
btnIngresar.setBounds(60, 80, 90, 23);
getContentPane().add(btnIngresar);
}
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == btnIngresar) {
actionPerformedBtnIngresar(arg0);
}
}
protected void actionPerformedBtnIngresar(ActionEvent arg0) {
char contrasena[] = jpassContrasena.getPassword();
String contrasenadef = new String(contrasena);
if (txtUsuario.getText().equals("Administrador") && contrasenadef.equals("admin"))
{ Principal.sesion = 'A';
JOptionPane.showMessageDialog(this, "Bienvenido, administrador", "Mensaje de bienvenida", JOptionPane.INFORMATION_MESSAGE);
Cargando1 dialog = new Cargando1();
this.dispose();
dialog.setVisible(true);
dialog.iterate();
}
else if (txtUsuario.getText().equals("Vendedor") && contrasenadef.equals("vendedor"))
{ Principal.sesion = 'V';
JOptionPane.showMessageDialog(this, "Bienvenido, vendedor", "Mensaje de bienvenida", JOptionPane.INFORMATION_MESSAGE);
Cargando1 dialog = new Cargando1();
this.dispose();
dialog.setVisible(true);
dialog.iterate();
}
else
{ JOptionPane.showMessageDialog(null, "Por favor ingrese un usuario y/o contraseña correctos", "Acceso denegado", JOptionPane.ERROR_MESSAGE);
}
}
}
This is the JDialog called cargando1
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JProgressBar;
public class Cargando1 extends JDialog {
private final JPanel contentPanel = new JPanel();
private JProgressBar pgbCargando;
int porcentaje=0;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Cargando1 dialog = new Cargando1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.iterate();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Cargando1() {
setBounds(100, 100, 450, 154);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
pgbCargando = new JProgressBar(0,2000);
pgbCargando.setBounds(10, 11, 414, 93);
pgbCargando.setStringPainted(true);
contentPanel.add(pgbCargando);
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
setContentPane(contentPanel);
}
void iterate() {
while (porcentaje < 2000)
{ pgbCargando.setValue(porcentaje);
try {Thread.sleep(100);}
catch (InterruptedException e) { }
porcentaje += 95;
}
Principal formulario1 = new Principal();
formulario1.setLocationRelativeTo(null);
this.dispose();
formulario1.setVisible(true);
}
}
The problem is in the iterate() method. Change your iterate() method to the following and give it a try.
void iterate() {
final Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (porcentaje < 2000) {
pgbCargando.setValue(porcentaje);
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
}
porcentaje += 95;
}
}
});
t.setDaemon(true);
t.start();
}
This will free up the main thread to do gui updates while the ProgressBar's value is modified in the background.
Two things to fix(and a note for the future):
Use Cargando1.setVisible(true) in Cargando1
DO NOT use Thread.sleep for swing, because javax.swing is not thread-safe. Your JDialog will freeze if you use Thread.sleep. Rather, use a Timer(javax.swing) with an ActionListener, or if you really want to use Thread.sleep, look into multithreading.
3. please indent better!!!! usually a new line with an extra 4 spaces after every {
I am using WindowBuilder in Eclipse to aid in my GUI design. I am trying to make a Jlist popup after the user either enters in a text file with integers in it or, if they enter a file that doesn't exist, they select a file with integers in it from JFileChooser. My problem I am having now is that when the file is selected, nothing happens. The program also doesn't seem to recognize when I do enter in a file that exists, it just defaults to the JFileChooser. Any ideas as to what I'm doing wrong and/or how to make the Jlist appear after an appropriate file is entered?
Here is the code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GUI {
private JFrame frame;
private JTextField txtEnterFileName;
private JTextField textField;
private JFileChooser fileChooser;
private JList list;
private JList list_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtEnterFileName = new JTextField();
txtEnterFileName.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtEnterFileName.setEditable(false);
txtEnterFileName.setText("Enter File Name Below and Press Button");
txtEnterFileName.setBounds(72, 11, 304, 41);
frame.getContentPane().add(txtEnterFileName);
txtEnterFileName.setColumns(10);
textField = new JTextField();
textField.setBounds(113, 63, 221, 25);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int number;
boolean endOfFile = false;
File userF;
userF = new File(textField.getText());
if(!userF.exists()){
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home") + "/desktop"));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(userF.exists()){
try {
Scanner inFile = new Scanner(userF);
if(inFile.hasNextLine()){
inFile.close();
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(inFile.hasNextInt()){
String label[] = {"Smallest Number", "Largest Number", "Count", "Average", "Median", "Quit"};
list = new JList(label);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
});
btnNewButton.setBounds(174, 99, 89, 23);
frame.getContentPane().add(btnNewButton);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
Scanner#nextLine always seems to return true so long as there some text on the first line.
So a file in the format of ...
1 2 3 4 5 6
Will have Scanner#nextLine return true. Instead, you should check for hasNextInt first and then skip over to showing the JFileChooser
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify