how to change swing look and feel in netbeans - java

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

Related

JPanels content doesn't reshow

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

How to make an image move using the keyboard in java?

I have a maze that I need to get a ball to move through, but I don't know what code I need to use to move the image of the ball around the maze.
I have been given a hint that I need to swap images round.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CBallMaze extends JFrame implements ActionListener
{
//Below is where I have declared all the different objects I have used throughout my program
private JButton buttonRight, buttonLeft, buttonUp, buttonDown, buttonTL, buttonTR, buttonBL, buttonBR, buttonCenter, optionOne, optionTwo, optionThree, optionExit, scenarioAct, scenarioRun, scenarioReset, compassPH;
private JButton [] game = new JButton [208];
private JPanel panelCentre, panelRight, panelBottom, buttonPanel, compassPanel, optionsPanel, selectionPanel, panelAct, panelRun, panelReset, panelSlider;
private JTextField optionTF, squareTF, directionTF;
private JLabel option, square, direction, compassDirection;
private JSlider speedSlider;
private String firstOption = "1", secondOption = "2", thirdOption = "3", upDirection = "North", rightDirection = "East", downDirection = "South", leftDirection = "West";
private int i;
private int[] map = new int[]
{
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
};
final ImageIcon iconCompassNorth = new ImageIcon("north.jpg");
final ImageIcon iconCompassWest = new ImageIcon("west.jpg");
final ImageIcon iconCompassSouth = new ImageIcon("south.jpg");
final ImageIcon iconCompassEast = new ImageIcon("east.jpg");
ImageIcon iconReset = new ImageIcon("Reset.jpg");
ImageIcon iconRun = new ImageIcon("Run.jpg");
ImageIcon iconAct = new ImageIcon("Act.jpg");
ImageIcon iconSand, iconWhite, iconBall, iconEnd;
public CBallMaze(String title) {
super(title);
}
public static void main(String[] args)
{
CBallMaze cBallMaze = new CBallMaze("CBallMaze Ball Maze Application");
cBallMaze.setSize(775, 650);
cBallMaze.createGUI();
cBallMaze.setVisible(true);
}
private void createGUI()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new BorderLayout() );
//Panels
panelCentre = new JPanel();
panelCentre.setPreferredSize(new Dimension(625, 450));
panelCentre.setBackground(Color.BLACK);
window.add(panelCentre);
panelCentre.setLayout(new GridLayout(13, 16));
panelRight = new JPanel();
panelRight.setPreferredSize(new Dimension(180, 450));
panelRight.setBackground(Color.WHITE);
window.add(panelRight, BorderLayout.EAST);
optionsPanel = new JPanel();
optionsPanel.setPreferredSize(new Dimension(150, 100));
optionsPanel.setBackground(Color.WHITE);
panelRight.add(optionsPanel, BorderLayout.EAST);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(175, 100));
buttonPanel.setBackground(Color.WHITE);
panelRight.add(buttonPanel, BorderLayout.EAST);
selectionPanel = new JPanel();
selectionPanel.setPreferredSize(new Dimension(175, 150));
selectionPanel.setBackground(Color.WHITE);
panelRight.add(selectionPanel, BorderLayout.EAST);
ImageIcon cw = new ImageIcon("west.jpg");
compassPanel = new JPanel();
compassPanel.setPreferredSize(new Dimension(175, 300));
compassPanel.setBackground(Color.WHITE);
panelRight.add(compassPanel, BorderLayout.EAST);
panelBottom = new JPanel();
panelBottom.setPreferredSize(new Dimension(875, 50));
panelBottom.setBackground(Color.WHITE);
window.add(panelBottom, BorderLayout.SOUTH);
panelAct = new JPanel();
panelAct.setPreferredSize(new Dimension(125, 40));
panelAct.setBackground(Color.WHITE);
panelBottom.add(panelAct, BorderLayout.SOUTH);
panelRun = new JPanel();
panelRun.setPreferredSize(new Dimension(125, 40));
panelRun.setBackground(Color.WHITE);
panelBottom.add(panelRun, BorderLayout.SOUTH);
panelReset = new JPanel();
panelReset.setPreferredSize(new Dimension(125, 40));
panelReset.setBackground(Color.WHITE);
panelBottom.add(panelReset, BorderLayout.SOUTH);
panelSlider = new JPanel();
panelSlider.setPreferredSize(new Dimension(200, 40));
panelSlider.setBackground(Color.WHITE);
panelBottom.add(panelSlider, BorderLayout.SOUTH);
//Displays
option = new JLabel("Option: ");
optionsPanel.add(option, BorderLayout.LINE_START);
option.setEnabled(true);
option.setForeground(Color.BLACK);
option.setHorizontalAlignment(JLabel.LEFT);
optionTF = new JTextField("1");
optionsPanel.add(optionTF, BorderLayout.LINE_END);
optionTF.setEnabled(true);
optionTF.setPreferredSize(new Dimension(50, 25));
optionTF.setHorizontalAlignment(JTextField.CENTER);
square = new JLabel("Square: ");
optionsPanel.add(square, BorderLayout.LINE_START);
square.setEnabled(true);
square.setForeground(Color.BLACK);
square.setHorizontalAlignment(JLabel.LEFT);
squareTF = new JTextField("");
optionsPanel.add(squareTF, BorderLayout.LINE_END);
squareTF.setEnabled(true);
squareTF.setPreferredSize(new Dimension(50, 25));
squareTF.setHorizontalAlignment(JTextField.CENTER);
direction = new JLabel("Direction: ");
optionsPanel.add(direction, BorderLayout.LINE_START);
direction.setEnabled(true);
direction.setForeground(Color.BLACK);
direction.setHorizontalAlignment(JLabel.LEFT);
directionTF = new JTextField("Still");
optionsPanel.add(directionTF, BorderLayout.LINE_END);
directionTF.setEnabled(true);
directionTF.setPreferredSize(new Dimension(50, 25));
directionTF.setHorizontalAlignment(JTextField.CENTER);
//buttons
buttonTL = new JButton("");
buttonPanel.add(buttonTL);
buttonTL.setPreferredSize(new Dimension(45, 25));
buttonTL.setEnabled(false);
buttonUp = new JButton("^");
buttonPanel.add(buttonUp);
buttonUp.setPreferredSize(new Dimension(45, 25));
buttonUp.addActionListener(this);
buttonUp.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(upDirection);
compassDirection.setIcon(iconCompassNorth);
}
});
buttonTR = new JButton("");
buttonPanel.add(buttonTR);
buttonTR.setPreferredSize(new Dimension(45, 25));
buttonTR.setEnabled(false);
buttonLeft = new JButton("<");
buttonPanel.add(buttonLeft);
buttonLeft.setPreferredSize(new Dimension(45, 25));
buttonLeft.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(leftDirection);
compassDirection.setIcon(iconCompassWest);
}
});
buttonCenter = new JButton("");
buttonPanel.add(buttonCenter);
buttonCenter.setPreferredSize(new Dimension(45, 25));
buttonCenter.setEnabled(false);
buttonRight = new JButton(">");
buttonPanel.add(buttonRight);
buttonRight.setPreferredSize(new Dimension(45, 25));
buttonRight.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(rightDirection);
compassDirection.setIcon(iconCompassEast);
}
});
buttonBL = new JButton("");
buttonPanel.add(buttonBL);
buttonBL.setPreferredSize(new Dimension(45, 25));
buttonBL.setEnabled(false);
buttonDown = new JButton("v");
buttonPanel.add(buttonDown);
buttonDown.setPreferredSize(new Dimension(45, 25));
buttonDown.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(downDirection);
compassDirection.setIcon(iconCompassSouth);
}
});
buttonBR = new JButton("");
buttonPanel.add(buttonBR);
buttonBR.setPreferredSize(new Dimension(45, 25));
buttonBR.setEnabled(false);
optionOne = new JButton("Option One");
selectionPanel.add(optionOne);
optionOne.setPreferredSize(new Dimension(125, 25));
optionOne.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(firstOption);
}
});
optionTwo = new JButton("Option Two");
selectionPanel.add(optionTwo);
optionTwo.setPreferredSize(new Dimension(125, 25));
optionTwo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(secondOption);
}
});
optionThree = new JButton("Option Three");
selectionPanel.add(optionThree);
optionThree.setPreferredSize(new Dimension(125, 25));
optionThree.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(thirdOption);
}
});
optionExit = new JButton("Exit");
selectionPanel.add(optionExit);
optionExit.setPreferredSize(new Dimension(125, 25));
scenarioAct = new JButton("Act");
scenarioAct.setIcon(iconAct);
panelAct.add(scenarioAct);
scenarioAct.addActionListener(this);
scenarioRun = new JButton("Run");
scenarioRun.setIcon(iconRun);
panelRun.add(scenarioRun);
scenarioRun.addActionListener(this);
scenarioReset = new JButton("Reset");
scenarioReset.setIcon(iconReset);
panelReset.add(scenarioReset);
scenarioReset.addActionListener(this);
JSlider speedSlider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
speedSlider.setMajorTickSpacing(10);
speedSlider.setMinorTickSpacing(5);
speedSlider.setPaintTicks(true);
speedSlider.setBackground(Color.WHITE);
speedSlider.setLabelTable(speedSlider.createStandardLabels(10));
panelSlider.add(speedSlider);
compassDirection = new JLabel();
compassPanel.add(compassDirection);
try
{
iconSand = new ImageIcon("sand.jpg");
}
catch (Exception e)
{
System.err.println("Sand Icon "+e);
}
try
{
iconBall = new ImageIcon("sand60x60.png");
}
catch (Exception e)
{
System.err.println("Ball Icon "+e);
}
try
{
iconWhite = new ImageIcon("white32x32.jpg");
}
catch (Exception e)
{
System.err.println("White Icon "+e);
}
try
{
iconEnd = new ImageIcon("sandstone.jpg");
}
catch (Exception e)
{
System.err.println("End Icon"+e);
}
for (i=0;i<208;i++)
{
game[i] = new JButton ();
if(map[i]==1)
{
game[i].setIcon(iconSand);
}
if(map[i]==2)
{
game[i].setIcon(iconBall);
}
if(map[i]==3)
{
game[i].setIcon(iconWhite);
}
if(map[i]==4)
{
game[i].setIcon(iconEnd);
}
game[i].setBorder(null);
game[i].setPreferredSize(new Dimension(32, 32));
game[i].addActionListener(this);
panelCentre.add(game[i]);
}
}
public void actionPerformed(ActionEvent arg0)
{
}
}
Try this (works for me):
After this line panelCentre.add(game[i]); enter this:
game[i].addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
System.out.println("right...");
break;
case KeyEvent.VK_LEFT:
System.out.println("left...");
break;
case KeyEvent.VK_DOWN:
System.out.println("down...");
break;
case KeyEvent.VK_UP:
System.out.println("up...");
}
}
});
This should print out the direction you typed with the arrow keys.
Here is the answer to the question
How to move the ball in the maze
https://gist.github.com/ad78d37918de6320733b
Note that you should use an own KeyEventDispatcher because otherwise you would have to attach the KeyListener to ALL components in your WHOLE GUI (see this post)
Anyway, as #chris pointed out, a ball object and another data structure than array would make your assignment easier :)

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

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

Refresh a JTable after insert data in mysql database

i´ve been trying to refresh de JTable after inserting data in MySql, but i cant manage to make it work.
The data is filled in the agregar JPanel and saved after clicking a button, checking in the mysql console, the data is added to the database, but when i open the table it doesn´t update unless i restart the program.
This is My code:
public class verTodos extends JPanel {
contactoDAO dao = new contactoDAO();
List<contacto> contactos = dao.getAll();
private JTable table;
public verTodos() {
String[] colName = { "Id", "Nombre", "Apellido", "Telefono",
"Direccion", "Email", "Rubro1", "Rubro2", "Rubro3" };
Object[][] obj = new Object[contactos.size()][10];
for (int i = 0; i < contactos.size(); i++) {
contacto c = contactos.get(i);
obj[i][0] = c.getId();
bj[i][1] = c.getNombre();
obj[i][2] = c.getApellido();
obj[i][3] = c.getTelefono();
obj[i][4] = c.getDireccion();
obj[i][5] = c.getEmail();
obj[i][6] = c.getRubro1();
obj[i][7] = c.getRubro2();
obj[i][8] = c.getRubro3();
setBounds(100, 100, 800, 300);
}
DefaultTableModel contactTableModel = new DefaultTableModel(obj,colName);
table = new JTable(contactTableModel);
setLayout(new BorderLayout(0, 0));
contactTableModel.fireTableDataChanged();
contactTableModel.setColumnIdentifiers(colName);
add(table.getTableHeader(), BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(table);
repaint();
}
}
this is the main screen that contains the JPanels:
public class principal extends JFrame {
JFrame frame = new JFrame();
JPanel container = new JPanel();
CardLayout cl = new CardLayout();
private final JMenuBar menuBar = new JMenuBar();
/.....
.....
private final JMenuItem mntmVerTodos = new JMenuItem("Ver todos");
private final JMenuItem mntmAgregar = new JMenuItem("Agregar");
agregar ag = new agregar();
verTodos ver = new verTodos();
...
...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new principal();
}
});
}
public principal() {
textField.setMaximumSize(new Dimension(300, 500));
textField.setBounds(new Rectangle(0, 0, 30, 0));
textField.setColumns(10);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int X = (screen.width / 2) - (1366 / 2);
int Y = (screen.height / 2) - (720 / 2);
frame.setBounds(X, Y, 1363, 720);
container.setLayout(cl);
ver.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
container.add(ver, "ver");
container.add(ag, "ag");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
frame.getContentPane().add(container);
frame.setJMenuBar(menuBar);
menuBar.add(mnNewMenu);
cl.show(container, "ver");
mntmVerTodos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "ver");
}
});
mnContactos.add(mntmVerTodos);
mnContactos.add(mntmAgregar);
mntmModificar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "mod");
}
});
menuBar.add(btn);
frame.setVisible(true);
}
}
You need to repopulate your model once the database has been updated. Add a refresh button that when clicked, updates contactTableModel

Java JFrame Question

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class tictac2 implements ActionListener{
static boolean blue = true; //used to keep track of turns. if true, blue's turn, else, red's turn. Blue is x, red is o
static int bWins = 0, rWins = 0;
JFrame mainWindow;
JPanel board;
JButton[] buttons;
public tictac2() {
init();
}
private void init() {
try { //Try to set the L&F to system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.toString();
System.out.println("Couln't change look and feel. Using default");
}
mainWindow = new JFrame("Tic Tac Toe!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setSize(800,600);
JMenuBar bar = new JMenuBar(); //Menu bar init
JMenu file = new JMenu("File");
JMenuItem newGame = new JMenuItem("New Game"), quitItem = new JMenuItem("Quit");
file.add(newGame);
file.addSeparator();
file.add(quitItem);
bar.add(file);
mainWindow.getContentPane().add(bar, BorderLayout.NORTH); //Menu bar done
newGameBoard(); //New Game Board
JPanel infoPane = new JPanel();
infoPane.setLayout(new GridLayout(1,3));
JLabel turn = new JLabel("Blue Player's Turn"), spacer = new JLabel(""), score = new JLabel("Blue: 0, Red: 0");
infoPane.add(turn);
infoPane.add(spacer);
infoPane.add(score);
mainWindow.getContentPane().add(infoPane,BorderLayout.SOUTH);
newGame.addActionListener(this); //Add action listeners
quitItem.addActionListener(this);
}
private void newGameBoard() {
board = new JPanel(); //Game Pane init
board.setLayout(new GridLayout(3,3));
buttons = new JButton[9];
for (int i = 0; i <9; i++){
buttons[i] = new JButton("");
buttons[i].setOpaque(true);
buttons[i].setFont(new Font("sansserif", Font.BOLD, 90));
board.add(buttons[i]);
buttons[i].addActionListener(this);
}
mainWindow.getContentPane().add(board,BorderLayout.CENTER); //Finish game pane init
}
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton j = (JButton)e.getSource();
j.setForeground(tictac2.blue ? Color.BLUE:Color.RED);
j.setText(tictac2.blue ? "X" : "O");
j.setEnabled(false);
tictac2.blue = !tictac2.blue;
}
else if (e.getSource() instanceof JMenuItem){
JMenuItem j = (JMenuItem) e.getSource();
if (j.getText().equals("Quit")) {
System.exit(0);
}
else if (j.getText().equals("New Game")) {
board.removeAll();
mainWindow.remove(board);
board = null;
for (int i = 0; i < 9; i++) {
buttons[i] = null;
}
newGameBoard();
tictac2.bWins = 0;
tictac2.rWins = 0;
tictac2.blue = true;
mainWindow.repaint(100);
}
}
}
public static void main(String[] args) {
new tictac2();
}
}
I am working on a tic tac toe program. In it I have 2 buttons. Whenever I hit new game, the newGameBoard function is supposed to run and make a new board. However, the screen just goes blank! I can't figure it out and would appreciate help. Sorry if I am not posting in the correct format, I am new here.
Thanks so much!
Move mainWindow.setVisible(true) to the end of init(). You don't want to set the frame to visible until you've added everything to it. That way it will validate and layout its subcomponents.
Another solution is to manually call mainWindow.validate() at the end of init(). That's what you have to do if you add components to the frame after making it visible.
use paintAll() or validate() on mainWindow:
mainWindow.validate();
instead of :
mainWindow.repaint(100);
validate and paintAll() as described in API doc.
Your changed code looks like:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TicTac2 implements ActionListener{
static boolean blue = true; //used to keep track of turns. if true, blue's turn, else, red's turn. Blue is x, red is o
static int bWins = 0, rWins = 0;
JFrame mainWindow;
JPanel board;
JButton[] buttons;
public TicTac2() {
init();
}
private void init() {
try { //Try to set the L&F to system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.toString();
System.out.println("Couln't change look and feel. Using default");
}
mainWindow = new JFrame("Tic Tac Toe!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setSize(800,600);
JMenuBar bar = new JMenuBar(); //Menu bar init
JMenu file = new JMenu("File");
JMenuItem newGame = new JMenuItem("New Game"), quitItem = new JMenuItem("Quit");
file.add(newGame);
file.addSeparator();
file.add(quitItem);
bar.add(file);
mainWindow.getContentPane().add(bar, BorderLayout.NORTH); //Menu bar done
newGameBoard(); //New Game Board
JPanel infoPane = new JPanel();
infoPane.setLayout(new GridLayout(1,3));
JLabel turn = new JLabel("Blue Player's Turn"), spacer = new JLabel(""), score = new JLabel("Blue: 0, Red: 0");
infoPane.add(turn);
infoPane.add(spacer);
infoPane.add(score);
mainWindow.getContentPane().add(infoPane,BorderLayout.SOUTH);
newGame.addActionListener(this); //Add action listeners
quitItem.addActionListener(this);
}
private void newGameBoard() {
board = new JPanel(); //Game Pane init
board.setLayout(new GridLayout(3,3));
buttons = new JButton[9];
for (int i = 0; i <9; i++){
buttons[i] = new JButton("");
buttons[i].setOpaque(true);
buttons[i].setFont(new Font("sansserif", Font.BOLD, 90));
board.add(buttons[i]);
buttons[i].addActionListener(this);
}
mainWindow.getContentPane().add(board,BorderLayout.CENTER); //Finish game pane init
}
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton j = (JButton)e.getSource();
j.setForeground(TicTac2.blue ? Color.BLUE:Color.RED);
j.setText(TicTac2.blue ? "X" : "O");
j.setEnabled(false);
TicTac2.blue = !TicTac2.blue;
}
else if (e.getSource() instanceof JMenuItem){
JMenuItem j = (JMenuItem) e.getSource();
if (j.getText().equals("Quit")) {
System.exit(0);
}
else if (j.getText().equals("New Game")) {
board.removeAll();
mainWindow.remove(board);
board = null;
for (int i = 0; i < 9; i++) {
buttons[i] = null;
}
newGameBoard();
TicTac2.bWins = 0;
TicTac2.rWins = 0;
TicTac2.blue = true;
mainWindow.validate();
//mainWindow.repaint();
}
}
}
public static void main(String[] args) {
new TicTac2();
}
}

Categories

Resources