I had spent two days in solving this problem but I have not found any solution.
I will put some easy code.
There is JFrame with some menu Bar, JPanels, but we focus on 2 options:
"Create Server"
"Close connection"
When I create server, on JPanel I draw checkerboard, and when I close connection, JPanel is clean, but the problem begins when I want to create server one more time, JPanel shows nothing.
I checked the input JPanel, and I put required JPanel before recreate server - nothing
I thought maybe it's gameControl, but I use it in other cases and it works also.
If anybody wants to try:
Here is entire project: http://bycniebytem.cba.pl/checkers.rar
Problem is inside the Checkers.java class,
But I'm waiting for your advices! Thanks!
hostServer.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
hostServer.setEnabled(false);
closeConnection.setEnabled(true);
server = new Server();
try
{
JPanel networkPanel = new JPanel();
player1 = new Player(1,boardSize, fieldSize);
player1.gameControl.setBounds(10, 10, boardSize*fieldSize + 10, boardSize*fieldSize + 10);
player1.gameControl.setSize(boardSize*fieldSize, boardSize*fieldSize);
player1.gameControl.addMouseListener(player1.gameControl);
player1.gameControl.addMouseMotionListener(player1.gameControl);
player1.gameControl.setFocusable(true);
player1.gameControl.setPreferredSize(new Dimension(boardSize*fieldSize,boardSize*fieldSize));
player1.connectWithServer(server.serverSocket.getInetAddress().getHostAddress());
JPanel votePanel = new JPanel();
JRadioButton whiteRadioButton = new JRadioButton("White");
JRadioButton blackRadioButton = new JRadioButton("Black");
blackRadioButton.setBounds(1, 1, 100, 30);
whiteRadioButton.setBounds(1, blackRadioButton.getHeight() + 5, 100, 30);
JButton bReady = new JButton("Ready");
bReady.setBounds(1, whiteRadioButton.getHeight() + 5, 100, 30);
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(whiteRadioButton);
radioGroup.add(blackRadioButton);
votePanel.add(blackRadioButton);
votePanel.add(whiteRadioButton);
votePanel.add(bReady);
votePanel.setBounds(player1.gameControl.getWidth() + 10, 10, blackRadioButton.getWidth(), blackRadioButton.getHeight() * 3);
votePanel.setPreferredSize(new Dimension(blackRadioButton.getWidth(), player1.gameControl.getHeight()));
setSize(boardSize * fieldSize + votePanel.getWidth() + 50, getJMenuBar().getHeight() + boardSize * fieldSize + 20);
networkPanel.add(player1.gameControl);
networkPanel.add(votePanel);
add(networkPanel);
setContentPane(networkPanel);
}
catch(IOException ex)
{
}
}
});
And close connection
closeConnection.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try
{
if(server != null)
{
if(server.getPlayerBlackSocket() != null)
{
server.sendMessage(server.getPlayerBlackSocket(), "closeConnection");
server.getPlayerBlackSocket().close();
}
if(server.getPlayerWhiteSocket() != null)
{
server.sendMessage(server.getPlayerWhiteSocket(), "closeConnection");
server.getPlayerWhiteSocket().close();
}
if(server.getServerSocket() != null)
{
server.getServerSocket().close();
}
}
}
catch (IOException ex)
{
}
player1.isOpenedConnection = false;
JPanel pane = (JPanel) getContentPane();
pane.removeAll();
remove(pane);
JPanel Pan = new JPanel();
JLabel label = new JLabel("label"); // just to test if jpanel can show and it shows
label.setBounds(10,10,100,30);
Pan.add(label);
setContentPane(Pan);
revalidate();
repaint();
closeConnection.setEnabled(false);
hostServer.setEnabled(true);
}
});
Related
Idea of this app is to draw a shape on JPanel. First you would need to choose a shape by clicking a button and then click somewhere on the panel to draw it by using one MouseListener, but I can't figure out how to implement which button is activated after I click it. I tried using getSource(), but it doesn't seem to work. Here's the code:
public class Draw extends JFrame {
private JPanel contentPane;
private Point startPoint = null, endPoint = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Draw frame = new Draw();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Draw() {
getContentPane().setLayout(new BorderLayout(0, 0));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
final PnlDrawing pnldrawing = new PnlDrawing();
contentPane.add(pnldrawing, BorderLayout.CENTER);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
JSeparator separator = new JSeparator();
separator.setOrientation(SwingConstants.VERTICAL);
panel.add(separator);
JButton btnSelect = new JButton("Select");
panel.add(btnSelect);
JButton btnModify = new JButton("Modify");
panel.add(btnModify);
JButton btnRemove = new JButton("Remove");
panel.add(btnRemove);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.NORTH);
final JButton btnAddPoint = new JButton("Add Point");
panel_1.add(btnAddPoint);
final JButton btnAddLine = new JButton("Add Line");
panel_1.add(btnAddLine);
final JButton btnAddCircle = new JButton("Add Circle");
panel_1.add(btnAddCircle);
final JButton btnAddDonut = new JButton("Add Donut");
panel_1.add(btnAddDonut);
final JButton btnAddRectangle = new JButton("Add Rectangle");
panel_1.add(btnAddRectangle);
pnldrawing.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if(e.getSource().equals(btnAddPoint)) {
pnldrawing.shapes.add(new Point(e.getX(), e.getY()));
pnldrawing.repaint();
}
if(e.getSource().equals(btnAddLine)) {
if (startPoint == null)
{
startPoint = new Point(e.getX(),e.getY());
}
else if(endPoint == null)
{
endPoint = new Point(e.getX(),e.getY());
}
if (startPoint != null && endPoint != null)
{
Line line = new Line(startPoint,endPoint);
pnldrawing.shapes.add(line);
pnldrawing.repaint();
startPoint = null;
endPoint = null;
}
}
if(e.getSource().equals(btnAddCircle)) {
DlgCircle drawCircle = new DlgCircle();
drawCircle.setVisible(true);
Point center = new Point(e.getX(),e.getY());
if (drawCircle.isOk)
{
pnldrawing.shapes.add(new Circle(center,Integer.parseInt(drawCircle.txtCircle.getText())));
pnldrawing.repaint();
}
}
if(e.getSource().equals(btnAddDonut)) {
DlgDonut drawDonut = new DlgDonut();
drawDonut.setVisible(true);
Point center = new Point(e.getX(),e.getY());
if (drawDonut.isOk)
{
pnldrawing.shapes.add(new Donut(center,Integer.parseInt(drawDonut.txtRadius.getText()),Integer.parseInt(drawDonut.txtInner.getText())));
pnldrawing.repaint();
}
}
if(e.getSource().equals(btnAddRectangle)) {
DlgRectangleSec drawRect = new DlgRectangleSec();
drawRect.setVisible(true);
Point upperLeft = new Point(e.getX(),e.getY());
if(drawRect.isOk) {
pnldrawing.shapes.add(new Rectangle(upperLeft,Integer.parseInt(drawRect.txtWidth.getText()),Integer.parseInt(drawRect.txtHeight.getText())));
pnldrawing.repaint();
}
}
}
});
}
}
Here's the GUI
First of all you might want to change your painting logic to make it more user friendly. That is you could:
Use the mousePressed event to save the mouse point.
Add logic in the mouseDragged event to paint the shape as the mouse is being dragged.
Finally, in the mouseReleased event you would make the drawing shape permanent.
Check out Custom Painting Approaches for working example. It only paints rectangle, but it should give you a starting point.
but I can't figure out how to implement which button is activated
Use JRadioButton instead of JButton. The button will remain selected.
Then the logic in your MouseListener code becomes something like:
if (addLineButton.isSelected())
// do something
else if (addRectangleButton.isSelected())
// do something
Am I correct that you want to get the button pressed on the mouse? If so, take a look at this link to specify actions done by a certain click. Then you can set a String variable to what button was clicked like String buttonclicked = “left click”.
Right click mouse event
I'm pretty sure I have to make a container and add the labels to the container in the win() and lose() methods. But how should I do this? Also, if you have any other tips to make the code more readable and coherent.
P.S. This is my first time using Java Swing to program graphics, so I know the code is very messy. I mostly just care if the program works the way I want it to...
P.P.S There were a few class variables, but StackOverflow wouldn't let me post them
public class TwoDBettingGame extends JFrame {
/** Constructor to setup the UI components */
public TwoDBettingGame() {
Container cp = this.getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER));
if (money == 0) {
money = 1000;
}
// Define the UI components
JLabel label1 = new JLabel("Your money: $"+String.valueOf(money));
JLabel label2 = new JLabel("How much would you like to bet?");
JLabel label3 = new JLabel("$");
JTextArea textarea1 = new JTextArea(1, 3);
Icon heads = new ImageIcon(getClass().getResource("heads.png"));
Icon tails = new ImageIcon(getClass().getResource("tails.png"));
JButton buttonheads = new JButton(" Heads", heads);
JButton buttontails = new JButton(" Tails", tails);
// Define preferred characteristics
label1.setFont(new Font("Times New Roman", 1, 50));
label2.setFont(new Font("Times New Roman", 1, 33));
label3.setFont(new Font("Times New Roman", 1, 70));
textarea1.setEditable(true);
textarea1.setFont(new Font("Times New Roman", 1, 60));
buttonheads.setPreferredSize(new Dimension(200, 75));
buttontails.setPreferredSize(new Dimension(200, 75));
buttonheads.setFont(new Font("Times New Roman", 1, 30));
buttontails.setFont(new Font("Times New Roman", 1, 30));
// Create new panel with buttons 1 and 2
JPanel panel2 = new JPanel();
panel2.add(buttonheads);
((FlowLayout)panel2.getLayout()).setHgap(40);
panel2.add(buttontails);
// Add all UI components
cp.add(label1);
cp.add(label2);
cp.add(label3);
cp.add(textarea1);
cp.add(panel2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked
setTitle("Betting Game"); // "this" JFrame sets title
setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // or pack() the components
setResizable(false); // window can't be resized
setLocationRelativeTo(null); // puts window in center of screen
setVisible(true); // show it
// Add action listeners to buttons
buttonheads.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sideBetOn = "heads";
// Get TextArea text
String betString = textarea1.getText();
try{
bet = Integer.parseInt(betString);
} catch (NumberFormatException n) {
bet = 0;
}
buttonClicked();
}
});
buttontails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sideBetOn = "tails";
// Get TextArea text
String betString = textarea1.getText();
try{
bet = Integer.parseInt(betString);
} catch (NumberFormatException n) {
bet = 0;
}
buttonClicked();
}
});
}
public void buttonClicked() {
if (bet > 0 && bet <= money) {
int x = rand.nextInt(2);
if (x == 0) {
coinOutcome = "heads";
} else {
coinOutcome = "tails";
} if (coinOutcome.equals(sideBetOn)) {
money = money + bet;
dispose();
win();
Wait();
} else {
money = money - bet;
dispose();
lose();
Wait();
if (money <= 0) {
System.exit(0);
} else {
dispose();
main(null);
}
}
}
}
public void Wait() {
try {
Thread.sleep((long) (secs*1000)); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public void win() {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
// Define the UI components
JLabel label4 = new JLabel("The coin flip was " + coinOutcome + ".");
JLabel label5 = new JLabel("You won $" + bet + "!");
// Define preferred characteristics
label4.setFont(new Font("Times New Roman", 1, 20));
label5.setFont(new Font("Times New Roman", 1, 20));
// Add all UI components
frame.add(label4);
frame.add(label5);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked
setTitle("You Win!!!"); // "this" JFrame sets title
setSize(WINDOW_WIDTH2, WINDOW_HEIGHT2); // or pack() the components
setResizable(false); // window can't be resized
setLocationRelativeTo(null); // puts window in center of screen
setVisible(true); // show it
}
public void lose() {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
// Define the UI components
JLabel label4 = new JLabel("The coin flip was " + coinOutcome + ".");
JLabel label5 = new JLabel("You lost $" + bet + "!");
// Define preferred characteristics
label4.setFont(new Font("Times New Roman", 1, 20));
label5.setFont(new Font("Times New Roman", 1, 20));
// Add all UI components
frame.add(label4);
frame.add(label5);
if (money <= 0) {
JLabel label6 = new JLabel("I'm sorry, you lost. Better luck next time...");
label6.setFont(new Font("Times New Roman", 1, 12));
frame.add(label6);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked
setTitle("You Lose :("); // "this" JFrame sets title
setSize(WINDOW_WIDTH2, WINDOW_HEIGHT2); // or pack() the components
setResizable(false); // window can't be resized
setLocationRelativeTo(null); // puts window in center of screen
setVisible(true); // show it
}
/** The entry main() method */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TwoDBettingGame(); // Let the constructor do the job
}});
}
}
How to add JLabels to JFrame?
I'm pretty sure I have to make a container and add the labels to the container in the win() and lose() methods..
I wouldn't use that approach. A label without text or icon is invisible (unless it has a visible border). So create and add the label at start-up with no text. When a win or loss is achieved, set some text.
If the layout refuses to add space for the label without any text (e.g. in the PAGE_START of a BorderLayout it would have no height), add some text to it before pack() is called, and set it to no text afterwards.
I'm creating a gui that has 2 panels. When the gui is first loaded only one panel is visible and when a button is pressed the new panel is displayed. The problem is that on the 2nd panel when it loads the buttons are invisible and only display when the mouse hovers over them. On top of that when you move the screen they become invisible again and need to be hovered over to be displayed again.
I really don't know what to try as I have looked at methods of having multiple panels and this seems the best way to do it and aswell as this the buttons are implmented the same way I have implemented them for the 1st panel and they render correctly.
Full Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui {
private JFrame frame;
private JPanel panel1;
private JPanel panel2;
private JButton btnShip1, btnShip2, btnShip3, btnTutorial, btnLeftControl, btnHull, btnTargeting, btnRadar, btnWarning, btnRightControl;
private JTextField txtCharacterName, txtShipName;
private JLabel welcome, background;
public static void main(String[] args) {
new Gui();
}
public Gui(){
createWindow();
addButtons();
addFields();
addWelcome();
frame.add(panel1);
frame.setVisible(true);
addBackground();
addShipControls();
}
public void createWindow(){
frame = new JFrame();
frame.setTitle("Space Battle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(642, 518);
panel1 = new JPanel();
panel1.setLayout(null);
panel1.setBackground(Color.decode("#242627"));
panel2 = new JPanel();
panel2.setLayout(null);
panel2.setBackground(Color.decode("#242627"));
}
public void addButtons(){
btnShip1 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/cruiserSelectBtn.jpg");
btnShip1.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_1_hover.gif");
btnShip1.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip1.setBounds(246,0,380,160);
btnShip1.setMargin(new Insets(0, 0, 0, 0));
btnShip1.addActionListener(new cruiserSelectHandler());
btnShip1.setBorder(null);
panel1.add (btnShip1);
btnShip2 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/fighterSelectBtn.jpg");
btnShip2.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_2_hover.gif");
btnShip2.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip2.setBounds(246,160,380,160);
btnShip2.setMargin(new Insets(0, 0, 0, 0));
btnShip2.addActionListener(new fighterSelectHandler());
btnShip2.setBorder(null);
panel1.add (btnShip2);
btnShip3 = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/battleSelectBtn.jpg");
btnShip3.setIcon(img);
}
catch (Exception e) {}
try
{
ImageIcon img = new ImageIcon ("resources/button_3_hover.gif");
btnShip3.setRolloverIcon(img);
}
catch (Exception e) {}
btnShip3.setBounds(246,320,380,160);
btnShip3.setMargin(new Insets(0, 0, 0, 0));
btnShip3.addActionListener(new battleSelectHandler());
btnShip3.setBorder(null);
panel1.add (btnShip3);
btnTutorial = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/tutorialBtn.jpg");
btnTutorial.setIcon(img);
}
catch (Exception e) {}
btnTutorial.setBounds(5,426,234,49);
btnTutorial.setMargin(new Insets(0, 0, 0, 0));
panel1.add (btnTutorial);
}
public void addFields(){
txtCharacterName = new JTextField("Insert Character Name");
txtCharacterName.setBounds(12,260,220,35);
panel1.add(txtCharacterName);
txtShipName = new JTextField("Insert Ship Name");
txtShipName.setBounds(12,315,220,35);
panel1.add(txtShipName);
}
public void addWelcome(){
welcome = new JLabel ();
try
{
ImageIcon img = new ImageIcon ("resources/welcome.jpg");
welcome.setIcon(img);
}
catch (Exception e) {}
welcome.setBounds(0,0,247,229);
panel1.add(welcome);
}
//Class used to change panels
class cruiserSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
class fighterSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
class battleSelectHandler implements ActionListener {
public void actionPerformed(ActionEvent even) {
frame.add(panel2);
panel1.setVisible(false);
}
}
public void addBackground(){
//Is the background interfering?
background = new JLabel ();
try
{
ImageIcon img = new ImageIcon ("resources/background.jpg");
background.setIcon(img);
}
catch (Exception e) {}
background.setBounds(0,0,640,480);
panel2.add(background);
}
//Class used to add controls/buttons
public void addShipControls(){
btnLeftControl = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/left_controls.png");
btnLeftControl.setIcon(img);
}
catch (Exception e) {}
btnLeftControl.setBounds(-8,319,131,160);
btnLeftControl.setMargin(new Insets(0, 0, 0, 0));
btnLeftControl.setBorder(null);
panel2.add (btnLeftControl);
btnHull = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/hull_controls.png");
btnHull.setIcon(img);
}
catch (Exception e) {}
btnHull.setBounds(123,319,91,160);
btnHull.setMargin(new Insets(0, 0, 0, 0));
btnHull.setBorder(null);
panel2.add (btnHull);
btnTargeting = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/targeting_controls.png");
btnTargeting.setIcon(img);
}
catch (Exception e) {}
btnTargeting.setBounds(214,319,202,160);
btnTargeting.setMargin(new Insets(0, 0, 0, 0));
btnTargeting.setBorder(null);
panel2.add (btnTargeting);
btnWarning = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/warning_controls.png");
btnWarning.setIcon(img);
}
catch (Exception e) {}
btnWarning.setBounds(416,411,86,68);
btnWarning.setMargin(new Insets(0, 0, 0, 0));
btnWarning.setBorder(null);
panel2.add (btnWarning);
btnRadar = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/radar_idea.gif");
btnRadar.setIcon(img);
}
catch (Exception e) {}
btnRadar.setBounds(416,319,86,92);
btnRadar.setMargin(new Insets(0, 0, 0, 0));
btnRadar.setBorder(null);
panel2.add (btnRadar);
btnRightControl = new JButton ();
try
{
ImageIcon img = new ImageIcon ("resources/right_controls.png");
btnRightControl.setIcon(img);
}
catch (Exception e) {}
btnRightControl.setBounds(502,319,131,160);
btnRightControl.setMargin(new Insets(0, 0, 0, 0));
btnRightControl.setBorder(null);
panel2.add (btnRightControl);
}
}
when a button is pressed the new panel is displayed.
The problem is:
you are using a null layout
you are add two different panels to the frame.
By default Swing paints components in the reverse order that they were added.
So when you add panel1, it is the only panel of the frame so it is painted.
Then you click a button and add panel2. So Swing paints panel2 and then repaints panel1 on top, so panel2 is hidden. When you mouse over the button it appears because buttons listen for mouseEntered events and the button gets repainted.
When you resize the screen panel2 is painted and then panel1 is painted so you have the problem again.
The solution is to use a proper layout manager. In your case you should be using a Card Layout. The Card Layout will swap panels making sure only one panel is ever visible at a time. Read the Swing tutorial on Using Card Layout. Then get rid of all the null layouts and setBounds() methods.
public class ATMgui extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500;
public static final int HEIGHT = 200;
private ATMbizlogic theBLU;// short for the Business Logic Unit
public JLabel totalBalanceLabel;
public JTextField withdrawTextField;
public JTextField depositTextField;
public JTextField pinTextField;
/**
* Creates a new instance of ATMgui
*/
public ATMgui() {
setTitle("ATM Transactions");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLACK);
contentPane.setLayout(new BorderLayout());
// Do the panel for the rest stop
JLabel start = new JLabel("Welcome To Your Account", JLabel.CENTER);
Font curFont = start.getFont();
start.setFont(new Font(curFont.getFontName(), curFont.getStyle(), 25));
start.setForeground(Color.BLUE);
start.setOpaque(true);
start.setBackground(Color.BLACK);
pinTextField = new JTextField();
JLabel pinLabel = new JLabel("Enter your PIN below:", JLabel.CENTER);
pinLabel.setForeground(Color.RED);
pinLabel.setOpaque(true);
pinLabel.setBackground(Color.WHITE);
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(this);
pinButton.setBackground(Color.red);
JPanel pinPanel = new JPanel();
pinPanel.setLayout(new GridLayout(3, 1, 100, 0));
pinPanel.add(pinLabel);
pinPanel.add(pinTextField);
pinPanel.add(pinButton);
contentPane.add(pinPanel, BorderLayout.WEST);
JPanel headingPanel = new JPanel();
headingPanel.setLayout(new GridLayout());
headingPanel.add(start);
contentPane.add(headingPanel, BorderLayout.NORTH);
// Do the panel for the amount & type of transactions
withdrawTextField = new JTextField();
JLabel withdrawLabel = new JLabel("Withdraw (0.00)", JLabel.CENTER);
withdrawLabel.setForeground(Color.RED);
withdrawLabel.setOpaque(true);
withdrawLabel.setBackground(Color.WHITE);
depositTextField = new JTextField();
JLabel depositLabel = new JLabel("Deposit (0.00)", JLabel.CENTER);
depositLabel.setForeground(Color.RED);
depositLabel.setOpaque(true);
depositLabel.setBackground(Color.WHITE);
JButton txButton = new JButton("Transactions OK");
txButton.addActionListener(this);
txButton.setBackground(Color.red);
JPanel txPanel = new JPanel();
txPanel.setLayout(new GridLayout(5, 1, 30, 0));
txPanel.add(withdrawLabel);
txPanel.add(withdrawTextField);
txPanel.add(depositLabel);
txPanel.add(depositTextField);
txPanel.add(txButton);
contentPane.add(txPanel, BorderLayout.EAST);
txPanel.setVisible(true);
totalBalanceLabel = new JLabel("Your balance after transactions: ", JLabel.CENTER);
totalBalanceLabel.setForeground(Color.BLUE);
totalBalanceLabel.setOpaque(true);
totalBalanceLabel.setBackground(Color.BLACK);
contentPane.add(totalBalanceLabel, BorderLayout.SOUTH);
theBLU = new ATMbizlogic();
}
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK")) {
try {
double deposit = Double.parseDouble(depositTextField.getText().trim());
double withdraw = Double.parseDouble(withdrawTextField.getText().trim());
theBLU.computeBalance(withdraw, deposit);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
} catch (ATMexception ex) {
totalBalanceLabel.setText("Error: " + ex.getMessage());
} catch (Exception ex) {
totalBalanceLabel.setText("Error in deposit or withdraw amount: " + ex.getMessage());
}
} else if (actionCommand.equals("Enter Pin OK")) {
try {
double pin = Double.parseDouble(pinTextField.getText().trim());
theBLU.checkPin(pin);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
} catch (ATMexception ex) {
totalBalanceLabel.setText("Error: " + ex.getMessage());
} catch (Exception ex) {
totalBalanceLabel.setText("Error in pin: " + ex.getMessage());
}
} else {
System.out.println("Error in button interface.");
}
}
public static void main(String[] args) {
ATMgui gui = new ATMgui();
gui.setVisible(true);
}
}
I don't think this is the right way to implement ActionListeners for buttons.
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK"))
else ...
}
With the if-else stamements in the method actionPerformed, your program is forced to check what listener to invoke, every time whatever button is pressed, and, in this way, your code isn't easy to edit and reuse.
Also, the GUI Container is acting like a receiver of events, then you should avoid
pinButton.addActionListener(this);
Try to implement your own inner classes for each button, like this:
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae){
//enter here your action
txPanel.setVisible(true);
}
});
In this way, you don't need to implement the ActionListener interface for your class, because you're implementing a inner istance of the interface for your pinButton. Check this old question of SO.
Also, you should avoid to implement all your GUI elements in your class constructor, it's better to implement the GUI in a separate method, like createAndShowGui(), and call it in the constructor, to respect the Java Swing conventions and to run the Swing components in a different thread, called Event Dispatch Thread, different from the main thread of your application. Read this question.
Then include txPanel.setVisible(false); in createAndShowGui() method.
Remember that the Swing components are not thread-safe.
Since the code pasted by you is not working, I had made a small program for you, have a look, and see what changes can you do to incorporate that in your case :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelTest extends JFrame
{
private JPanel eastPanel;
public PanelTest()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
Container container = getContentPane();
eastPanel = new JPanel();
eastPanel.setBackground(Color.DARK_GRAY);
JPanel westPanel = new JPanel();
westPanel.setBackground(Color.YELLOW);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.BLUE);
container.add(eastPanel, BorderLayout.LINE_START);
container.add(centerPanel, BorderLayout.CENTER);
container.add(westPanel, BorderLayout.LINE_END);
eastPanel.setVisible(false);
JButton showButton = new JButton("Click Me to Display EAST JPanel");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
eastPanel.setVisible(true);
}
});
JButton hideButton = new JButton("Click Me to Hide EAST JPanel");
hideButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
eastPanel.setVisible(false);
}
});
container.add(hideButton, BorderLayout.PAGE_START);
container.add(showButton, BorderLayout.PAGE_END);
setSize(300, 300);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PanelTest();
}
});
}
}
And from future, never use NORTH, EAST, WEST and SOUTH for BorderLayout. They have been replaced with PAGE_START, LINE_START, LINE_END and PAGE_END respectively.
A BorderLayout object has five areas. These areas are specified by the BorderLayout constants:
PAGE_START
PAGE_END
LINE_START
LINE_END
CENTER
Version note:
Before JDK release 1.4, the preferred names for the various areas were different, ranging from points of the compass (for example, BorderLayout.NORTH for the top area) to wordier versions of the constants we use in our examples. The constants our examples use are preferred because they are standard and enable programs to adjust to languages that have different orientations.
I had modified the checkPin(...) method of the ATMLogin class to return a boolean instead of void, so that inside the actionPerformed(...) method of the ATMgui class, if this thing returns true, then only to set the required JPanel to visible, else nothing is to be done.
Do check the code and see what changes you can do to make it work for your end.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ATMgui extends JFrame implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500;
public static final int HEIGHT = 200;
private ATMbizlogic theBLU;// short for the Business Logic Unit
private JPanel txPanel;
public JLabel totalBalanceLabel;
public JTextField withdrawTextField;
public JTextField depositTextField;
public JTextField pinTextField;
/**
* Creates a new instance of ATMgui
*/
public ATMgui()
{
setTitle("ATM Transactions");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLACK);
contentPane.setLayout(new BorderLayout());
// Do the panel for the rest stop
JLabel start = new JLabel("Welcome To Your Account", JLabel.CENTER);
Font curFont = start.getFont();
start.setFont(new Font(curFont.getFontName(), curFont.getStyle(), 25));
start.setForeground(Color.BLUE);
start.setOpaque(true);
start.setBackground(Color.BLACK);
pinTextField = new JTextField();
JLabel pinLabel = new JLabel("Enter your PIN below:", JLabel.CENTER);
pinLabel.setForeground(Color.RED);
pinLabel.setOpaque(true);
pinLabel.setBackground(Color.WHITE);
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(this);
pinButton.setBackground(Color.red);
JPanel pinPanel = new JPanel();
pinPanel.setLayout(new GridLayout(3, 1, 100, 0));
pinPanel.add(pinLabel);
pinPanel.add(pinTextField);
pinPanel.add(pinButton);
contentPane.add(pinPanel, BorderLayout.WEST);
JPanel headingPanel = new JPanel();
headingPanel.setLayout(new GridLayout());
headingPanel.add(start);
contentPane.add(headingPanel, BorderLayout.NORTH);
// Do the panel for the amount & type of transactions
withdrawTextField = new JTextField();
JLabel withdrawLabel = new JLabel("Withdraw (0.00)", JLabel.CENTER);
withdrawLabel.setForeground(Color.RED);
withdrawLabel.setOpaque(true);
withdrawLabel.setBackground(Color.WHITE);
depositTextField = new JTextField();
JLabel depositLabel = new JLabel("Deposit (0.00)", JLabel.CENTER);
depositLabel.setForeground(Color.RED);
depositLabel.setOpaque(true);
depositLabel.setBackground(Color.WHITE);
JButton txButton = new JButton("Transactions OK");
txButton.addActionListener(this);
txButton.setBackground(Color.red);
txPanel = new JPanel();
txPanel.setLayout(new GridLayout(5, 1, 30, 0));
txPanel.add(withdrawLabel);
txPanel.add(withdrawTextField);
txPanel.add(depositLabel);
txPanel.add(depositTextField);
txPanel.add(txButton);
contentPane.add(txPanel, BorderLayout.EAST);
txPanel.setVisible(false);
totalBalanceLabel = new JLabel("Your balance after transactions: ", JLabel.CENTER);
totalBalanceLabel.setForeground(Color.BLUE);
totalBalanceLabel.setOpaque(true);
totalBalanceLabel.setBackground(Color.BLACK);
contentPane.add(totalBalanceLabel, BorderLayout.SOUTH);
theBLU = new ATMbizlogic();
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK"))
{
try
{
double deposit = Double.parseDouble(depositTextField.getText().trim());
double withdraw = Double.parseDouble(withdrawTextField.getText().trim());
theBLU.computeBalance(withdraw, deposit);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
}
/*catch (ATMexception ex)
{
totalBalanceLabel.setText("Error: " + ex.getMessage());
}*/
catch (Exception ex)
{
totalBalanceLabel.setText("Error in deposit or withdraw amount: " + ex.getMessage());
}
}
else if (actionCommand.equals("Enter Pin OK"))
{
try
{
double pin = Double.parseDouble(pinTextField.getText().trim());
if(theBLU.checkPin(pin))
txPanel.setVisible(true);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
}
/*catch (ATMexception ex)
{
totalBalanceLabel.setText("Error: " + ex.getMessage());
}*/
catch (Exception ex)
{
totalBalanceLabel.setText("Error in pin: " + ex.getMessage());
ex.printStackTrace();
}
}
else
{
System.out.println("Error in button interface.");
}
}
public static void main(String[] args)
{
ATMgui gui = new ATMgui();
gui.setVisible(true);
}
}
class ATMbizlogic
{
private double totalBalance;
private boolean rightPinEntered;
/**
* Creates a new instance of ATMbizlogic
*/
public ATMbizlogic()
{
totalBalance = 0.0;
rightPinEntered = true;
}
public void computeBalance(double withdraw, double deposit)
//throws ATMexception
{
if(withdraw <=0)
{
System.out.println("Negative withdraw not allowed");
//throw new ATMexception("Negative withdraw not allowed");
}
if(deposit <=0)
{
System.out.println("Negative deposit not allowed");
//throw new ATMexception("Negative deposit not allowed");
}
double balance = deposit - withdraw;
totalBalance = totalBalance + balance;
}
public boolean checkPin(double pin)
//throws ATMexception
{
if(pin <=0)
{
System.out.println("Negative pin not allowed");
rightPinEntered = false;
//throw new ATMexception("Negative pin not allowed");
}
/*else if(rightPinEntered == false)
{
System.out.println("Can not take another pin");
rightPinEntered = false;
//throw new ATMexception("Can not take another pin");
}*/
else if(pin<1111 || pin>9999)
{
System.out.println("Enter a valid pin");
rightPinEntered = false;
//throw new ATMexception("Enter a valid pin");
}
else
{
rightPinEntered = true;
}
return rightPinEntered;
}
public double getBalance()
{
return totalBalance;
}
}
In the call to constructor ATMgui(), put
txPanel.setVisible(false);
and in the actionCommand.equals("Enter Pin OK") part, you can set it to true.
Is that what you want?
i am new to netbeans ide , i have a swing desktop application and i want to change the default java look and feel (for it) to substance look and feel ( or other) , so how to add substance jar file to my project
(i want to deploy the project to jar file) , and set a look and feel from it .
thanks
First try this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
public Test() {
initComponents();
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
menuBar1 = new JMenuBar();
menu1 = new JMenu();
menuItem5 = new JMenuItem();
menuItem4 = new JMenuItem();
checkBoxMenuItem1 = new JCheckBoxMenuItem();
menuItem3 = new JMenuItem();
menu2 = new JMenu();
menuItem6 = new JMenuItem();
tabbedPane1 = new JTabbedPane();
panel1 = new JPanel();
scrollPane1 = new JScrollPane();
textPane1 = new JTextPane();
button1 = new JButton();
button2 = new JButton();
button3 = new JButton();
scrollPane2 = new JScrollPane();
textArea1 = new JTextArea();
scrollPane3 = new JScrollPane();
tree1 = new JTree();
progressBar1 = new JProgressBar();
radioButton1 = new JRadioButton();
checkBox1 = new JCheckBox();
panel2 = new JPanel();
panel3 = new JPanel();
Container contentPane = getContentPane();
contentPane.setLayout(null);
{
{
menu1.setText("text");
menuItem5.setText("text");
menu1.add(menuItem5);
menuItem4.setText("text");
menu1.add(menuItem4);
menu1.addSeparator();
checkBoxMenuItem1.setText("text");
menu1.add(checkBoxMenuItem1);
menuItem3.setText("text");
menu1.add(menuItem3);
}
menuBar1.add(menu1);
{
menu2.setText("text");
menuItem6.setText("text");
menu2.add(menuItem6);
}
menuBar1.add(menu2);
}
setJMenuBar(menuBar1);
{
{
panel1.setLayout(null);
{
scrollPane1.setViewportView(textPane1);
}
panel1.add(scrollPane1);
scrollPane1.setBounds(15, 15, 665, scrollPane1.getPreferredSize().height);
button1.setText("text");
panel1.add(button1);
button1.setBounds(15, 45, 300, button1.getPreferredSize().height);
button2.setText("text");
panel1.add(button2);
button2.setBounds(325, 45, 140, 23);
button3.setText("text");
panel1.add(button3);
button3.setBounds(470, 45, 210, 23);
{
scrollPane2.setViewportView(textArea1);
}
panel1.add(scrollPane2);
scrollPane2.setBounds(15, 75, 665, 175);
{
scrollPane3.setViewportView(tree1);
}
panel1.add(scrollPane3);
scrollPane3.setBounds(15, 260, 140, 150);
progressBar1.setValue(40);
panel1.add(progressBar1);
progressBar1.setBounds(160, 260, 520, 20);
radioButton1.setText("text");
panel1.add(radioButton1);
radioButton1.setBounds(160, 290, 100, radioButton1.getPreferredSize().height);
checkBox1.setText("text");
panel1.add(checkBox1);
checkBox1.setBounds(265, 295, 165, checkBox1.getPreferredSize().height);
{
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel1.getComponentCount(); i++) {
Rectangle bounds = panel1.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel1.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel1.setMinimumSize(preferredSize);
panel1.setPreferredSize(preferredSize);
}
}
tabbedPane1.addTab("text", panel1);
{
panel2.setLayout(null);
{
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel2.getComponentCount(); i++) {
Rectangle bounds = panel2.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel2.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel2.setMinimumSize(preferredSize);
panel2.setPreferredSize(preferredSize);
}
}
tabbedPane1.addTab("text", panel2);
{
panel3.setLayout(null);
{
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel3.getComponentCount(); i++) {
Rectangle bounds = panel3.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel3.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel3.setMinimumSize(preferredSize);
panel3.setPreferredSize(preferredSize);
}
}
tabbedPane1.addTab("text", panel3);
}
contentPane.add(tabbedPane1);
tabbedPane1.setBounds(10, 10, 700, 450);
{
Dimension preferredSize = new Dimension();
for(int i = 0; i < contentPane.getComponentCount(); i++) {
Rectangle bounds = contentPane.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = contentPane.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
contentPane.setMinimumSize(preferredSize);
contentPane.setPreferredSize(preferredSize);
}
pack();
setLocationRelativeTo(getOwner());
}
private JMenuBar menuBar1;
private JMenu menu1;
private JMenuItem menuItem5;
private JMenuItem menuItem4;
private JCheckBoxMenuItem checkBoxMenuItem1;
private JMenuItem menuItem3;
private JMenu menu2;
private JMenuItem menuItem6;
private JTabbedPane tabbedPane1;
private JPanel panel1;
private JScrollPane scrollPane1;
private JTextPane textPane1;
private JButton button1;
private JButton button2;
private JButton button3;
private JScrollPane scrollPane2;
private JTextArea textArea1;
private JScrollPane scrollPane3;
private JTree tree1;
private JProgressBar progressBar1;
private JRadioButton radioButton1;
private JCheckBox checkBox1;
private JPanel panel2;
private JPanel panel3;
public static void main(String args[]){
new Test().setVisible(true);
}
}
You can also use Nimbus theme, modified to this code :
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception e){
System.out.println("Nimbus isn't available");
}
And edit the main project for this :
public static void main(String args[]){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception e){
System.out.println("Nimbus isn't available");
}
new Test().setVisible(true);
}
Reference :
forum.codecall.net
You place the .jar in a module wrapper, as you would any .jar file in a NetBeans Platform application. As for setting the look and feel, you might want to extend ModuleInstall, specifically, override the restored() method with something like this:
try {
UIManager.setLookAndFeel(new SubstanceRavenGraphiteLookAndFeel());
} catch (Exception e) {
System.out.println("Substance Raven Graphite failed to initialize");
}
Sorry if is old but on Netbeans you can click with the secondary button on your project (right click), and go to Properties.
Next go to Appliation>Desktop App and there you can change the look and feel :).
If you want use Substance LookAndFeel in your application, the easy step is add SubstanceLookAndFeel jar into your library classpath (On NetBeans IDE just right click on library node, then add Substance.jar). After you add substance.jar, in your main application just add this code (before you launch main frame) :
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(new SubstanceLookAndFeel());
} catch (ClassNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
new MainFrame();
}
});
}
If you want NetBeans IDE using Substance Look And Feel too, just put SubstanceLookAndFeel.jar in specific directory (ex. in /home/your-username/LAF/SubstanceLookAndFeel.jar) and launch NetBeans IDE with this command :
$ netbeans --cp:p /home/your-username/LAF/SubstanceLookAndFeel.jar --laf org.jvnet.substance.SubstanceLookAndFeel