How to make buttons in java

How to make a button in java

The class implements a (extends a ) to respond to mouse clicks on the Go board. Or if you use a JButton then you need code like: Solution 2: I assume that the problem is how the button looks grayed out, because really is the way you disable a button — which just means making it not clickable (or did you want it to respond to keyboard input?).

How to make a Button program? (Java)

As each game class is having its own main method you can simply can the respective main method of the game you want to start.

As main method is static no need for any initialization, simply —

Java — Make a button round, JDC Tech Tips: August 26, 1999: Creating Round Swing Buttons. import java.awt.*; import java.awt.geom.*; import javax.swing.*; public class RoundButton extends JButton < public RoundButton (String label) < super (label); // These statements enlarge the button so that it // becomes a circle rather than an oval.

How to make a JButton not clickable in java?

Because in my application I have a grid of JButtons that are used as icons

Then don’t use buttons, use a JLabel which also supports an Icon.

Читайте также:  Операторы управления ходом программы java

Or maybe use a JList which can also support a grid.

Or if you use a JButton then you need code like:

JButton button = new JButton(. ); button.setBorderPainted( false ); button.setFocusPainted( false ); 

I assume that the problem is how the button looks grayed out, because setEnabled really is the way you disable a button — which just means making it not clickable (or did you want it to respond to keyboard input?). If that’s the case, then you can change the way it looks by using html:

Java — How to make a button unclickable, How do i make it so that it know when to grey out the button or make it unclickable when the user gets to the last screen. Here is my code: public class ReadingActivity extends Activity implements OnClickListener < private ViewFlipper viewFlipper; Button btnNext, btnPrev; private float lastX; /** Called when the …

How to make a grid of buttons

Use a JPanel with a 9×9 GridLayout and ad to it JButtons configured to your need as demonstrated in the following very basic mre:

import java.awt.*; import java.awt.image.*; import javax.swing.*; public class GridOfButtons extends JPanel < private static final int ROWS = 9, COLS = 9, SIZE = 65, BORDER = 2; private static final Color BOARD_COLOR = Color.BLACK; public GridOfButtons() < setLayout(new GridLayout(ROWS, COLS, BORDER, BORDER)); setBackground(BOARD_COLOR); StonesFactory factory = new StonesFactory(SIZE); boolean isBlack = false; for (int col = 0; col < COLS; col++) < for (int row = 0; row < ROWS; row++) < add(factory.makeButton(isBlack)); isBlack = !isBlack; >> this.initBoard(); > public void initBoard() < JFrame f = new JFrame("Board Of Buttons"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(new GridBagLayout()); f.add(this); f.pack(); f.setVisible(true); >public static void main(String[] args) < SwingUtilities.invokeLater(()->new GridOfButtons()); > > class StonesFactory < private static final Color STONE = Color.YELLOW, WHITE_STONE = Color.WHITE, BLACK_STONE = Color.BLACK; private final int size; private final ImageIcon whiteIcon, blackIcon; public StonesFactory(int size) < this.size = size; whiteIcon = new ImageIcon(createImage(false)); blackIcon = new ImageIcon(createImage(true)); >JButton makeButton(boolean isBlack) < JButton stone = new JButton(); stone.setPreferredSize(new Dimension(size, size)); stone.setBackground(STONE); stone.setIcon(isBlack ? blackIcon : whiteIcon); return stone; >//construct image for button's icon private BufferedImage createImage(boolean isBlack) < BufferedImage img = new BufferedImage(size , size, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = img.createGraphics(); g2.setColor(isBlack ? BLACK_STONE : WHITE_STONE); g2.fillOval(0,0,size,size); g2.dispose(); return img; >> 

Alternatively you can produce the board by custom painting of a JPanel . This will make the individual «stones» not clickable and more difficult to modify:

import java.awt.*; import javax.swing.*; public class GridByPainting extends JPanel < private static final int ROWS = 9, COLS = 9, SIZE = 65, BORDER = 2; private static final Color BOARD_COLOR = Color.BLACK, STONE = Color.YELLOW, WHITE_STONE = Color.WHITE, BLACK_STONE = Color.BLACK; private final Dimension size; public GridByPainting() < int x = BORDER + COLS*(SIZE + BORDER); int y = BORDER + ROWS*(SIZE + BORDER); size = new Dimension(x,y); this.initBoard(); >@Override public Dimension getPreferredSize() < return size; >public void initBoard() < JFrame f = new JFrame("Grid By Painting"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(new GridBagLayout()); f.add(this); f.pack(); f.setVisible(true); >@Override public void paintComponent(Graphics g) < super.paintComponent(g); int width = getWidth(); int height = getHeight(); int stoneWidth = (width - BORDER) / COLS - BORDER; int stoneHeight = (height -BORDER)/ ROWS - BORDER ; //draw board g.setColor(BOARD_COLOR); g.fillRect(0, 0, width, height); boolean isBlack = true; //draw square stones for (int col = 0; col < COLS; col++) < for (int row = 0; row < ROWS; row++) < int x = BORDER + col*(stoneWidth + BORDER); int y = BORDER + row*(stoneHeight + BORDER); g.setColor(STONE); g.fillRect(x, y, stoneWidth, stoneHeight); //draw circle g.setColor(isBlack ? BLACK_STONE : WHITE_STONE); isBlack = !isBlack; g.fillOval(x, y, stoneWidth, stoneHeight); >> > public static void main(String[] args) < SwingUtilities.invokeLater(()->new GridByPainting()); > > 

It seems like you skipped over some of the important parts of the Oracle tutorial, Creating a GUI With Swing.

Here’s my comment from August 23rd, just 10 days ago.

Generally, you create a logical model of a Go board using a plain Java getter / setter class. You use a drawing JPanel to create the Go board in the GUI and draw circles to represent the stones. The Oracle tutorial, Creating a GUI With Swing, will show you the steps to creating a Swing GUI. Skip the Netbeans section.

So, where’s your logical model? Where’s your drawing JPanel ?

Here’s a quick GUI I created.

Go Board

My code has a logical model. My code has a drawing JPanel .

The first thing I did was create a plain Java getter / setter class to hold a logical representation of a Go Board. I named this the Board class.

The next thing I did was start my Swing GUI with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.

I used the run method of my Runnable class to create the JFrame . The JFrame methods must be called in a specific order. This is the order I use for all my Swing applications.

I separate the creation of the JFrame from the creation of any subsequent JPanels . I do this to keep my code organized, easy to read, and easy to understand.

I extend a JPanel to create the drawing JPanel . I do this so I can override the paintComponent method of the JPanel class. The drawing JPanel draws (paints) the board state. That’s all. Nothing else. Another class will take care of adding pieces to the logical Go board and repainting the drawing JPanel.

The MoveListener class implements a MouseListener (extends a MouseAdapter ) to respond to mouse clicks on the Go board. The MoveListener class keeps track of whose turn it is. In a more elaborate version of a Go board, you would have another plain Java getter / setter class to keep track of the game state.

Here’s the complete runnable code. I made all the classes inner classes so I could post this code as one block.

import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class GoBoard implements Runnable < public static void main(String[] args) < SwingUtilities.invokeLater(new GoBoard()); >private Board board; private DrawingPanel drawingPanel; public GoBoard() < this.board = new Board(); >@Override public void run() < JFrame frame = new JFrame("Go Board"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.drawingPanel = new DrawingPanel(board); frame.add(drawingPanel, BorderLayout.CENTER); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); >public class DrawingPanel extends JPanel < private static final long serialVersionUID = 1L; private final int margin, pieceRadius, lineSpacing; private Board board; public DrawingPanel(Board board) < this.board = board; this.margin = 60; this.pieceRadius = 40; this.lineSpacing = 100; this.setBackground(new Color(0x993300)); int width = 8 * lineSpacing + margin + margin; this.setPreferredSize(new Dimension(width, width)); this.addMouseListener(new MoveListener(board)); >@Override protected void paintComponent(Graphics g) < super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; paintHorizontalLines(g2d); paintVerticalLines(g2d); paintPieces(g2d); >private void paintHorizontalLines(Graphics2D g2d) < int x = margin; int y1 = margin; int y2 = getHeight() - margin; g2d.setColor(Color.YELLOW); g2d.setStroke(new BasicStroke(3f)); for (int index = 0; index < 9; index++) < g2d.drawLine(x, y1, x, y2); x += lineSpacing; >> private void paintVerticalLines(Graphics2D g2d) < int x1 = margin; int x2 = getWidth() - margin; int y = margin; g2d.setColor(Color.YELLOW); g2d.setStroke(new BasicStroke(3f)); for (int index = 0; index < 9; index++) < g2d.drawLine(x1, y, x2, y); y += lineSpacing; >> private void paintPieces(Graphics2D g2d) < int[][] b = board.getBoard(); for (int row = 0; row < b.length; row++) < for (int column = 0; column < b[row].length; column++) < int x = column * lineSpacing + margin; int y = row * lineSpacing + margin; if (b[row][column] == 1) < g2d.setColor(Color.BLACK); g2d.fillOval(x - pieceRadius, y - pieceRadius, pieceRadius + pieceRadius, pieceRadius + pieceRadius); >else if (b[row][column] == 2) < g2d.setColor(Color.WHITE); g2d.fillOval(x - pieceRadius, y - pieceRadius, pieceRadius + pieceRadius, pieceRadius + pieceRadius); >> > > > public class MoveListener extends MouseAdapter < private boolean isBlackTurn = true; private Board board; public MoveListener(Board board) < this.board = board; >@Override public void mouseReleased(MouseEvent event) < Point point = event.getPoint(); int margin = 60; int pieceRadius = 40; int lineSpacing = 100; int column = (point.x - margin + pieceRadius) / lineSpacing; int row = (point.y - margin + pieceRadius) / lineSpacing; int piece = (isBlackTurn) ? 1 : 2; board.setPiece(piece, row, column); drawingPanel.repaint(); isBlackTurn = !isBlackTurn; >> public class Board < private int[][] board; public Board() < this.board = new int[9][9]; >/** * 

* This method inserts a piece on the board. *

* * @param piece - 1 for black, 2 for white * @param row - row of piece * @param column - column of piece */ public void setPiece(int piece, int row, int column) < this.board[row][column] = piece; >public int[][] getBoard() < return board; >> >

Swing — Java: using an image as a button, Java: using an image as a button. I would like to use an image as a button in Java, and I tried to do this: BufferedImage buttonIcon = ImageIO.read (new File («buttonIconPath»)); button = new JButton (new ImageIcon (buttonIcon)); But this still shows the actual button behind the image, I would only like the …

Источник

JButton basic tutorial and examples

In this Java Swing tutorial, you will learn how to use button that allows the user to perform action in a desktop application.

You know, JButton is a fundamental Swing component that renders a button on screen and responds to user’s clicking event for performing a specific task. This article summarizes common programming practices for using JButton in Swing.

Table of content:

1. Creating a JButton object

JButton button = new JButton("Edit");

Image:
Create a button with only an icon in the file system:

JButton button = new JButton(new ImageIcon("images/start.gif"));

Here the icon file start.gif is placed under images directory which is relative to the program.
Image:
Create a button with only icon inside a jar file or in classpath:

String iconPath = "/net/codejava/swing/jbutton/stop.jpg"; Icon icon = new ImageIcon(getClass().getResource(iconPath)); JButton button = new JButton(icon);

Here the icon file stop.jpg is placed under a specific package in the classpath.
Image:
Create a button with a caption and an icon:

JButton button = new JButton("Start", new ImageIcon("images/start.gif"));

Image:

2. Adding the button to a container

frame.add(button); dialog.add(button); panel.add(button); applet.getContentPane().add(button);
frame.add(button, BorderLayout.CENTER); panel.add(button, gridbagConstraints);

3. Adding event listener for JButton

button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent evt) < // do everything here. >>);
button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent evt) < // delegate to event handler method buttonActionPerformed(evt); >>);
private void buttonActionPerformed(ActionEvent evt) < // do something here. >
public class App extends JFrame implements ActionListener < public App() < // creates the button. // adds event listener: button.addActionListener(this); >@Override public void actionPerformed(ActionEvent evt) < // do something here. >>

Here the container ( JFrame ) must implement the ActionListener interface and override the method actionPerformed() .

4. Setting mnemonic and hotkey for JButton

button.setMnemonic(KeyEvent.VK_E);

The letter E is underlined: so user can invoke that button’s action by pressing Alt + Einstead of clicking mouse.

  • Set F2 as the hot key to invoke the button’s action:
  • String mapKey = "KEY_F2"; InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke("F2"), mapKey); button.getActionMap().put(mapKey, new AbstractAction() < public void actionPerformed(ActionEvent evt) < buttonActionPerformed(evt); >>);

    5. Setting a JButton as the default button

    A window can have a default button whose action will be invoked when the user hits Enter key. Here is the code to set the button as default button in the frame window:

    getRootPane().setDefaultButton(button);

    The default button is bold in the window like the 3 rd button in this screenshot:

    button set as default6. Customizing JButton’s appearance

    button.setFont(new java.awt.Font("Arial", Font.BOLD, 14)); button.setBackground(Color.YELLOW); button.setForeground(Color.BLUE);

    Image:

  • Change font style using HTML code:
  • 7. JButton demo program

    For reference, we created a demo program which incorporates all the practices mentioned above. The program looks like this:

    JButton demo program

    You can download source code of this program in the attachment section.

    Other Java Swing Tutorials:

    About the Author:

    Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

    Add comment

    Comments

    merci
    I want to add to the button text using a variable. how do I get this to work? jpFormatPanel.add(new JButton(«Format Citation: «
    + strTemplateName

    I want to add to the button text using a variable. how do I get this to work? jpFormatPanel.add(new JButton(«Format Citation: »
    + strTemplateName
    + » — »
    + strTemplateCode),
    BorderLayout.NORTH);

    CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
    CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.

    Copyright © 2012 — 2023 CodeJava.net, all rights reserved.

    Источник

    Оцените статью