Creating a Button in Java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I am fairly new to programming as I am only in a Computer Science class in high school. I have thought of the idea of creating a chess program that basically simulates a game of chess. To do this I figured I would have the users click on the spot that they would want to move to.
I have looked all over the internet, including java's API's, and I have found some very useful information. After all of this however, I am still very confused about all of the different methods and classes as well as interfaces to use to create and use Buttons in Java. Although this isn't a question about code(Sorry), I was wondering if anybody knew of any tutorials that would be suitable for my situation. All I am looking for is something that can show me how to create and use a simple, one function button. Preferably, it would be nice if it describes all of the methods so that I actually understand what I am doing.
Again, sorry this isnt a question about code. I couldn't think of a better place to ask this question, than Stack Overflow so please do not down-vote this "question".
Thanks

Here is a totally self contained example (with some code comments to help you understand what is going on):
//Here I am using Swing and AWT (a rather standard way to manage UI elements in Java though technically not the only way)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
//Here is a base class that extends JFrame, JFrames are containers for Swing UI widgets that are represented as windows when executed
public class ButtonExample extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
//Creatign the frame
ButtonExample frame = new ButtonExample();
//Creating the button with the label "Click me!"
JButton button = new JButton("Click me!");
//Adding an action listener so we can assign some logic to be executed when this button is clicked on (this is using an anonymous inner class in future versions of Java this will be replaced by the MUCH cleaner Lamba approach, keep an eye out for that)
button.addActionListener(new ActionListener() {
//Keep a variable to store how many times the button is clicked. This shows that the action listener stays running in between clicks)
private int count = 0;
//While technically optional thew #Override annotation helps if you update interfaces, get into the habit of doing this to make future work easier, things like Eclipse will insert it for you
#Override
public void actionPerformed(ActionEvent e) {
//Bump up the count variable
this.count++;
//And print it to System.out
System.out.println("Pressed "+this.count + " times");
}
});
//Add the button (with it's listener) to the frame
frame.add(button);
//Tell Swing to resize the frame to fit the requested size of all of it's contained widgets
frame.pack();
//Tell Swing to show the frame
frame.setVisible(true);
}
}

Try:
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Do what you like here after button is clicked, for example:
System.out.println("Button clicked");
}
});
someJPanel.add(button);
To make such application - you will need lot's of knowledge. Also it should look nice, so lot's of work with graphics in Java..

Try to read this documentation: Here You Are
There, you can download, launch the example, so you can see, try every button..

Related

How to create a custom JButton class in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm afraid I don't have any code because I don't really know what I'm doing. I'm trying to learn some Java by creating a basic game and want to make a menu. What I want to do is have a class with a custom JButton (basically a JButton of a certain size and a picture on the background, formatted specially, etc.) which can be called from another class and given custom text when it is called. My question is, how do I create the custom button which can be called externally?
create a class and extend it to JButton like below and there you can change all sort of things that has to do with JButton.
import javax.swing.JButton;
public class CustomJButton extends JButton {
public CustomJButton() {
this.setText("Custom JButton");
// initialize
}
// add your own methods or override JButton methods
public void myFunc(){
}
}
In the constructor for your custom JButton, you'll want to accept a parameter that specifies the text you want the button to contain, and you'll specify the other things that you don't want to change from instance to instance, such as the size or the background image.
import javax.swing.*;
class MyButton extends JButton{
public MyButton(String text){
super(text);
...set size, add background image, etc...
}
}
No this button is a JButton you can create a new one
like normally, MyButton btn = new MyButton(); You just added an extra method that will format it the way you want. If you want to learn more about this topic look at object inheritance.
public MyButton extends JButton{
public void doStuff(){
this.setBackground("yourBackground");
...
}
}

Making a multi-tiered program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on an assignment in which I need to combine two programs that I have created into one functioning program. The end result I am hoping for is a program that once launched, opens a log in window, then once logged in, the user gets to play a tic tac toe game. Basically I just was wonder how to have a window within which when you click a button, a new window opens that can run extensive code.
If you're using Swing framework, Create a second JFrame and set its visibility to false, and when the button is clicked, set it visibility to true.
public class MyFrame extends JFrame {
private JButton jbt = new JButton("Open Window");
private AnotherFrame jfrm = new AnotherFrame();
public MyFrame(){
add(jbt);
jfrm.setVisibility(false);
add(jfrm);
jbt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
jfrm.setVisibility(true);
}
});
}
private AnotherFrame extends JFrame {
public AnotherFrame(){
}
}
}

How to add title in Netbeans (java)? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Just can't figure this out in my GUI, I know it's probably simple but thought I'd ask.
I assume I need something in this code:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new myGUI().setVisible(true);
}
});
}
Thanks.
Edit - for some reason public static etc. isn't showing up above - but you probably don't need that.
You're not showing us the whole code, so this is only a guess, but probably a good one: I assume that myGUI is a subclass of JFrame, and you want to call setTitle() on it. Something like
myGUI m = new myGUI();
m.setTitle("The Title");
m.setVisible(true);
You'd put these three lines in place of the one new myGUI().setVisible(true); .
If you are in Netbeans do you have a screen/form in which you have been designing your Frame?
If so open the navigator toolbar and right click on your frame, select properties and look for the one called title, and type in your text there.
Otherwise you will need to add something like
myGui.setTitle("A title") // assuming its a JFrame

Java/Swing GUI best practices (from a code standpoint) [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
As a contrast to this wiki, I am looking for the proper way to implement Swing GUI controls from a coding standpoint.
I have been on a quest to learn Java and its GUI tools but I find internet tutorial after internet tutorial that throws everything in main and I know this isn't right.
I've also tried RAD systems like Netbeans and other "visual" editors but by the time I get to coding I've got a heap of code that I don't know half of what it does, so I'm intent on learning to hand code swing, and I know the basic controls and layout, but want to do it the right way.
Is there a model or standard I'm missing?
example questions...
do I extend JFrame and create my own frame object? (I would assume yes)
do I encapsulate the main menu inside that frame object? or do I create its own? etc...
How to I separate "View" logic from "Application" logic?
Basically, I'm looking for what the industry standard is, on how to organize GUI code.
Since there seems to be some argument about what constitutes "best practices", I'll give you what I have found works best for me, and my reasoning:
1.
Each window should extend either JFrame or JDialog (depending on the type of window). This makes it easy to control the properties of the window without specifying a specific object every time. This is more of the general case, though, as I have been known to do it both ways.
2.
The main() method should be in a separate class. This increases the likelihood of being able to use your window classes elsewhere, as they are not tied to specific implementations. Technically it doesn't make a difference, but application startup code just doesn't belong in a window.
3.
Listeners should be in anonymous inner classes. Your top-level class should not implement any listeners. This prevents hacks like calling the listener methods from anywhere except the object to which they are attached.
Here is a simple application with a single frame to demonstrate these practices:
public class Main {
public static void main(String[] args) {
final String text = args[0];
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final MyWindow wnd = new MyWindow(text);
wnd.setVisible(true);
}
});
}
}
public class MyWindow extends JFrame {
public MyWindow(String text) {
super("My Window");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
MyWindow.this.setVisible(false);
MyWindow.this.dispose();
}
});
final JButton btn = new JButton(text);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(MyWindow.this, "Button Pressed", "Hey", JOptionPane.INFORMATION_MESSAGE);
}
});
setLayout(new FlowLayout());
add(btn);
pack();
}
}
I agree with all of Jonathan's points.
Each window should extend either JFrame or JDialog...
The main() method should be in a separate class...
Listeners should be in anonymous inner classes...
I would also like to add the following:
Use GridBagLayout (GBL) judiciously. GBL is a powerful Layout Manager, difficult to learn, but quite powerful.
Consider hand coding all your UI. I'm personally not a fan of the code that is produced by visual editors. But, with that said I have not used a visual editor in several years (2000ish). They might be better at this point.
Use JPanels judiciously. Look at your ui and determine which components should behave the same as the screen size changes and then group those components together on a JPanel. Consider using JPanels inside of JPanels to get your correct resizing behavior.
I normally take a slightly different approach on having my components handle events then Jonathan does, but I believe his approach is a bit cleaner then mine.
Also, really study the use of MVC and Layered Architecture. It is truly best not to be mixing UI and Business Logic together.

Are there any good tools for finding usage statistics of GUI, broken down panes and components? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Collecting usage statistics per web-page on sites is common practice, I'm interested in a similar thing, but for GUI:s. You see Google Chrome (and others) collect usage statistics so Google can find out what features people use, to data-mine what seems to "work".
A straight-forward way to do this is to explicitly log the interaction with every GUI element, but that is both tedious and prone to mistakes in missing parts of the GUI.
So what I wonder, is this a solved problem? Is there anything existing that can provide a summary similar to code-profiling, metrics (number of visits, clicks, etc) broken down on per component? Automatically added to all components in the whole tree of AWT/Swing components?
This information would need to be summarized to a file so it can be sent to "us" for aggregation and data mining, to drive decisions etc.
I don't really know exactly what I want, so I am also asking to find out good ideas and what other people have done that have faced this problem.
Whilst this isn't a complete solution, it might help guide you closer to something workable. I agree with the previous poster, that it is possible to add hooks into your code, this becomes unmanageable on a large project. Also if you miss a part of the application and come to examine the data, you'll have a blank space each time the user uses that component.
Instead you can listen directly to AWTEvents which are generated by every component in the UI. This could easily be the source information for your data mining. The following code shows you how this is done:
package awteventlistenerexample;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
private static final String ACTION_CLOSE = "Close";
private JFrame frame;
public Test() {
frame = new JFrame();
initActions();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.getRootPane().getActionMap().get(ACTION_CLOSE).actionPerformed(null);
}
});
JPanel content = new JPanel(new FlowLayout());
content.add(new JLabel("Creature"));
JButton badger = new JButton("Badger");
badger.setName("badger");
JButton ferret = new JButton("Ferret");
ferret.setName("ferret");
JButton stoat = new JButton("Stoat");
stoat.setName("stoat");
content.add(badger);
content.add(ferret);
content.add(stoat);
frame.add(content, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton close = new JButton(frame.getRootPane().getActionMap().get(ACTION_CLOSE));
buttonPanel.add(close);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(200, 150);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void initActions() {
Action close = new AbstractAction("Close") {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
};
frame.getRootPane().getActionMap().put(ACTION_CLOSE, close);
}
public static void main(String args[]) {
// Attach listener to AWTEvents (Mouse Events)
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent event) {
if (event instanceof MouseEvent) {
MouseEvent m = (MouseEvent) event;
if (m.getID() == MouseEvent.MOUSE_CLICKED) {
System.out.println(m.toString());
}
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
EventQueue.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
}
In this case I have listened to Mouse Events. These seem to be the most useful as they can tell you what the user clicked on. From here, you'll need to work out what you need to collect in order to build up a picture of what the user clicked on. I would also be interested in what the user didn't click on as well.
There is lots of work surrounding automated UI testing which uses this technique. Abbot and FEST are examples I have used. You might want to look at how they process AWTEvents in case there is anything helpful there.
Well, you would first expect to receive the usage statistics somehow. So are you going to have your app connect to a database? Are you going to have another app that process the usage statistics? In short, I would create a function like this
void LogUsage(this object id or handle name/caption text etc)
and let that function handle all the processing of handling statistical usage. Of course you will need to do /some/ kind of work such as add this function to onClicks, edits changes etc, but that should be fairly simple. Especially if your LogUsage function just takes something unique (like the name) and uses that for the statistics.
The LogUsage function can also then manage connecting remotely and clearing any cache it may have stored since its last transmit.
Simply stated, if you created a LogUsage function that accepts the object, and you always grab the name. You could just easily copy/paste this line throughout your program
LogUsage(this);
Edit-
I also noticed you are looking for suggestions: I would do what I said above; a simple LogUsage function that accepts a param such as the object, and grab the name, eg - btnLogin, and then processes that name into some kind of file. You would obviously first load this file into some kind of map or array, check to see if it exists first. If not it adds it to the list with 1 click (or usage). If it exists, it increments its usage point. You will obviously not want to call LogUsage on the OnChange method in a textbox etc, but probably all onFocus, Clicks, or whatever you are really wanting to keep track of.
In the end, you might end up with something like btnLogin (5) that is sent to you, indicating that the user clicked on btnLogin 5 times.
Handling all this received data is another endeavor, which is why I would definitely have it sent to a database rather than receiving, say an email or a server directory full of files of usage statistics. Either way, you will need something to process it and turn it into graphs or sortable usage statistics etc..
Netbeans and Eclipse both have mechanisms for collecting UI statistics but I have no idea how easy it is to use these outwith applications based on their platforms.
Well, as far as I know, I've never seen any kind of usage statistics automatic gathering for Swing applications.
To my mind, the easiest way to implement such a feature would be to use look'n'feel : this way, each component will transparently be associated to the best fitting loggers (a JCheckBox will be listened for checks, while a JSCrollBar would have its scroll logged).
You may think about asking Kirill Grouchnikov about that feature, but I fear even Substance does not implement it.

Categories