How to set Bounds and Preferedsize of JTextPane - java

I'm writing a Java program and I use JSplitPane to split between two JTextPanes.
The bottom JtextPane is in JTabbedPane.
public class test extends JFrame{
private JTextPane commandTextPane = new JTextPane();
private JPanel tokenPanel;
private JTextPane tokenTextPane = new JTextPane();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test window = new test();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public test (){
setBounds(100, 100, 900, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
commandTextPane.setBounds(0, 0, 200, 300);
commandTextPane.setPreferredSize(new Dimension(200, 300));
//create ressultTabPane
JTabbedPane resultTabPane = new JTabbedPane();
tokenTabPanel();
resultTabPane.addTab("Token", tokenPanel);
JScrollPane topScroll = new JScrollPane(commandTextPane,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
TextLineNumber topLine = new TextLineNumber(commandTextPane);
topScroll.setRowHeaderView(topLine);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topScroll, resultTabPane);
splitPane.setOneTouchExpandable(true);
getContentPane().add(splitPane);
setVisible(true);
}
public void tokenTabPanel() {
tokenPanel = new JPanel();
tokenTextPane.setBounds(0, 0, 200, 300);
tokenTextPane.setPreferredSize(new Dimension(200,300));
JScrollPane tokenScroll = new JScrollPane(tokenTextPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
TextLineNumber tokenLine = new TextLineNumber(tokenTextPane);
tokenScroll.setRowHeaderView(tokenLine);
tokenPanel.add(tokenScroll);
}
}
The problem is I can't set Bounds and PreferedSize of those JTextPanes. When I set them, the top JTextPane is not expect size and the bottom JTextPane is not in the top-left also its size.
image --> (http://upic.me/show/54858871)
Do you know how to fix them? Sorry for my English.
Thanks in advance.

Related

How to make JTextArea autoscroll

i have problem with my JTextArea i java. When i print output in the text area, it doesn't automatically scroll to the bottom. And when it reaches the bottom of text area i cannot scroll it with scroll panel. Here is my GUI Code:
public void initializeWindow()
{
JPanel pan;
JPanel colorBox;
JPanel consolePanel;
JLabel panText;
JFrame frame = new JFrame();
JScrollPane scroll;
gridPanels = new JPanel[sizeX][sizeY];
boardPanel = new JPanel();
legend = new JPanel();
consolePanel = new JPanel();
consoleOutput = new JTextArea(25,20);
consoleOutput.setEditable(false);
consoleOutput.setPreferredSize(new Dimension( 200,300));
consoleOutput.setAutoscrolls(true);
scroll = new JScrollPane(this.consoleOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
consolePanel.setBorder(BorderFactory.createLineBorder(Color.black));
consolePanel.add(consoleOutput);
consolePanel.add(scroll);
boardPanel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
boardPanel.setLayout(new GridLayout(sizeX,sizeY));
legend.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
legend.setPreferredSize( new Dimension(300,boardPanel.getHeight()));
PrintStream printStream = new PrintStream(new CustomOutputStream(consoleOutput));
for (Organizm org: legendOrgs)
{
pan = new JPanel();
colorBox = new JPanel();
panText = new JLabel();
pan.setMaximumSize(new Dimension(100,70));
pan.setAlignmentX(Component.LEFT_ALIGNMENT);
pan.setLayout(new FlowLayout(FlowLayout.LEADING));
colorBox.setBackground(org.getOrgColor());
colorBox.setAlignmentX(Component.LEFT_ALIGNMENT);
colorBox.setPreferredSize(new Dimension(30,30));
colorBox.setMaximumSize(new Dimension(30,30));
panText.setPreferredSize(new Dimension(100,15));
panText.setText(" - " + org.getName());
panText.setAlignmentX(Component.RIGHT_ALIGNMENT);
pan.add(colorBox);
pan.add(panText);
legend.add(pan);
}
legend.add(consolePanel);
for(int i=0; i<sizeY; i++)
{
for(int j=0; j<sizeX; j++)
{
gridPanels[i][j] = new JPanel();
if(organizmy[i][j]!=null)
gridPanels[i][j].setBackground(organizmy[i][j].getOrgColor());
else gridPanels[i][j].setBackground(Color.white);
boardPanel.add(gridPanels[i][j]);
}
}
System.setOut(printStream);
System.setErr(printStream);
frame.add(boardPanel);
frame.add(legend,BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Wirtualny świat");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
worldFrame = frame;
}
And here is my Custom output Stream class which is used to print everything i print via System.out.println to my text Area:
public class CustomOutputStream extends OutputStream
{
private final JTextArea textArea;
public CustomOutputStream(JTextArea textArea)
{
this.textArea = textArea;
}
#Override
public void write(int b)
{
textArea.append(String.valueOf((char)b));
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
Here is link to image what it looks like in GUI:
You need to remove this line from your code:
consoleOutput.setPreferredSize(new Dimension( 200,300));
Unfortunately, it prevents your JTextArea from being scrollable because you set static size to that element.
P.S. Stay away from Swing - there are better options in Java
It works for me.
import javax.swing.*;
public class Scrollin{
public static void main(String[] args){
JFrame frame = new JFrame("scrolling");
JTextArea area = new JTextArea(20, 20);
frame.add(new JScrollPane(area));
frame.setVisible(true);
frame.pack();
Timer t = new Timer( 150, evt->{
area.setCaretPosition( area.getDocument().getLength() );
area.append("word is born\n");
});
t.start();
}
}
As text is added, the window will scroll to the end provided the cursor is at the end of the document.
Maybe you can start with something as short as this to demonstrate your issue?

How to provide communicate from panel to frame in java

I have used cardlayout in my main class. I have added first panel in that cardlayout. I'm trying to hide the image in frame from first panel. So I have used interface like below code,
My Main class,
public class HomePage implements OptionMenuListener{
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Already there
frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(20, 20));
File file = new File(jsonFilePath);
if(!file.exists()) {
LoginPage login = new LoginPage();
contentPane.add(login, Constants.CARD_LOGIN);
ConfigueBranch configureBranch = new ConfigueBranch(false);
contentPane.add(configureBranch, Constants.CARD_CONFIGURE_BRANCH);
ConfigureSystem configureSystem = new ConfigureSystem(false);
contentPane.add(configureSystem, Constants.CARD_CONFIGURE_SYSTEM);
ConfigureCustomer configureCustomer = new ConfigureCustomer(false);
contentPane.add(configureCustomer, Constants.CARD_CONFIGURE_CUSTOMER);
}
MainPage mainPage = new MainPage(HomePage.this);
contentPane.add(mainPage, Constants.CARD_MAINPAGE);
// SettingsPage configureExpinContainer = new SettingsPage();
// contentPane.add(configureExpinContainer, Constants.CARD_SETTINGS_PAGE);
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(new EmptyBorder(50, 10, 10, 10));
Image image = MyUtil.loadImage("/logo.png"); // transform it
Image newimg = image.getScaledInstance(244, 80, java.awt.Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(newimg); // transform it back
JLabel label = new JLabel("", icon, JLabel.LEFT);
label.setFont(new java.awt.Font("Arial", Font.BOLD, 24));
label.setOpaque(true);
label.setForeground(Color.BLACK);
label.setBounds(0, 60, 300, 200);
buttonPanel.add(label);
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_START);
frame.pack();
frame.setSize(1000, 700);
centeredFrame(frame);
frame.setVisible(true);
frame.setResizable(false);
}
public static void centeredFrame(javax.swing.JFrame objFrame) {
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;
int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;
objFrame.setLocation(iCoordX, iCoordY);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
#Override
public void onMenuSelect(boolean isShow) {
}
}
I'm using for interface to provide communication to frame from panel,
public interface OptionMenuListener {
void onMenuSelect(boolean isShow);
}
I'm using the below panel in cardlayout,
public class MainPage extends JPanel{
JButton inputOutputFilesBtn, syncBtn, tsBtn, settingsBtn;
public MainPage(HomePage homePage){
homePage.onMenuSelect(true);
init();
}
public void init(){
JTabbedPane jtbExample = new JTabbedPane();
JPanel jplInnerPanel1 = createInnerPanel("No device connected");
jtbExample.addTab("Input and Output Files", jplInnerPanel1);
jtbExample.setSelectedIndex(0);
JPanel jplInnerPanel2 = createInnerPanel("No device connected");
jtbExample.addTab("Sync", jplInnerPanel2);
JPanel jplInnerPanel3;
if(configuredSystem.equalsIgnoreCase("Expeditors")) {
jplInnerPanel3 = createInnerPanel("No device connected");
jtbExample.addTab("TS", jplInnerPanel3);
}
JPanel jplInnerPanel4 = new SettingsPage();
jtbExample.addTab("Settings", jplInnerPanel4);
JPanel jplInnerPanel5 = new LogoutPage();
jtbExample.addTab("Logout", jplInnerPanel5);
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(620, 400));
this.add(jtbExample, BorderLayout.CENTER);
add(jtbExample);
}
protected JPanel createInnerPanel(String text) {
JPanel jplPanel = new JPanel();
JLabel jlbDisplay = new JLabel(text);
jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
jplPanel.setLayout(new GridLayout(1, 1));
jplPanel.add(jlbDisplay);
return jplPanel;
}
But i'm getting Cannot use this in a static context error in this below line
MainPage mainPage = new MainPage(HomePage.this);
Now i want to send some information from panel to the frame which have cardlayout. Could you please suggest me an idea to do this? Thanks in advance.
You can't use this in a static context like since this represent the class instance that is executing a method. Here, you are in a static context, so you don't have an instance.
private static void createAndShowGUI() {
MainPage mainPage = new MainPage(HomePage.this);
}
You either need to declare a variable
private static void createAndShowGUI() {
HomePage homePage = /*initialize or get it from somewhere */
MainPage mainPage = new MainPage(homePage);
}
Or move that logic outside the static context
private void createAndShowGUI() {
MainPage mainPage = new MainPage(HomePage.this);
}

JButton not responsive - have to click twice

I created a GUI using java swing and in a specific situation, the JButton is unresponsive and I have to click it twice. On the click, it takes the info in the textArea and sends it to a TextParser class to be parsed. If I type more stuff in the area after, and click the evaluateButton, it doesn't respond and I have to click it again to work. Does anyone know if this is a known bug or how I can fix this?
The code for the class is as follows.
/**
* Add the components to the GUI.
* #param pane - the pane for the GUI
*/
public static void addComponentsToPane(Container pane) {
pane.setLayout(new BorderLayout());
JPanel instructionsPanel = new JPanel();
JLabel instructions = new JLabel("Enter the email text below");
instructionsPanel.setBackground(Color.LIGHT_GRAY);
instructionsPanel.add(instructions);
pane.add(instructionsPanel, BorderLayout.NORTH);
JPanel textAreaPanel = new JPanel();
textAreaPanel.setBackground(Color.LIGHT_GRAY);
final JTextArea textArea = new JTextArea();
textArea.setBackground(Color.WHITE);
textArea.setMinimumSize(new Dimension(400,350));
textArea.setMaximumSize(new Dimension(400,350));
textArea.setPreferredSize(new Dimension(400,350));
textArea.setLineWrap(true);
Border border = BorderFactory.createLineBorder(Color.BLACK);
textArea.setBorder(border);
textArea.setMinimumSize(new Dimension(500, 200));
textArea.setFont(new Font("Serif", Font.PLAIN, 16));
textAreaPanel.add(textArea);
pane.add(textAreaPanel, BorderLayout.CENTER);
JPanel scoringPanel = new JPanel();
JButton evaluateButton = new JButton("Evaluate Email");
final JLabel scoreLabel = new JLabel("");
JButton uploadFileBtn = new JButton("Upload File");
JButton importTermsBtn = new JButton("Import Terms");
scoringPanel.add(evaluateButton);
scoringPanel.add(uploadFileBtn);
scoringPanel.add(importTermsBtn);
scoringPanel.add(scoreLabel);
pane.add(scoringPanel, BorderLayout.SOUTH);
evaluateButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
String email = textArea.getText();
TextParser textParser = new TextParser(email);
double score = textParser.parse();
scoreLabel.setText(score+"");
} catch (Exception ex) {
System.out.println(ex);
}
}
});
uploadFileBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
scoreLabel.setText("Feature not yet available.");
}
});
importTermsBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DatabaseInput d = new DatabaseInput();
d.main(null);
}
});
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("EmailGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setLocationRelativeTo(null);
frame.setPreferredSize(new Dimension(500,500));
frame.setTitle("Email Text Input");
frame.setResizable(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(screenSize.width, screenSize.height);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
My main method just calls createAndShowGUI(). I am new to StackOverflow so if I need to give more or less information in my post please let me know!
As Reimeus and Jason C said in the comments, I should have been using ActionListener which works perfectly.

Why can't I type in a JTextArea unless I resize the window?

I've placed a JTextArea within a JFrame and come across an issue where I can only type within my JTextArea unless I resize the window. How can I get JTextArea to let me type as soon as the window runs without having to resize it?
public class Frame extends JFrame{
public Note() {
this.setSize(new Dimension(1000, 1000));
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public JScrollPane createContent(){
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
this.add(scrollPane, BorderLayout.CENTER);
return null;
}
public static void main(String[] args) {
new Note();
Note mainWindow = new Note();
}
}
public class Note extends JFrame{
private static final long serialVersionUID = 1L;
public Note() {
createContent(); // add this line into your code.
int x = 400;
int y = 300;
this.setSize(new Dimension(x, y));
this.setTitle("Post-It Note");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public JScrollPane createContent(){
Color textAreaColor = new Color(248, 247, 235);
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBorder(null);
textArea.setBackground(textAreaColor);
scrollPane.setBackground(textAreaColor);
textArea.setMargin(new Insets(10, 15, 20, 20));
this.add(scrollPane, BorderLayout.CENTER);
return null;
}
public static void main(String[] args) {
new Note();
// mainWindow.createContent(); comment this line...
}
}
Note:
into your older code,
new Note(); // this one create 1-frame..
...
// Note mainWindow = new Note(); this one also create another frame so need to comment it
// mainWindow.createContent(); does not required because already this method called by constructor...

textarea not visible when adding scroll java

When i add an scroll to my textarea then the textarea isnt visible in the application:
Code:
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
final JTextArea textArea = new JTextArea();
textArea.setBounds(15, 112, 689, 310);
JScrollPane scrollPane = new JScrollPane( textArea );
panel.add( scrollPane );
Here is how to do what the code seems to be trying to do, using sizing hints for the text area, layouts and padding. Adjust numbers to need.
See further comments in code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ScrollingTextArea {
private JComponent panel = null;
ScrollingTextArea() {
initUI();
}
public void initUI() {
if (panel != null) {
return;
}
panel = new JPanel(new BorderLayout());
// adjust numbers to need
panel.setBorder(new EmptyBorder(32, 15, 32, 15));
// adjust rows & cols to need
final JTextArea textArea = new JTextArea(20,80);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane);
}
public JComponent getUI() {
return panel;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ScrollingTextArea o = new ScrollingTextArea();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Categories