I have created a JFrame in which I have created JTextArea.I have passed this JTextArea as a constructor to the other class. The JFrame is as follows:
JFrame frame = new JFrame("Find");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JTextArea textArea = new JTextArea(20,15);
frame.add(textArea,BorderLayout.NORTH);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
Texts text = new Texts(textArea);
frame.add(text.pane(),BorderLayout.CENTER);
JScrollPane pane = new JScrollPane(textArea);
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
JOptionPane.showMessageDialog(null, "Thank you for using finder");
System.exit(0); //Close program
}
});
}
I have passed the JTextArea to other class however it is not being displayed in the JFrame only the buttons show up.:
public class Texts {
public JTextArea tx;
JTextField findField = new JTextField( 10);
int pos = 0;
public Texts(JTextArea textArea) {
// TODO Auto-generated constructor stub
tx=textArea;
tx.setVisible(true);
}
public Component pane() {
// TODO Auto-generated method stub
JButton findButton = new JButton("Find");
JButton clearButton = new JButton("Clear");
JPanel header = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
header.add(findField, gbc);
gbc.gridx++;
header.add(findButton, gbc);
tx.add(header, BorderLayout.SOUTH);
header.add(clearButton);
findButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get the text to find...convert it to lower case for easier comparison
String find = findField.getText();
// Focus the text area, otherwise the highlighting won't show up
tx.requestFocusInWindow();
// Make sure we have a valid search term
if (find != null && find.length() > 0) {
Document document = tx.getDocument();
..........
First you do this...
frame.add(textArea,BorderLayout.NORTH);
Then you do this...
JScrollPane pane = new JScrollPane(textArea);
This effectively removes the textArea from the frame, this is because a component can only have a single parent.
Instead, try something like...
JScrollPane pane = new JScrollPane(textArea);
frame.add(pane,BorderLayout.NORTH);
Related
I have an actionlistener on a button that is to change a boolean called flood to true when clicked, this is then used in an if statement to call a method that will change a frame. My problem is nothing is happening when the button is clicked. I am using a debug log to check for the problem but I'm stumped.
public class Stop_The_Flood extends JFrame implements ActionListener{
final Button StopTheFlood = new Button("Stop The Flood!");
boolean flood = false;
public Stop_The_Flood(char[][] array) {
setTitle("Stop The Flood!");
setSize(1024,768);
//Container panel
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
//map panel
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(700, 900));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = array[0].length;
gbc.gridheight = array.length;
gbc.fill = GridBagConstraints.BOTH;
//Button Panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
g.gridwidth = 1;
g.gridheight = 1;
g.gridx = 8;
g.gridy = 15;
g.fill = GridBagConstraints.BOTH;
buttonPanel.setSize(350,350);
//Add to everything to frame
getContentPane().add(container);
container.add(panel, gbc);
container.add(buttonPanel, g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 100, 100);
StopTheFlood.setBackground(Color.cyan);
StopTheFlood.addActionListener(this);
JLabel[][] labelArray = new JLabel[array.length][array[0].length];
//Initialize JLabel array with the array that contains the data
labels(panel, labelArray, array);
buttonPanel.add(StopTheFlood);
setVisible(true);
if(flood == true) {
final Logger logger = Logger.getLogger("Stop_The_Flood");
logger.warning("found water");
}
}
public void actionPerformed(ActionEvent event) {
flood = true;
}
Nothing is being performed in your actionPerformed method, so you could try to create a new ClickListener class:
private class Clicklistener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == StopTheFlood)
{
flood = true;
}
}
}
Then on your "Stop_The_Flood" class create an object of ClickListener and add it to .addActionLister():
Clicklistener click= new Clicklistener();
StopTheFlood.addActionListener(click);
P.S don't forget to pass StopTheFlood to the ClickListener since I did not add that to the code.
I use gridbaglayout to dynamically construct the JPANEL from an array of label and button. And i want the label to stretch its width as the panel dimension is been changed by user. I have the weightx and fill constraints and still this is not working. This inner Gridbaglayout panel is been enclosed by an another outer panel of grid layout.
Thanks in advance for your comments and suggestions.
Below is the SC for this case -
JPanel flowpanel = new JPanel(new GridBagLayout());
JPanel boxPanel = new JPanel(new GridLayout(2,0));
int valueCount =8;
void labelPropertySetter(JLabel label, JButton button, String name) throws IOException {
label.setPreferredSize(new Dimension(200,55));
label.setText(name);
button.setPreferredSize(new Dimension(100,55));
button.setName(name);
button.setText(name);
}
public static void main (String[] args) throws IOException {
DemoPanel dp = new DemoPanel();
JLabel[] numberLabel = new JLabel[dp.valueCount];
JButton[] button = new JButton[dp.valueCount];
for (int i=0;i<dp.valueCount;i++) {
try {
//jpanel[i]= new JPanel(new BorderLayout(0,0));
numberLabel[i]=new JLabel();
button[i]=new JButton();
button[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((JButton)e.getSource()).setVisible(false);
System.out.println(((JButton)e.getSource()).getName());
}
});
dp.labelPropertySetter(numberLabel[i], button[i], new StringBuilder("Name :").append(i).toString());
//dp.boxPanel.add(jpanel[i]);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
GridBagConstraints gbc = new GridBagConstraints();
for(int i=0;i<dp.valueCount;i++)
{
gbc.gridx=1;
gbc.gridy=i;
gbc.gridheight=1;
gbc.gridwidth=1;
gbc.weightx=1.0;
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.anchor=GridBagConstraints.CENTER;
dp.flowpanel.add(numberLabel[i], gbc);
gbc.gridx=2;
gbc.gridy=i;
gbc.gridheight=1;
gbc.gridwidth=1;
gbc.weightx=0;
gbc.anchor=GridBagConstraints.LINE_END;
dp.flowpanel.add(button[i], gbc);
}
dp.boxPanel.setPreferredSize(new Dimension(500,500));
dp.boxPanel.add(dp.flowpanel);
dp.add(dp.boxPanel);
dp.pack();
dp.setVisible(true);
}
}
Firstly, I have only just started coding in Java this evening so apologizes if I seem like a total newb and that my code is atrocious, Im very much a novice. Basically I want an image to change colour when a certain number is entered into a text field on a separate j frame. so the car appears blue when loaded and if they press 1 the car moves and changes color. My issues is I cant seem to access the text variable to manipulate it. Any help would be greatly appreciated, thank you x
public class ImageBackground extends JFrame
{
public static void main(String[] args) throws Exception
{
JFrame F = new JFrame("CrossRoads Simulation");
TextDemo textDemo = new TextDemo();
try
{
F.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Stacy/workspace/Test/crossRoadsBackground.png")))));
}
catch(IOException e)
{
System.out.println("Image doesnt exist");
}
F.setResizable(false);
F.pack();
F.setVisible(true);
JButton button = new JButton(new ImageIcon("C:/Users/Stacy/workspace /Test/CarBlueOne.png"));
button.setSize(new Dimension(50, 50));
button.setLocation(130, 210);
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
F.add(button);
textDemo.createAndShowGUI();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textDemo.textArea.setCaretPosition(textDemo.textArea.getDocument().getLength( ));
}
}
TextDemo.java
public class TextDemo extends JPanel implements ActionListener {
public JTextField textField;
public JTextArea textArea;
public final static String newline = "\n";
JFrame F = new JFrame("CrossRoads Simulation");
ImageBackground imageBackground = new ImageBackground();
public TextDemo() {
super(new GridBagLayout());
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(5, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
}
protected static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TextDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add contents to the window.
frame.add(new TextDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
int input = Integer.parseInt(text);
if (input == 1)
{
JButton button = new JButton(new ImageIcon("C:/Users/Stacy/workspace /Test/CarRedOne.png"));
button.setSize(new Dimension(50, 50));
button.setLocation(170, 210);
}
textArea.append(text + newline);
textField.selectAll();
}
}
You do not have any code to expose the text variable in TextDemo to other classes. You should read/modify the text from the TextField variable. It should look similar to this:
public String getText() {
return textField.getText();
}
public void setText(String text) {
textField.setText(text);
}
Why are the JLabel, JTextField and JButton components on the FieldBox panel not displaying?
Please let me know if I can add anything to this question to make it more answerable!
The field box (one of which is created for each of several instance fields):
public class FieldBox extends javax.swing.JPanel {
JLabel label;
JTextField textField;
public FieldBox() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
label = new JLabel();
gbc.gridx = 0;
gbc.gridy = 0;
add(label,gbc);
textField = new JTextField();
gbc.gridx = 1;
gbc.gridy = 0;
add(textField, gbc);
JButton editBtn = new JButton("edit");
gbc.gridx = 2;
gbc.gridy = 0;
add(editBtn, gbc);
JButton saveBtn = new JButton ("save");
gbc.gridx = 3;
gbc.gridy = 0;
add(saveBtn, gbc);
label.setVisible(true);
label.setBackground(Color.yellow);
setVisible(true);
initComponents();
}
The panel onto which the boxes are added: (the panel appears. I know this panel loads because I can see its background. I can also see the "tit" JLabel, which I'm using for testing. Also, when I load the boxes onto it using a gridLayout (as shown below), I see the background of one of the boxes, but none of its contents are displayed, and also there should be three boxes shown but I only see one. Using a GridBagLayout
public class ShowBook extends javax.swing.JPanel {
public ShowBook(Book b) {
setLayout(new GridLayout(1,6));
setBackground(Color.GREEN);
String[] fieldTitles = {"title", "catalog", "publisher" };
JLabel tit = new JLabel("tit");
add(tit);
for (String s : fieldTitles){
FieldBox fb = new FieldBox();
fb.label.setText(s + ": ");
fb.textField.setText(getField(b, s));
System.out.println("in text field" + fb.textField.getText());
fb.revalidate();
fb.setVisible(true);
add (fb);
}
revalidate();
setVisible(true);
}
The panel onto which the ShowBook panel (above) is added. This panel also contains a listbox, which lists books in the collection, and a button to launch a ShowBook panel with the selected book as parameter.
public class ShowLib extends javax.swing.JPanel {
/**
* Creates new form ShowLib
*/
public ShowLib(Library l) {
setLayout(new BorderLayout()) ;
setBackground(Color.WHITE);
JPanel listPanel = new JPanel();
listPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
final JList bookList = new JList();
bookList.setVisible(true);
bookList.setPreferredSize(new Dimension(150, 600));
bookList.setBackground(Color.yellow);
DefaultListModel dlm = new DefaultListModel();
for (Book b : l.libList){
dlm.addElement(b);
}
bookList.setModel(dlm);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = gbc.BOTH;
listPanel.add(bookList, gbc);
JButton showBtn = new JButton("show");
gbc.gridy = gbc.RELATIVE;
listPanel.add(showBtn, gbc);
showBtn.addActionListener(new ActionListener () {
#Override
public void actionPerformed(ActionEvent e){
Book b = (Book) bookList.getSelectedValue();
ShowBook db = new ShowBook (b);
System.out.println("Clicked");
add (db, BorderLayout.CENTER);
revalidate();
}
});
revalidate();
setVisible(true);
add(listPanel, BorderLayout.WEST);
}
Where the ShowLib panel is added to the main JFrame. I know this works because that panel displays properly
void showLib() {
ShowLib sl = new ShowLib(l);
sl.setVisible(true);
setContentPane(sl);
revalidate();
// this.revalidate();
// this.pack();
System.out.println("showlibClicked");
}
The problem was the line initComponents(); at the bottom of the FieldBox class.
Lesson learned: If you're not using NetBeans visual GUI editor, GET RID OF THIS LINE!
this is my first time here.
I was writing a GUI-driven program which would allow me to perform Caesar's cipher on .txt files.
However, before I could add the ActionListeners and ChangeListeners I decided to test the GUI. Here is what I got:
Here is the code:
package implementation;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Frame extends JFrame{
public Frame(){
super("Caesar[E]");
this.setVisible(true);
this.setLocationRelativeTo(null);
/*Adding the options to GUI*/
factor.setPreferredSize(new Dimension(30,30));
JToolBar toolbar = new JToolBar();
radio.add(encrypt);
radio.add(decrypt);
toolbar.add(encrypt);
toolbar.add(decrypt);
toolbar.add(factor);
toolbar.setFloatable(false);
/*Adding the JTextArea for input*/
Box inputBound = Box.createHorizontalBox();
Box inputBound_text = Box.createVerticalBox();
Box inputBound_buttons = Box.createVerticalBox();
inputScroll.add(input);
inputScroll.setEnabled(true);
input.setEditable(true);
inputScroll.setBorder(BorderFactory.createTitledBorder("Text/File for Encryption/" +
"Decryption"));
inputBound_text.add(inputScroll);
inputBound_buttons.add(openFile);
inputBound_buttons.add(cancelFileInput);
inputBound.add(inputBound_text);
inputBound.add(Box.createHorizontalStrut(25));
inputBound.add(inputBound_buttons);
/*Adding JTextArea for output*/
Box outputBound = Box.createHorizontalBox();
Box outputBound_text = Box.createVerticalBox();
Box outputBound_buttons = Box.createVerticalBox();
outputScroll.add(output);
output.setEditable(true);
outputScroll.setBorder(BorderFactory.createTitledBorder("Text After Encryption" +
"/Decryption"));
outputBound_text.add(outputScroll);
outputBound_buttons.add(saveFile);
outputBound_buttons.add(send);
outputBound.add(outputBound_text);
outputBound.add(Box.createHorizontalStrut(25));
outputBound.add(outputBound_buttons);
outputBound.setSize(150, 200);
/*Adding JButton for performing the action*/
this.add(performAction,BorderLayout.SOUTH);
/*Adding the components to the Frame*/
Box outerBox = Box.createVerticalBox();
outerBox.add(toolbar,BorderLayout.NORTH);
outerBox.add(inputBound);
outerBox.add(outputBound);
this.add(outerBox);
this.setSize(500, 700);
}
boolean isFileInput = false;
boolean isEncrypt = true;
JButton performAction = new JButton("Encrypt!");
JButton openFile = new JButton("Open a File");
JButton cancelFileInput = new JButton("Cancel File Input");
JButton saveFile = new JButton("Save File");
JButton send = new JButton("Send");
JTextArea input = new JTextArea();
JTextArea output = new JTextArea();
JFileChooser chooser = new JFileChooser();
JScrollPane inputScroll = new JScrollPane();
JScrollPane outputScroll = new JScrollPane();
ButtonGroup radio = new ButtonGroup();
JRadioButton encrypt = new JRadioButton("Encrypt",true);
JRadioButton decrypt = new JRadioButton("Decrypt",false);
JSpinner factor = new JSpinner(new SpinnerNumberModel(1,1,26,1));
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new Frame();
}
});
}
}
Can you please tell me how I can solve the problems as shown in the image?
I know I can use setPreferredSize() but how do I make sure that I enter the correct dimension without trial-and-error?
I like the SpringLayout, it is very flexible and there is very not a lot that it can't do. Especially you will not need to care about setPreferredSize anymore. Just search for it, there are enough resources out there.
SpringLayout allows you to define the size of elements relative to others - so for example, you can make sure the buttons will look the same.
I would recommend MiGLayout as LayoutManager. Things like that are easy in MiGLayout
Trial-and-error is never a good way to get the layout you want. Instead, use the JTextArea constructor that lets you say how many rows and columns you want.
JTextArea(int rows, int columns)
JTextArea will calculate a good preferred size for when you pack() the window, and you won't need setSize().
Edit: You said, "JTextArea is inactive. I can't enter text in it."
Instead of add(), use setViewportView():
inputScroll.setViewportView(input);
...
outputScroll.setViewportView(output);
...
In situations like these, I like to divide my application into areas of responsibility. This keeps the code clean and self contained, allowing me to replace sections of it if/and when required, without adversely effect the rest of the application.
It also means that you can focus on the individual requirements of each section.
With complex layout, it's always better (IMHO) to use compounding containers with separate layout managers, it reduces the complexity and potential for strange cross over behavior.
public class BadLayout07 {
public static void main(String[] args) {
new BadLayout07();
}
public BadLayout07() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MasterPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MasterPane extends JPanel {
public MasterPane() {
EncryptSettings encryptSettings = new EncryptSettings();
InputPane inputPane = new InputPane();
OutputPane outputPane = new OutputPane();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(encryptSettings, gbc);
gbc.gridy++;
gbc.weighty = 1;
gbc.fill = gbc.BOTH;
add(inputPane, gbc);
gbc.gridy++;
add(outputPane, gbc);
}
}
public class EncryptSettings extends JPanel {
private JRadioButton encrypt;
private JRadioButton decrypt;
private JSpinner factor;
public EncryptSettings() {
encrypt = new JRadioButton("Encrypt");
decrypt = new JRadioButton("Decrypt");
ButtonGroup bg = new ButtonGroup();
bg.add(encrypt);
bg.add(decrypt);
factor = new JSpinner(new SpinnerNumberModel(new Integer(1), new Integer(1), null, new Integer(1)));
setLayout(new FlowLayout(FlowLayout.LEFT));
add(encrypt);
add(decrypt);
add(factor);
}
}
public class InputPane extends JPanel {
private JTextArea input;
private JButton open;
private JButton close;
public InputPane() {
setBorder(new TitledBorder("Source Text"));
input = new JTextArea();
open = new JButton("Open");
close = new JButton("Close");
JPanel tb = new JPanel(new FlowLayout(FlowLayout.LEFT));
tb.add(open);
tb.add(close);
setLayout(new BorderLayout());
add(tb, BorderLayout.NORTH);
add(new JScrollPane(input));
}
}
public class OutputPane extends JPanel {
private JTextArea output;
private JButton save;
private JButton send;
public OutputPane() {
setBorder(new TitledBorder("Encrypted Text"));
output = new JTextArea();
output.setEditable(false);
save = new JButton("Save");
send = new JButton("Send");
JPanel tb = new JPanel(new FlowLayout(FlowLayout.LEFT));
tb.add(save);
tb.add(send);
setLayout(new BorderLayout());
add(tb, BorderLayout.NORTH);
add(new JScrollPane(output));
}
}
}
I've not interconnect any of the functionality, but it is a simple case of providing appropriate setters and getters as required, as well appropriate event listeners.