JTextField text won't print - java

as you see I have made a very simple program where I input text on a textfield, then press the button to print it on the console:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Main {
private static class Window extends JFrame {
private static class TextField extends JTextField {
private TextField() {
setVisible(true);
setBounds(5, 0, 190,20);
}
}
public class Button extends JButton implements ActionListener {
private Button() {
setText("print");
addActionListener(this);
setVisible(true);
setBounds(5, 35, 190,20);
}
public void actionPerformed(ActionEvent e) {
TextField textField = new TextField();
String input = textField.getText();
System.out.println(input);
}
}
However, while I click the button, it adds blank lines to the console, without the text I have written in it.

Your actionPerformed method creates a new TextField instance and prints the text from that new instance.
A very simple example that works as intended:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TextAndButtonExample {
public static void main( String[] args ) {
EventQueue.invokeLater(() -> new TextAndButtonExample().start());
}
void start() {
JTextField textField = new JTextField();
JButton button = new JButton(new AbstractAction("Print") {
public void actionPerformed( ActionEvent e ) {
System.out.println(textField.getText());
}
});
JPanel controlPane = new JPanel(new GridLayout(2, 1));
controlPane.add(textField);
controlPane.add(button);
JPanel contentPane = new JPanel();
contentPane.add(controlPane);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Note that I did not extend any Swing components and that I did use a layout manager instead of explicitly setting bounds for components.

Related

JTextArea and JButton. Set the focus on the button [duplicate]

This question already has answers here:
Java GUI: How to Set Focus on JButton in JPanel on JFrame?
(5 answers)
Closed 4 years ago.
The following program shows a JTextArea and a "Close" JButton. I defined the button as the default button because I would like it to have the focus as soon as I open the window. However, when I run the program the button is highlighted but the focus is on the text field.
How do I set the focus on the button and not the text area?
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
public class Test {
static JPanel southPanel;
static JButton closeButton;
static JFrame frame;
static JTextArea textArea;
private static final Dimension REASON_AREA_SIZE = new Dimension(250, 50);
public static void main(String args[]) {
String title = "";
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setSize(1000, 800);
textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(true);
JScrollPane lScrollPane = new JScrollPane(textArea);
lScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
lScrollPane.setPreferredSize(REASON_AREA_SIZE);
frame.add(lScrollPane, BorderLayout.CENTER);
frame.add(createSouthPanel(), BorderLayout.SOUTH);
//Here the close button is defined by default, the focus should be on it
setDefaultButton();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(title);
frame.setVisible(true);
}
private static JPanel createSouthPanel() {
southPanel = new JPanel(
new FlowLayout(FlowLayout.RIGHT, 10, 10));
southPanel.setBorder(new EtchedBorder(EtchedBorder.RAISED));
addCloseButton(southPanel);
return southPanel;
}
/**
* Set the close button as default
*/
protected static void setDefaultButton() {
frame.getRootPane().setDefaultButton(closeButton);
}
private static void addCloseButton(JPanel pButtonsPanel) {
closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent pEvent) {
frame.dispose();
}
});
pButtonsPanel.add(closeButton);
}
}
Inside your setDefaultButton() method, add:
closeButton.requestFocus()
Focus is different to the default.

JTextfield and JButtons

I have created a JFrame with 3 JTextFields, a button and a label in the centre of the page. I will create a key where if the user enters 'a' in all three textfields and hits the button, the color of the text in the label should change to a different colour for example red.
The main problem I have is linkning my textfields and the button so they work together.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CE203_2017_Ex1 extends JFrame
{
public static void window()
{
//Button
JButton but = new JButton("Submit");
//JNumberTextField
JTextField rgb1 = new JTextField("",3);
JTextField rgb2 = new JTextField("",3);
JTextField rgb3 = new JTextField("",3);
//JLabel
JLabel text1 = new JLabel("hello my name is adam ", JLabel.CENTER);
text1.setForeground(Color.BLUE);
text1.setAlignmentX(0);
text1.setAlignmentY(0);
//JFrame
JFrame window1 = new JFrame("Adam");
window1.setVisible(true);
window1.setSize(500,500);
window1.add(text1);
//JPanel
JPanel butPanel = new JPanel();
butPanel.add(rgb1);
butPanel.add(rgb2);
butPanel.add(rgb3);
butPanel.add(but);
window1.add(butPanel, BorderLayout.SOUTH);
window1.add(text1);
Here is my actionlistener for the button
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JTextField input = (JTextField) e.getSource();
String passy = input.getText();
String p = new String (passy);
if (rgb1.equals("a")&& rgb2.equals("a")&& rgb3.equals("a")){
text1.setForeground(Color.WHITE);
}
else{
JOptionPane.showMessageDialog(null, "nocorrect");}}});
}
public static void main( String[] args )
{
window();
}
}
You want to test the text value in the textFields not the objects.
if (rgb1.getText().equals("a")&& rgb2.getText().equals("a")&& rgb3.getText().equals("a")) {
text1.setForeground(Color.WHITE);
}

How to get a combo box to show on button click in java?

i am trying to get it so when a button is pressed a combo box is displayed in java. here is what i have tried.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class main {
public static void main(String[] args) {
final JFrame testFrame = new JFrame();
testFrame.setSize(300,450);
testFrame.setLocation(150,250);
testFrame.setTitle("My frame");
testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
testFrame.setResizable(true);
testFrame.setVisible(true);
testFrame.setLayout(new FlowLayout());
final JButton testButton = new JButton("show");
testFrame.add(testButton);
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent event) {
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == testButton) {
String[] myArray = {"test","test2"};
JComboBox testingCom = new JComboBox(myArray);
testFrame.add(testingCom);
}
}
}
}
}
Any help would be much appreciated. thank you.
Based in your code, you never addActionListener to your button.
In your ActionListener, you are creating a new instance of a combobox each time actionPerformed is called, and i don't if it's that what you want, you may be interested in if it's visible or not.
So you can change your code like this:
final JButton testButton = new JButton("show");
final JComboBox combo = new JComboBox(new String[]{"test1","test2"});
testButton.addActionListener(new ActionListener(){
// this is anonymous class
#Override
public void actionPerformed(ActionEvent evt){
//then you know that is attached to this button
combo.setVisible(!combo.isVisible());
}
});
combo.setVisible(Boolean.FALSE);
testFrame.add(testButton);
testFrame.add(combo);
Simply set the combo visible or invisible in the ActionListener and then revalidate and repaint its container. e.g.,
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
final JComboBox<String> myCombo = new JComboBox<String>(new String[]{"Foo", "Bar"});
final JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(250, 100));
mainPanel.add(new JButton(new AbstractAction("Toggle Combo") {
#Override
public void actionPerformed(ActionEvent arg0) {
myCombo.setVisible(!myCombo.isVisible());
mainPanel.revalidate();
mainPanel.repaint();
}
}));
mainPanel.add(myCombo);
JOptionPane.showMessageDialog(null, mainPanel);
}
}
Perhaps a cleaner way to do it is to use a CardLayout. If you use this, your components won't be shifting on removal and reviewing of the combo. For example:
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Main2 {
public static void main(String[] args) {
final JComboBox<String> myCombo = new JComboBox<String>(new String[]{"Foo", "Bar"});
final CardLayout cardLayout = new CardLayout();
final JPanel cardPanel = new JPanel(cardLayout);
cardPanel.add(myCombo, "combo");
cardPanel.add(new JLabel(), "empty");
final JPanel mainPanel = new JPanel();
mainPanel.add(new JButton(new AbstractAction("Toggle Combo") {
#Override
public void actionPerformed(ActionEvent evt) {
cardLayout.next(cardPanel);
}
}));
mainPanel.add(cardPanel);
JOptionPane.showMessageDialog(null, mainPanel);
}
}

addActionListener on panel. How to map to main frame?

I have 2 panel (2 class, extends from JPanel), 1 frame (1 class, extends from JFrame)
My first panel - WelcomePanel:
package caro;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class WelcomePanel extends JPanel {
public WelcomePanel() {
ImageIcon logoImage = new ImageIcon("/home/khanhpq/logo.png");
JButton playButton = new JButton("Play");
JButton exitButton = new JButton("Exit");
JLabel imageLabel = new JLabel(logoImage);
add(imageLabel);
add(playButton);
add(exitButton);
playButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(null, "Are you sure ?", "Warning", JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
}
}
My second panel - BoardPanel:
package caro;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class BoardPanel extends JPanel {
public BoardPanel() {
JPanel boardPanel = new JPanel();
Board board = new Board();
CellButton cellButton[] = new CellButton[144];
GridLayout gridLayout = new GridLayout(12, 12);
boardPanel.setLayout(gridLayout);
for (int i = 0; i < 144; i++) {
cellButton[i] = new CellButton();
boardPanel.add(cellButton[i]);
}
}
}
My main frame - MainFrame
package caro;
import javax.swing.JFrame;
public class MainFrame extends JFrame {
public MainFrame() {
add(new WelcomePanel());
setSize(360, 380);
setVisible(true);
}
public static void main(String[] args) {
MainFrame startFrame = new MainFrame();
}
}
My question: Help me write code, addActionListener on buttons of panels (material example). When i press play button (of WelcomePanel), WelcomePanel is hidden and BoardPanel is show. And, when i exit BoardPanel (close button is pressed, or click x button), WelcomePanel is showed.
My friend recommend use Message and Handle, but I don't know. Please help me. Thanks.
Its better to declare dependencies (Component like buttons, panels, etc...) as fields. In this way they are visible for a third class that is the Controller of them. In next examaple I make MainFrame controlling itself, just an example. Read about Presentation patterns for better pratices.
WelcomePanel.java
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class WelcomePanel extends JPanel {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
ImageIcon logoImage;
JButton playButton;
JButton exitButton;
JLabel imageLabel;
public WelcomePanel() {
logoImage = new ImageIcon("/home/khanhpq/logo.png");
playButton = new JButton("Play");
exitButton = new JButton("Exit");
imageLabel = new JLabel(logoImage);
add(imageLabel);
add(playButton);
add(exitButton);
}
}
BoardPanel.java
import javax.swing.JButton;
import javax.swing.JPanel;
public class BoardPanel extends JPanel {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
JButton closeButton;
public BoardPanel() {
closeButton = new JButton();
add(closeButton);
}
}
MainFrame.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame implements ActionListener {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
WelcomePanel welcomePanel;
BoardPanel boardPanel;
public MainFrame() {
welcomePanel = new WelcomePanel();
boardPanel = new BoardPanel();
add(welcomePanel);
add(boardPanel);
boardPanel.setVisible(false);
boardPanel.closeButton.addActionListener(this);
welcomePanel.playButton.addActionListener(this);
setSize(360, 380);
}
/**
* This class is the controller.
*/
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(boardPanel.closeButton)) {
welcomePanel.setVisible(false);
boardPanel.setVisible(true);
} else if (e.getSource().equals(welcomePanel.playButton)) {
welcomePanel.setVisible(true);
boardPanel.setVisible(false);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame startFrame = new MainFrame();
startFrame.setVisible(true);
}
});
}
}

Why Java ActionListener is not working?

Folks, I intend to implement a simple button ActionListener but it appears to not work.
The java codes are attached as following.....
The program intends to respond the click action from user and change the context of the JLabel
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame implements ActionListener {
public JButton btn = new JButton("Click");
public JLabel display = new JLabel("null");
public JPanel mainPanel = new JPanel();
public Frame() {
mainPanel.add(btn);
mainPanel.add(display);
add(mainPanel);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn) {
display.setText("it works");
System.out.println("it works");
}
}
public static void main(String[] args) {
Frame testFrame = new Frame();
testFrame.pack();
testFrame.setVisible(true);
}
}
Your actionlistener (the JFrame itself) is not added with addActionListener.
You should add ActionListner to the button
public Frame(){
mainPanel.add(btn);
mainPanel.add(display);
btn.addActionListener(this);
add(mainPanel);
}

Categories

Resources