How to display a JButton and give it functionality? - java

Two questions.
Firstly I'm trying to display a JButton on a JFrame, so far I've managed to display the JFrame with nothing on it.
Secondly how would one add functionality to a button? Would you pass it a method?
Any feedback is appreciated.
<code>
//imports SWING etc...
//global variables...
public class FahrenheitGUI {
public static void main(String args[]){
prepareGUI();
}
private static void prepareGUI(){
JFrame frame = new JFrame("Temp");
JPanel panel = new JPanel();
JLabel temperatureLabel;
int h = 300; int w = 300;
frame.setSize(h,w);
JButton one = new JButton( "0" );
JButton two = new JButton( "1" );
JButton three = new JButton( "2" );
JButton four = new JButton( "3" );
JButton five = new JButton( "4" );
JButton six = new JButton( "5" );
JButton seven = new JButton( "6" );
JButton eight = new JButton( "7" );
JButton nine = new JButton( "8" );
JButton ten = new JButton( "9" );
JButton negative = new JButton( "-" );
JButton dot = new JButton( "." );
JButton reset = new JButton( "reset" );
one.setBounds(10,10,20,20);
//one.addActionListener(onButtonPress);
//creates an error
frame.setVisible(true);
}
}
class Keypad implements ActionListener{
public void actionPerformed( ActionEvent one){
// guessing
}
public void actionPerformed( ActionEvent two){
// guessing
}
}

You could create JPanel, add buttons to your panel and then and the whole panel to your JFrame like this:
JPanel panel = new JPanel(); //by default it will has FlowLayout
panel.add(yourButton);
frame.add(yourJPanel);
frame.setVisible(true);
Personally I create class that extends JPanel, and inside of it I set size for panel (not for frame) and then, after adding panel to my frame I call pack() method which will resize your frame in reference of the size of your panel.
If you want to change default layout manager just call setLayout(LayoutManager)
Edit:
If you want to add functionality to your button just use:
yourButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
//button logic
}
});

call frame.add(Button) for each button. Afterwards frame.pack() once.

Related

Allignment issue with the JLabel:

I'm trying to align my JLabel at the top of the screen but it is showing at the bottom instead. It can be fixed if put some negative values in the Top-Bottom parameter in setBounds, However ! I wish to know why it's behaving like this and how it can be fixed the other way.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class T2{
private JFrame jf;
private JLabel jL;
private JButton b1, b2;
private JRadioButton jr1;
private JTextField tf1, tf2;
private Font ft;
public void run(){
//JFrame
jf = new JFrame("Program");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.setLayout(null);
jf.setBounds(0,40,500,500);
//Container
Container c = jf.getContentPane();
//Font
ft = new Font("Consolas",1,25);
//JLABEL
jL = new JLabel();
jL.setText("Enter Name:");
c.add(jL);;
//Top-Bottom Positioning isn't working here..
jL.setBounds(50, 0 , 600, 600);
jL.setFont(ft);
//JTextField
tf1 = new JTextField("Type here...");
c.add(tf1);
tf1.setBounds(200, 0 , 200, 20);
}
public static void main(String args[]){
T2 obj = new T2();
obj.run();
}
}
Here's the screenshot:
LINK
Use a layout (the default BorderLayout does what you want), add the components you want to appear at the top to the layout with the constraint "NORTH", then magically it all works.
Further comments in the code.
class T2 {
private JFrame jf;
private JLabel jL;
private JButton b1, b2;
private JRadioButton jr1;
private JTextField tf1, tf2;
private Font ft;
public void run() {
//JFrame
jf = new JFrame( "Program" );
jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// jf.setVisible( true ); // don't do this until the frame is composed
// jf.setLayout( null ); // yucky in all respects
// jf.setBounds( 0, 40, 500, 500 ); // use setSize() instead
//Container
// Container c = jf.getContentPane(); // normally you just call add()
//Font
ft = new Font( "Consolas", 1, 25 );
// Make panel first
JPanel panelNorth = new JPanel();
//JLABEL
jL = new JLabel();
jL.setText( "Enter Name:" );
jL.setFont( ft );
panelNorth.add( jL );
//Top-Bottom Positioning isn't working here..
// jL.setBounds( 50, 0, 600, 600 );
//JTextField
tf1 = new JTextField( "Type here..." );
// c.add( tf1 );
panelNorth.add( tf1 );
// tf1.setBounds( 200, 0, 200, 20 );
// now just add the panel to the "north" of the jframe border layout
jf.add( panelNorth, BorderLayout.NORTH );
// now make visible
jf.setSize( 600, 480 );
jf.setLocationRelativeTo( null );
jf.setVisible( true );
}
public static void main( String args[] ) {
// Swing is not thread safe, do on EDT
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
T2 obj = new T2();
obj.run();
}
} );
}
}

Clear current FocusOwner (jTextfield)

Developing an application in swing, just a little query :-
I want to clear the current focus owner textfield using a button. It is possible to determine whether a textfield is the current focus owner or not using isFocusOwner() but how to clear the textfield which is currently on focus?
Thanks!!!
You might be able use a TextAction. A TextAction has access to the last text component that had focus. So then in the text action you just clear the text in the component. All the logic is fully contained in the one place.
Here is an example that demonstrates the concept of using a TextAction. In this case the number represented by the button is appended to the text field with focus:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class NumpadPanel extends JPanel
{
public NumpadPanel()
{
setLayout( new BorderLayout() );
JTextField textField1 = new JTextField(4);
JTextField textField2 = new JTextField(2);
JTextField textField3 = new JTextField(2);
JPanel panel = new JPanel();
panel.add( textField1 );
panel.add( textField2 );
panel.add( textField3 );
add(panel, BorderLayout.PAGE_START);
Action numberAction = new TextAction("")
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent textComponent = getFocusedComponent();
if (textComponent != null)
textComponent.replaceSelection(e.getActionCommand());
}
};
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setMargin( new Insets(20, 20, 20, 20) );
button.setFocusable( false );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Numpad Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new NumpadPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
In your case instead of using the replaceSelection() method you would just use the setText() method.
If you want to clear a textfield using the clicking of a button, you have to write the code to clear the textfield in the the ActionListener class's ActionPerformed method. This method is called when the button is pressed. But in order to press the button you have to get the focus from other component to this button. So in the method ActionPerformed you would get false to textField.isFocusOwner().
My suggestion to overcome this problem is:
add focus listeners to these 6 text fields.
declare a variable say lastFocused as type JTextField in initialise it to null in the Class that you are implementing all these.
write the following code to the focusListerners Overridden methods
void focusGained(FocusEvent e){
lastFocused = (JTextField) e.getComponent();
}
void focusLost(FocusEvent e){
lastFocused = null;
}
now in the ActionListener overridden method write the following:
void actionPerformed(ActionEvent e){
if(lastFocused != null){
lastFocused.setText("");
}
}
I feel this should solve your problem.

How to keep Focus on JTextField while clicking input number buttons?

I am new to GUI stuff and am having trouble with the following problem. I have 3 JTextFields, credit card number, expiration date, and security number. I am able to input information into the fields. I also implemented the focus listener for each button. If I click it, it says gained focus, if I click anywhere else, it loses focus. Under these text fields, I have a number pad (touch screen/mouse click) to enter the numbers. How do I keep focus on that particular text field until ONLY and SPECIFICALLY one of the other two textfields are clicked? The textfield that currently has focus will lose focus once I try to click to input numbers. I don't want this to happen. I searched online and wasn't able to find something specific to my case. Any help or tips would be appreciated.
myJButton.setFocusable(false);
or if a bunch of buttons held in an allMyButtons collection:
for (JButton button: allMyButtons) {
button.setFocusable(false);
}
That's it.
In additions to #Hovercrafts suggestion (+1) you will probably want to extend TextAction for the logic to insert the number into the text field. The TextAction gives you access to the last text field that had focus so the insertion code becomes very generic:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class NumpadPanel extends JPanel
{
public NumpadPanel()
{
setLayout( new BorderLayout() );
JTextField textField1 = new JTextField(4);
JTextField textField2 = new JTextField(2);
JTextField textField3 = new JTextField(2);
JPanel panel = new JPanel();
panel.add( textField1 );
panel.add( textField2 );
panel.add( textField3 );
add(panel, BorderLayout.PAGE_START);
Action numberAction = new TextAction("")
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent textComponent = getFocusedComponent();
if (textComponent != null)
textComponent.replaceSelection(e.getActionCommand());
}
};
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setMargin( new Insets(20, 20, 20, 20) );
button.setFocusable( false );
buttonPanel.add( button );
}
// Optionally auto tab when text field is full
//SizeDocumentFilter sf = new SizeDocumentFilter();
//sf.installFilter(textField1, textField2, textField3);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Numpad Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new NumpadPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You might also want to consider using Text Field Auto Tab so focus moves from text field to text field as the text field becomes full.

Regarding how to add an something from a text field into a JList

I have a program that needs to take user input (from an input box) and add it to a JList. When I click the Add button on my program however, errors occur.
Heres the code I hoped would work
JButton addButton = new JButton( "<-Add" );
addButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
final String name=inputField.getText();
// prompt user for new philosopher's name
// add new philosopher to model
philosophers.addElement( name );
}
}
);
Edit: Heres all of the code although ive tested this part and i'm confident it works (Except for the listner I tried to add to the text box)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PhilosophersJList extends JFrame {
private DefaultListModel philosophers;
private JList list;
private JTextField inputField;
public PhilosophersJList()
{
super( "Favorite Philosophers" );
// create a DefaultListModel to store philosophers
philosophers = new DefaultListModel();
philosophers.addElement( "Socrates" );
philosophers.addElement( "Plato" );
philosophers.addElement( "Aristotle" );
philosophers.addElement( "St. Thomas Aquinas" );
philosophers.addElement( "Soren Kierkegaard" );
philosophers.addElement( "Immanuel Kant" );
philosophers.addElement( "Friedrich Nietzsche" );
philosophers.addElement( "Hannah Arendt" );
// create a JList for philosophers DefaultListModel
list = new JList( philosophers );
JButton addButton = new JButton( "<-Add" );
addButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
final String name=inputField.getText();
// prompt user for new philosopher's name
// add new philosopher to model
philosophers.addElement( name );
}
}
);
// create JButton for removing selected philosopher
JButton removeButton =
new JButton( "Rem->" );
removeButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
// remove selected philosopher from model
setTitle("Now Removing Contact");
try
{
Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)
}
catch(InterruptedException e)
{
e.printStackTrace();
}
philosophers.removeElement(list.getSelectedValue());
setTitle("My Contacts List");
}
}
);
JTextField inputField=new JTextField();
inputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
// allow user to select only one philosopher at a time
list.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION );
//Create the text field
// create JButton for adding philosophers
// lay out GUI components
JPanel inputPanel = new JPanel();
inputPanel.add( addButton);
inputPanel.add( removeButton);
inputPanel.setLayout(new BoxLayout(inputPanel,BoxLayout.Y_AXIS));
inputField.setLayout(new FlowLayout());
inputField.setBounds(5, 5, 100, 100);
inputField.setPreferredSize(new Dimension(120,20));
JScrollPane scrollPane=new JScrollPane(list);
scrollPane.setPreferredSize(new Dimension(200,200));
Container container = getContentPane();
add(scrollPane);
container.add( inputPanel);
add( inputField);
container.setLayout(new FlowLayout());
setDefaultCloseOperation( EXIT_ON_CLOSE );
setSize( 500, 250 );
setVisible( true );
} // end PhilosophersJList constructor
// execute application
public static void main( String args[] )
{
new PhilosophersJList();
}
}
You don't initialize the inputField field. The problem is on line 69, where you declare a new local variable named inputField, instead of assigning the field. You need to actually refer to the inputField field.
So instead of
JTextField inputField = new JTextField();
you should write just
inputField = new JTextField();

JButton expanding to take up entire frame/container

Hey everyone. I'm trying to make a swing GUI with a button and a label on it. im using a border layout and the label ( in the north field ) shows up fine, but the button takes up the rest of the frame (it's in the center field). any idea how to fix this?
You have to add the button to another panel, and then add that panel to the frame.
It turns out the BorderLayout expands what ever component is in the middle
Your code should look like this now:
Before
public static void main( String [] args ) {
JLabel label = new JLabel("Some info");
JButton button = new JButton("Ok");
JFrame frame = ...
frame.add( label, BorderLayout.NORTH );
frame.add( button , BorderLayout.CENTER );
....
}
Change it to something like this:
public static void main( String [] args ) {
JLabel label = new JLabel("Some info");
JButton button = new JButton("Ok");
JPanel panel = new JPanel();
panel.add( button );
JFrame frame = ...
frame.add( label, BorderLayout.NORTH );
frame.add( panel , BorderLayout.CENTER);
....
}
Before/After
Before http://img372.imageshack.us/img372/2860/beforedl1.png
After http://img508.imageshack.us/img508/341/aftergq7.png
Or just use Absolute layout. It's on the Layouts Pallet.
Or enable it with :
frame = new JFrame();
... //your code here
// to set absolute layout.
frame.getContentPane().setLayout(null);
This way, you can freely place the control anywhere you like.
Again :)
import javax.swing.*;
public class TestFrame extends JFrame {
public TestFrame() {
JLabel label = new JLabel("Some info");
JButton button = new JButton("Ok");
Box b = new Box(BoxLayout.Y_AXIS);
b.add(label);
b.add(button);
getContentPane().add(b);
}
public static void main(String[] args) {
JFrame f = new TestFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Categories

Resources