I am trying to get the class i added to JPanel and run a function within the class.
I created MyButton class that extends JButton, This class i added to JPanel but after i added this class i want to run getText() on this objects.
I tried this but it does not recognize the function:
panel.getComponent(1).getText();
Main
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(2, 5));
for (int i = 0; i < 10; i++) {
panel.add(new MyButton());
}
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
MyButton
public class MyButton extends JButton {
private String text;
public MyButton()
{
this.text="Hello";
setText("test");
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
panel.getComponent(1).getText();
This returns a Component, which has no getText() method. It needs to be cast back to a JButton in order to use that method.
import java.awt.*;
import javax.swing.*;
public class ButtonText {
public static void main(String[] args) {
Runnable r = () -> {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(2, 5));
for (int i = 0; i < 10; i++) {
panel.add(new JButton("Text " + (i+1)));
}
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Component[] components = panel.getComponents();
for (Component component : components) {
JButton b = (JButton) component;
System.out.println(b.getText());
}
};
EventQueue.invokeLater(r);
}
}
BTW - having to trawl back though a panel to get the components seems like a poor hack. See What is the XY problem? Whatever the actual goal is here (& what is that goal?) is likely better served by storing the buttons in an array or list structure, when created.
Related
I've been working on creating a simple GUI through the use of JPanels. I've managed to what I believe fluke a reasonably looking layout and now I would like the user to be able to input values into the Mass textbox and the Acceleration textbox so when they hit calculate they are given a message telling them the Force.
The issue I am having is within the public void that is added to the buttons, I can't seem to figure out how to refer to values within the text field. I've tried to just refer to it generally by:
String mass = txts[1].getText();
However this doesn't recognise txts as existing?
Any help on this would be much appreciated.
Below is the full code in case it helps.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
import java.awt.*;
public class InitScreen {
public static void createHomeScreen() {
/*Creates a Java Frame with the Window Name = HomeScreen*/
JFrame frame = new JFrame("HomeScreen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.getContentPane().setPreferredSize(new Dimension(400,300));
frame.pack();
/*Creates the main JPanel in form of GridLayout*/
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(new EmptyBorder(new Insets(20,20,20,20)));
/*Creates the first sub panel*/
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(1,2,75,100));
firstPanel.setMaximumSize(new Dimension(300,100));
/*Creates the buttons in the first sub panel*/
JButton[] btns = new JButton[2];
String bText[] = {"Calculate", "Clear"};
for (int i=0; i<2; i++) {
btns[i] = new JButton(bText[i]);
btns[i].setPreferredSize(new Dimension(100, 50));
btns[i].setActionCommand(bText[i]);
btns[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
/*JOptionPane.showMessageDialog(null, "Clicked "+choice);*/
JOptionPane.showMessageDialog(null, "Force = ");
}
});
firstPanel.add(btns[i]);
}
/*Creates the second sub panel*/
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new BorderLayout());
/*Creates the labels for the second sub panel*/
JLabel label = new JLabel("Calculate the Force of an Object", SwingConstants.CENTER);
secondPanel.add(label,BorderLayout.NORTH);
/*Creates the third sub Panel for entering values*/
JPanel thirdPanel = new JPanel();
thirdPanel.setLayout(new GridLayout(3,1,10,10));
thirdPanel.setMaximumSize(new Dimension(400,100));
/*Create labels and text fields for third sub panel*/
String lText[] = {"Mass of Body", "Acceleration of Body", "Force"};
JLabel[] lbls = new JLabel[3];
JTextField[] txts = new JTextField[3];
for (int i=0; i<3; i++) {
txts[i] = new JTextField();
lbls[i] = new JLabel(lText[i], SwingConstants.LEFT);
lbls[i].setPreferredSize(new Dimension(50, 50));
thirdPanel.add(lbls[i]);
thirdPanel.add(txts[i]);
}
mainPanel.add(secondPanel);
mainPanel.add(thirdPanel);
mainPanel.add(firstPanel);
frame.setContentPane(mainPanel);
frame.setVisible(true);
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createHomeScreen();
}
});
}
}
First drop the reliance on static, and instead, create an instance of InitScreen and call it's createHomeScreen method
public class InitScreen {
public void createHomeScreen() {
//...
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
InitScreen screen = new InitScreen();
screen.createHomeScreen();
}
});
}
Now, make txts and instance field of InitScreen and use it within your methods
public class InitScreen {
private JTextField[] txts;
public void createHomeScreen() {
//...
txts = new JTextField[3];
//...
}
This takes txts from a local context to a class instance context, meaning you can now access it from any method within InitScreen
In this code , I have used 3 classes all of them which extend the JPanel class , whose instances are added to a JFrame in the JForm3 class's constructor.
I am wondering if there's a way to display the text present in the text field(instance of JTextField declared in TextPanel class) in the printTextOnConsole() method in the ButtonPanel class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JForm3
{
JFrame frame;
ButtonPanel bP;
TextPanel tP;
LabelPanel lP;
public JForm3()
{
frame = new JFrame("Java Window.");
bP = new ButtonPanel();
tP = new TextPanel();
lP = new LabelPanel();
frame.setSize(500,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER,tP);
frame.getContentPane().add(BorderLayout.EAST,bP);
frame.getContentPane().add(BorderLayout.WEST,lP);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
new JForm3();
}
}
class ButtonPanel extends JPanel implements ActionListener
{
JButton quitButton;
JButton printButton;
public ButtonPanel()
{
quitButton = new JButton("Quit");
printButton = new JButton("Print");
quitButton.addActionListener(this);
printButton.addActionListener(this);
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
this.add(quitButton);
this.add(printButton);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == quitButton)
System.exit(0);
else
printTextOnConsole();
}
public void printTextOnConsole()
{
}
}
class LabelPanel extends JPanel
{
JLabel label;
public LabelPanel()
{
this.setLayout(new BorderLayout());
label = new JLabel("Enter Some Text :");
this.add(BorderLayout.CENTER,label);
this.setVisible(true);
}
}
class TextPanel extends JPanel
{
JTextField textField;
public TextPanel()
{
this.setLayout(new BorderLayout());
textField = new JTextField("Enter text here");
this.add(BorderLayout.CENTER,textField);
this.requestFocus();
textField.select(0,textField.getText().length());
this.setVisible(true);
}
}
Use an interface to loose couple the text functionality between JPanels.
interface TextRetriever {
String getText();
}
Then pass the instance of the TextRetriever (TextPanel) to ButtonPanel
class ButtonPanel extends JPanel implements ActionListener {
private TextRetriever textRetriever;
public ButtonPanel(TextRetriever textRetriever) {
this.textRetriever = textRetriever
...
}
public void printTextOnConsole() {
String text = textRetriever.getText();
}
}
This is the JPanel
public class DisplayBoard {
public static void main (String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//The main panel
JPanel main = new JPanel();
main.setPreferredSize(new Dimension(600,800) );
main.setLayout(new BorderLayout());
//The title panel
JPanel title = new JPanel();
title.setPreferredSize(new Dimension(400, 120));
title.setBackground(Color.YELLOW);
JLabel test1 = new JLabel("Title goes here");
title.add(test1);
//The side bar panel
JPanel sidebar = new JPanel();
sidebar.setPreferredSize(new Dimension(200, 800));
sidebar.add(AddSubtract);
sidebar.setBackground(Color.GREEN);
JLabel test2 = new JLabel("Sidebar goes here");
sidebar.add(test2);
//The panel that displays all the cards
JPanel cardBoard = new JPanel();
cardBoard.setPreferredSize(new Dimension(400,640) );
//adding panels to the main panel
main.add(cardBoard, BorderLayout.CENTER);
main.add(title, BorderLayout.NORTH);
main.add(sidebar, BorderLayout.WEST);
frame.setContentPane(main);
frame.pack();
frame.setVisible(true);
}
}
and I want to add this class into the sidebar panel
public class AddSubtract {
int Number = 0;
private JFrame Frame = new JFrame("Math");
private JPanel ContentPane = new JPanel();
private JButton Button1 = new JButton("Add");
private JButton Button2 = new JButton("Subtract");
private JLabel Num = new JLabel ("Number: " + Integer.toString (Number));
public AddSubtract() {
Frame.setContentPane(ContentPane);
ContentPane.add(Button1);
ContentPane.add(Button2);
ContentPane.add(Num);
Button1.addActionListener(new Adding());
Button2.addActionListener(new Subtracting());
}
public class Adding implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number++;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public class Subtracting implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number--;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public void launchFrame(){
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.pack();
Frame.setVisible(true);
}
public static void main(String args[]){
AddSubtract Test = new AddSubtract();
Test.launchFrame();
}
}
Can someone explain to me how I can do this ?
I have a feeling that this is not going to work, but I really want to learn the way to do it.
This definately is not going to work. For starters, you have two main() methods. Second, if you want to add a class to your Frame, it should extend from JComponent. Basically, your code should look like this:
public class MainFrame extends JFrame {
public MainFrame() {
this.add(new MainPanel())
//insert all settings here.
}
}
public class MainPanel extends JPanel {
public MainPanel() {
this.add(new AddSubtract());
this.add(/*more panels*/)
}
}
public class AddSubtract extends JPanel {
public AddSubtract() {
//add buttons and stuff here
}
}
and variables do NOT start with capitals.
Edit: And when you have some JFrame, it's usually best to have a main() method with just one line:
public static void main(String[] args) {
new MainFrame();
}
just set the settings and configuration of the JFrame in the constructor.
I want to add multiple jpanels to jpanel.So i added a root panel to jscrollpane.and then added all individual jpanels to this root panel.I made jscrollpane's scrolling policy as needed.i.e HORIZONTAL_SCROLLBAR_AS_NEEDED,VERTICAL_SCROLLBAR_AS_NEEDED.
But the problem is all individual panels are not shown inside root panel.
Code:
JScrollPane scPanel=new JScrollPane();
JPanel rootPanel=new JPanel();
rootPanel.setLayout(new FlowLayout());
JPanel indPanel = new JPanel();
rootPanel.add(indPanel);
JPanel indPanel2 = new JPanel();
rootPanel.add(indPanel2);
//.....like this added indPanals to rootPanel.
scPanel.setViewPortView(rootPanel);
//scPanel.setHorizontalScrollPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);
And one more thing is, as i scroll the scrollbar the panels are going out of jscrollpane area.
I am not able to see all individual panels,
Please suggest me.
Edit: code snippet from double post:
MosaicFilesStatusBean mosaicFilesStatusBean = new MosaicFilesStatusBean();
DefaultTableModel tableModel = null;
tableModel = mosaicFilesStatusBean.getFilesStatusBetweenDates(startDate, endDate);
if (tableModel != null) {
rootPanel.removeAll();
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
for (int tempRow = 0; tempRow < tableModel.getRowCount(); tempRow++) {
int fileIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 0).toString());
String dateFromTemp = tableModel.getValueAt(tempRow, 3).toString();
String dateToTemp = tableModel.getValueAt(tempRow, 4).toString();
int processIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 5).toString());
int statusIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 6).toString());
String operatingDateTemp = tableModel.getValueAt(tempRow, 7).toString();
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, dateFromTemp, dateToTemp, processIdTemp, statusIdTemp, operatingDateTemp);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
}
The main reason, why you couldn't see your JPanel is that you are using FlowLayout as the LayoutManager for the rootPanel. And since your JPanel added to this rootPanel has nothing inside it, hence it will take it's size as 0, 0, for width and height respectively. Though using GridLayout such situation shouldn't come. Have a look at this code example attached :
import java.awt.*;
import javax.swing.*;
public class PanelAddition
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Panel Addition Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1));
JScrollPane scroller = new JScrollPane();
CustomPanel panel = new CustomPanel(1);
contentPane.add(panel);
scroller.setViewportView(contentPane);
frame.getContentPane().add(scroller, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
for (int i = 2; i < 20; i++)
{
CustomPanel pane = new CustomPanel(i);
contentPane.add(pane);
contentPane.revalidate();
contentPane.repaint();
}
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PanelAddition().createAndDisplayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
public CustomPanel(int num)
{
JLabel label = new JLabel("" + num);
add(label);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(200, 50));
}
}
Don't use FlowLayout for the rootPanel. Instead consider using BoxLayout:
JPanel rootPanel=new JPanel();
// if you want to stack JPanels vertically:
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
Edit 1
Here's an SSCCE that's loosely based on your latest code posted:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class PanelsEg extends JPanel {
private static final int MAX_ROW_COUNT = 100;
private Random random = new Random();
private JPanel rootPanel = new JPanel();
public PanelsEg() {
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(rootPanel);
scrollPane.setPreferredSize(new Dimension(400, 400)); // sorry kleopatra
add(scrollPane);
add(new JButton(new AbstractAction("Foo") {
#Override
public void actionPerformed(ActionEvent arg0) {
foo();
}
}));
}
public void foo() {
rootPanel.removeAll();
// rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS)); // only need to set layout once
int rowCount = random.nextInt(MAX_ROW_COUNT);
for (int tempRow = 0; tempRow < rowCount ; tempRow++) {
int fileIdTemp = tempRow;
String data = "Data " + (tempRow + 1);
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, data);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
rootPanel.repaint(); // don't forget to repaint if removing
}
private class MosaicPanel extends JPanel {
public MosaicPanel(int fileIdTemp, String data) {
add(new JLabel(data));
}
}
private static void createAndShowGui() {
PanelsEg mainPanel = new PanelsEg();
JFrame frame = new JFrame("PanelsEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This SSCCE works, in that it easily shows removing and adding JPanels to another JPanel that is held by a JScrollPane. If you're still having a problem, you should modify this SSCCE so that it shows your problem.
I have a JFrame which contains 3 JPanels. I want to pass the JTextField value of one panel to other. Each panel is shown using JTabbedPane. I am getting null when i access the value of other text field. How can i access?
You don't show any code, and so it's impossible to know why you're getting "null" values. Two possible solutions if you want all three JPanels to hold JTextFields with the same content:
Put the shared JTextField outside of the JPanels held by the JTabbedPane and instead in a JPanel that holds the JTabbedPane, so that the field is always visible no matter what tab is displayed, or
Use several JTextFields but have them share the same Document or "model".
e.g.,
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.text.PlainDocument;
public class SharedField extends JTabbedPane {
private static final int TAB_COUNT = 5;
private static final int MY_WIDTH = 600;
private static final int MY_HEIGHT = 300;
PlainDocument doc = new PlainDocument();
public SharedField() {
for (int i = 0; i < TAB_COUNT; i++) {
JTextField tField = new JTextField(10);
tField.setDocument(doc);
JPanel panel = new JPanel();
panel.add(tField);
add("Panel " + i, panel);
// to demonstrate some of the JTextFields acting like
// a label
if (i % 2 == 1) { // if i is odd
tField.setEditable(false);
tField.setBorder(null);
}
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(MY_WIDTH, MY_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("SharedField");
frame.getContentPane().add(new SharedField());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Edit 1
I see that you've cross-posted this on java-forums.org/ where you show some of your code:
pacage Demotool;
Class:MainFrame
This is the actionPerformed code of first panel
both str and scrTxt is (public static)
public void actionPerformed(ActionEvent e)
{
String act=e.getActionCommand();
if(act.equals("ADD"))
{
str=scrnTxt.getText();
System.out.println("Hi :"+str);
Demotool.DemoTool.jtp.setSelectedIndex(1);
}
}
using the belove code i tried to access the data but I am getting null String:
System.out.println("Hello:"+Demotool.MainFrame.str);
Problems:
Don't use static variables or methods unless you have a good reason to do so. Here you don't.
You're may be trying to access the MainFrame.str variable before anything has been put into it, making it null, or you are creating a new MainFrame object in your second class, one that isn't displayed, and thus one whose str variable is empty or null -- hard to say.
Either way, this design is not good. You're better off showing us a small demo program that shows your problem with code that compiles and runs, an sscce, so we can play with and modify your code and better be able to show you a decent solution.
One such decent solution is to add a DocumentListener to the JTextField so that changes to the text held by the JTextField are "pushed" into the observers that are listening for changes (your other classes).
For example, using DocumentListeners:
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
public class SharedField2 extends JTabbedPane {
private static final int LABEL_PANEL_COUNT = 4;
private static final int MY_WIDTH = 600;
private static final int MY_HEIGHT = 300;
public SharedField2() {
TextFieldPanel tfPanel = new TextFieldPanel();
LabelPanel[] labelPanels = new LabelPanel[LABEL_PANEL_COUNT];
add("TextFieldPanel", tfPanel);
for (int i = 0; i < labelPanels.length; i++) {
labelPanels[i] = new LabelPanel();
// add each label panel's listener to the text field
tfPanel.addDocumentListenerToField(labelPanels[i].getDocumentListener());
add("Label Panel " + i, labelPanels[i]);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(MY_WIDTH, MY_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("SharedField2");
frame.getContentPane().add(new SharedField2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class TextFieldPanel extends JPanel {
private JTextField tField = new JTextField(10);
public TextFieldPanel() {
add(tField);
}
public void addDocumentListenerToField(DocumentListener listener) {
tField.getDocument().addDocumentListener(listener);
}
}
class LabelPanel extends JPanel {
private DocumentListener myListener;
private JLabel label = new JLabel();
public LabelPanel() {
add(label);
myListener = new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
try {
label.setText(e.getDocument().getText(0,
e.getDocument().getLength()));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
};
}
public DocumentListener getDocumentListener() {
return myListener;
}
}
One simple solution will be making JTextField global so all panel can access it.
Make sure all your panel can access JTextField that is textField is globally accessible.
Following code demonstrate this:
JTextField textField = new JTextField(25);
JLabel labelForPanel2 = new JLabel(),labelForPanel3 = new JLabel();
private void panelDemo() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", panel1);
tabbedPane.addTab("Tab 2", panel2);
tabbedPane.addTab("Tab 3", panel3);
panel1.add(textField);
panel2.add(labelForPanel2);
panel3.add(labelForPanel3);
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
labelForPanel2.setText(textField.getText());
labelForPanel3.setText(textField.getText());
}
});
frame.add(tabbedPane);
frame.setVisible(true);
}
I don't know what exactly are you going to achieve, but maybe try data binding?
Take a look at BetterBeansBinding library.