Having trouble adding JScrollBar/JScrollPane to this JTextPane - java

Ok, so here's a snippet of my code containing the problem:
private JTextField userText;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private JTextPane images;
private JScrollPane jsp = new JScrollPane(images);
public Server(){
super(name+" - IM Server");
images = new JTextPane();
images.setContentType( "text/html" );
HTMLDocument doc = (HTMLDocument)images.getDocument();
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
add(jsp);
add(images, BorderLayout.CENTER);
images.setEditable(false);
try {
doc.insertString(0, "This is where images and text will show up.\nTo send an image, do\n*image*LOCATION OF IMAGE\n with NO SPACES or EXTRA TEXT.", null );
} catch (BadLocationException e) {
e.printStackTrace();
}
setSize(700,400);
setVisible(true);
ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("CHAT.png"));
setIconImage(logo.getImage());
}
and when I use it, there's no scrollbar on my JTextPane?! I have tried moving add(jsp); above and below where it is, and moving it below add(images, BorderLayout.NORTH); greys it out?! So what I want to know is how to add this JScrollPane to my JTextPane to give it a scrollbar. Thanks in advance!

Bascially, you actually never add a valid component to the JScrollPane...
private JTextPane images;
private JScrollPane jsp = new JScrollPane(images);
When this executes, images is null, so basically, you are calling new JScrollPane(null);
Then, you basically add images over the top of (replacing) jsp on the frame...
add(jsp);
add(images, BorderLayout.CENTER);
The default position is BorderLayout.CENTER and border layout can only support a single component in any of it's 5 available positions...
Instead, try something like...
public Server(){
super(name+" - IM Server");
images = new JTextPane();
images.setContentType( "text/html" );
HTMLDocument doc = (HTMLDocument)images.getDocument();
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
jsp.setViewportView(images);
add(jsp);
//add(images, BorderLayout.CENTER);
images.setEditable(false);
try {
doc.insertString(0, "This is where images and text will show up.\nTo send an image, do\n*image*LOCATION OF IMAGE\n with NO SPACES or EXTRA TEXT.", null );
} catch (BadLocationException e) {
e.printStackTrace();
}
setSize(700,400);
setVisible(true);
ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("CHAT.png"));
setIconImage(logo.getImage());
}

Related

How can I color this frame/border of my JTextArea?

I wanted to make a TextEditor and tried to change some colors. But I still have difficulties changing the color of the JFrame of the JTextArea (I mean this white border) and also don't know how I can make this text area so that it always changes the size to the selected JFrame size.
TextEditorPicture
TextEditorPicture2
public class TextEditor extends JFrame implements ActionListener {
JTextArea textArea;
JScrollPane scrollPane;
JLabel fontLabel;
JSpinner fontSizeSpinner;
JButton fontColorButton;
JComboBox fontBox;
JMenuBar menuBar;
JMenu fileMenu;
JMenuItem openItem;
JMenuItem saveItem;
JMenuItem exitItem;
TextEditor(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("TextEditor");
this.setSize(500,500);
this.setMinimumSize(new Dimension(500,0));
this.setMaximumSize(new Dimension(500, Integer.MAX_VALUE));
this.setVisible(true);
this.setLayout(new FlowLayout());
this.setLocationRelativeTo(null);
this.getContentPane().setBackground(Color.decode("#252025"));
//Text Area
textArea = new JTextArea();
textArea.setVisible(true);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setFont(new Font("SF Mono Regular 11", Font.PLAIN,20));
textArea.setBackground(Color.decode("#252025"));
textArea.setForeground(Color.decode("#eaeaea"));
//Scroll Panel Sidebar
scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500,500));
scrollPane.setMinimumSize(new Dimension(500,0));
scrollPane.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
scrollPane.setVisible(true);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//Font Text
fontLabel = new JLabel("Font: ");
fontLabel.setForeground(Color.decode("#eaeaea"));
//Font Size Spinner
fontSizeSpinner = new JSpinner();
fontSizeSpinner.setPreferredSize(new Dimension(50,25));
fontSizeSpinner.setValue(20);
fontSizeSpinner.getEditor().getComponent(0).setBackground(Color.decode("#252025"));
fontSizeSpinner.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
textArea.setFont(new Font("SF Mono Regular 11",Font.PLAIN,(int) fontSizeSpinner.getValue()));
textArea.setSelectedTextColor(Color.white);
}
});
fontColorButton = new JButton("Color");
fontColorButton.setBackground(Color.decode("#252025"));
fontColorButton.setOpaque(true);
fontColorButton.setBorderPainted(false);
fontColorButton.addActionListener(this);
fontColorButton.setForeground(Color.decode("#eaeaea"));
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
//Font Change Box
fontBox = new JComboBox(fonts);
fontBox.addActionListener(this);
fontBox.setBackground(Color.decode("#252025"));
fontBox.setForeground(Color.green);
fontBox.setOpaque(true);
fontBox.setEditable(true);
fontBox.getEditor().getEditorComponent().setBackground(Color.decode("#252025"));
((JTextField) fontBox.getEditor().getEditorComponent()).setBackground(Color.decode("#252025"));
fontBox.setSelectedItem("SF Mono Regular 11");
//Menubar
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
openItem = new JMenuItem("Open");
saveItem = new JMenuItem("Save");
exitItem = new JMenuItem("Exit");
openItem.addActionListener(this);
saveItem.addActionListener(this);
exitItem.addActionListener(this);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
this.add(fontLabel);
this.add(fontSizeSpinner);
this.add(fontColorButton);
this.add(fontBox);
this.add(scrollPane);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == fontColorButton) {
JColorChooser colorChooser = new JColorChooser();
Color color = colorChooser.showDialog(null, "Color", Color.white);
}
if(e.getSource()==fontBox) {
textArea.setFont(new Font((String)fontBox.getSelectedItem(),Font.PLAIN,textArea.getFont().getSize()));
}
//Open
if(e.getSource()==openItem) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
fileChooser.setFileFilter(filter);
int response = fileChooser.showOpenDialog(null);
if(response==JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
Scanner fileIn = null;
try {
fileIn = new Scanner(file);
if(file.isFile()) {
while(fileIn.hasNextLine()) {
String line = fileIn.nextLine()+"\n";
textArea.append(line);
}
}
} catch (FileNotFoundException e1){
e1.printStackTrace();
} finally {
fileIn.close();
}
}
}
//Save
if(e.getSource()==saveItem) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
int response = fileChooser.showSaveDialog(null);
if(response==JFileChooser.APPROVE_OPTION) {
File file;
PrintWriter fileOut = null;
file = new File(fileChooser.getSelectedFile().getAbsolutePath());
try {
fileOut = new PrintWriter(file);
fileOut.println(textArea.getText());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
fileOut.close();
}
}
}
//Exit
if(e.getSource()==exitItem) {
System.exit(0);
}
}
}
You need to use multiple layouts. FlowLayout alone is not sufficient.
The center component of a BorderLayout will always stretch to fill the container’s space.
Remember that you can put panels inside panels. Put your font and color labels/fields in a JPanel that uses a FlowLayout, then put that JPanel in the NORTH area of a JPanel that uses a BorderLayout. Your JScrollPane belongs in the center of that same BorderLayout.
Remove all calls to setPreferredSize, setMinimumSize, and setMaximumSize. They are intefering with a layout manager’s ability to properly arrange things. All components have a useful preferred size when they are created.
To set the size of your JScrollPane, use the setRows and setColumns methods of JTextArea. The JScrollPane parent will consult its Scrollable view (that is, the JTextArea) to determine its preferred size.

Problems with Changing JTextArea font size

I am trying to prompt the user for input from a JOptionPane to change the font size of the JTextArea, shown below as, "console".
Issue:
However, the JOptionPane is not showing when I click on the size JMenu item.
Code:
Font font = new Font("Arial", Font.PLAIN, 12);
panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);
JTextArea console = new JTextArea();
console.setLineWrap(true);
console.setWrapStyleWord(true);
console.setEditable(false);
console.setFont(font);
JScrollPane scroll = new JScrollPane(console);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll, BorderLayout.CENTER);
JMenuBar bar = new JMenuBar();
panel.add(bar, BorderLayout.NORTH);
JMenu size = new JMenu("Size");
size.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
String fontSize = JOptionPane.showInputDialog(panel, "New font size, 6 or larger:", "Set Font Size", JOptionPane.OK_CANCEL_OPTION);
Font newFont = font.deriveFont(Integer.parseInt(fontSize));
console.setFont(newFont);
}
});
bar.add(size);
This seems to be a bug but you could use a ´MenuListener´ as described in this answer by #TPete
Here is the code he provided in his answer to work around the issue:
JMenu menu = new JMenu("MyMenu");
menu.addMenuListener(new MenuListener() {
#Override
public void menuSelected(MenuEvent e) {
System.out.println("menuSelected");
}
#Override
public void menuDeselected(MenuEvent e) {
System.out.println("menuDeselected");
}
#Override
public void menuCanceled(MenuEvent e) {
System.out.println("menuCanceled");
}
});
Basically he's using a MenuListener instead of an ActionListener to catch the event successfully.
Hope this helps!
Issue with the JOptionPane is not showing when I click on the size JMenu item, is because the container where we need to display the pane is incorrect
try the following
JOptionPane.showInputDialog(**this**, "New font size, 6 or larger:",
"Set Font Size", JOptionPane.OK_CANCEL_OPTION);

Why won't my image display in my layout?

I'm working on this project in Java and need an image to display, along with a bio, and button that plays a song/sound. I finished the button and bio but I can figure out how to get the image to display in the NORTH part of the layout along with the button in the center part, any help would be great.
This is my error: The method add(String, Component) in the type Container is not applicable for the arguments (Image, String)
public void init() {
// image
myPicture = getImage(getCodeBase(), "sample.jpg");
// THIS IS WHERE MY PROBLEM IS vvvvvvv
add(myPicture, BorderLayout.NORTH);
add(bio);
paneSouth.add(play);
getContentPane().add(paneSouth, BorderLayout.SOUTH);
mySound = getAudioClip(getDocumentBase(), "sample.wav");
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mySound.play();
}});
}
public void paint(Graphics g){
g.drawImage(myPicture, 10, 10, this);
}
private JPanel paneSouth = new JPanel();
private TextArea bio = new TextArea("bio thing");
private JButton play = new JButton("Play");
private AudioClip mySound;
private Image myPicture;
}
EDIT:
public void init() {
// image
ImageIcon icon = new ImageIcon(myPicture);
JLabel myLabelImage = new Image(icon);
add(myLabelImage, BorderLayout.NORTH);
// bio
add(bio);
add(bio, BorderLayout.CENTER);
// sound
paneSouth.add(play);
getContentPane().add(paneSouth, BorderLayout.SOUTH);
mySound = getAudioClip(getDocumentBase(), "sample.wav");
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mySound.play();
}});
}
private JPanel paneSouth = new JPanel();
private TextArea bio = new TextArea("bio.");
private JButton play = new JButton("Play");
private AudioClip mySound;
private Image myPicture;
}
I guess you are using JApplet because you are using Swing components. Try something like this:
public class ImageApplet extends JApplet {
private JPanel paneSouth = new JPanel();
private JTextArea bio = new JTextArea("bio thing");
private JButton play = new JButton("Play");
private Image myPicture;
private ImageIcon icon;
private JLabel label;
public void init() {
try {
URL pic = new URL(getDocumentBase(), "sample.jpg");
myPicture = ImageIO.read(pic);
icon = new ImageIcon(myPicture);
label = new JLabel(icon);
} catch (Exception e) {
e.printStackTrace();
}
// add image
add(label, BorderLayout.NORTH);
// bio
add(bio, BorderLayout.CENTER);
// sound
paneSouth.add(play);
add(paneSouth, BorderLayout.SOUTH);
// here add your sound declaration and button event...
}
#Override
public void paint(Graphics g) {
super.paint(g);
}
}
And try change your TextArea for a JTextArea since you are only using swing components.

how to get int from JTextField with a JButton

I'm trying to get an int from my JTextField with the click of my JButton but I can't figure out how to do so. I'm trying to get the int and set it to a variable so I can use it in my program further down.
Here is the code(this is the whole method):
JFrame presets = new JFrame("Presets");
presets.setVisible(true);
presets.setSize(500, 500);
JPanel gui = new JPanel(new BorderLayout(2,2));
JPanel labelFields = new JPanel(new BorderLayout(2,2));
labelFields.setBorder(new TitledBorder("Presets"));
JPanel labels = new JPanel(new GridLayout(0,1,1,1));
JPanel fields = new JPanel(new GridLayout(0,1,1,1));
labels.add(new JLabel("Place values on Cat.2/Cat.3 at"));
JTextField f1 = new JTextField(10);
String text = f1.getText();
int first = Integer.parseInt(text);
labels.add(new JLabel("and place follow up value at"));
fields.add(new JTextField(10));
labelFields.add(labels, BorderLayout.CENTER);
labelFields.add(fields, BorderLayout.EAST);
JPanel guiCenter = new JPanel(new BorderLayout(2,2));
JPanel submit = new JPanel(new FlowLayout(FlowLayout.CENTER));
submit.add( new JButton("Submit") );
guiCenter.add( submit, BorderLayout.NORTH );
gui.add(labelFields, BorderLayout.NORTH);
gui.add(guiCenter, BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, gui);
Try this,
String getText()
Returns the text contained in this TextComponent.
So, convert your String to Integer as:
try {
int integerValue = Integer.parseInt(jTextField.getText());
}
catch(NumberFormatException ex)
{
System.out.println("Exception : "+ex);
}
Probably you want the entered data as int. write it in the button action
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
int myInt=Integer.parseInt(jtextfield.getText());
System.out.println("Integer is: "+myInt);
//do some stuff
}
catch (NumberFormatException ex) {
System.out.println("Not a number");
//do you want
}
}
});
Remember Integer.parseInt throws NumberFormatException which must be caught. see java docs
if you want to get the f1 text when the submit pressed, use this code:
.
.
.
JPanel submit = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
int first = Integer.parseInt(f1.getText().trim());
}
});
submit.add(button);
guiCenter.add(submit, BorderLayout.NORTH);
.
.
.

JTabbedPane with button getting the pane

I have a JTappedPane with a button on that I want to make close that tab.
I am doing it like so:
jTabbedPane1.addTab(title, null, panel, null);
JPanel pnl = new JPanel();
JButton close = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("x.png"));
close.setIcon(new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
close.setPreferredSize(new Dimension(10, 10));
close.setBorderPainted(false);
close.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(ActionEvent evt) {
//TODO CLOSE THE TAP WHEN BUTTON IS PRESSED
}
}});
JLabel lab = new JLabel(s);
pnl.setOpaque(false);
pnl.add(lab);
pnl.add(close);
jTabbedPane1.setTabComponentAt(jTabbedPane1.getTabCount() - 1, pnl);
I am trying to get the title of the tab on the tab that the button has been pressed on.
I thought i could do something like
close.getContaining() to return the tab it is on but I was wrong.
Any Ideas?
If I understand you correctly, you want to find the index of the tab which has the parent of the button as tabComponent:
public void actionPerformed(ActionEvent evt) {
JComponent source = (JComponent) evt.getSource();
Container tabComponent = source.getParent();
int tabIndex = jTabbedPane1.indexOfTabComponent(tabComponent);
jTabbedPane1.removeTabAt(tabIndex);
}
You could simply write:
jTabbedPane1.removeTabAt(jTabbedPane1.getSelectedIndex());

Categories

Resources