Graphics artifacts appear here in JPanel [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In my custom JPanel appears graphic artifacts. I dont know why, because I have used super.paintComponent() in all of my custom paintings.
Here is how it looks on create.
2. And here is how it looks when I click on upgrades button.
And here is the code.
Menu
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontFormatException;
import java.awt.Graphics;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Menu {
static JFrame frame;
public static double scale = 1.5;
private static int WIDTH = 300, HEIGHT = 400;
public static Font fontTerminal;
private JPanel menuPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws IOException
*/
public Menu() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
fontTerminal = new Font("Consolas", 1, 1);
try {
fontTerminal = Font.createFont(Font.TRUETYPE_FONT, new File("res/terminal.ttf"));
} catch (FontFormatException e1) {
e1.printStackTrace();
}
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
menuPanel = new BackgroundPanel();
menuPanel.setLayout(null);
GridBagConstraints gbc_menuPanel = new GridBagConstraints();
gbc_menuPanel.fill = GridBagConstraints.BOTH;
gbc_menuPanel.gridx = 0;
gbc_menuPanel.gridy = 0;
frame.getContentPane().add(menuPanel, gbc_menuPanel);
GameButton newgameButton = new GameButton();
int ngButtWidth = 194, ngButtHeight = 71;
newgameButton.setBounds((frame.getWidth()/2) - (ngButtWidth/2), (frame.getHeight()/2) - (ngButtHeight/2), ngButtWidth, ngButtHeight);
newgameButton.setBackground( new Color(0,0,0,0));
menuPanel.add(newgameButton);
newgameButton.setLayout(new BorderLayout(0, 0));
JLabel newgameLbl = new GLabel("New Game", newgameButton, SwingConstants.CENTER);
newgameLbl.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
GameWindow gp = new GameWindow();
frame.setVisible(false);
}
});
newgameLbl.setFont(fontTerminal.deriveFont(19f));
newgameLbl.setForeground(new Color(0,0,0));
newgameButton.add(newgameLbl, BorderLayout.CENTER);
GameButton creditsButton = new GameButton();
creditsButton.setBackground(new Color(0, 0, 0, 0));
creditsButton.setBounds(56, 262, 194, 71);
menuPanel.add(creditsButton);
creditsButton.setLayout(new BorderLayout(0, 0));
JLabel creditsLabel = new GLabel("Credits", creditsButton, SwingConstants.CENTER);
creditsLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Credits credits = new Credits();
credits.setVisible(true);
}
});
creditsLabel.setForeground(Color.BLACK);
creditsLabel.setFont(null);
creditsLabel.setBackground(new Color(0, 0, 0, 0));
creditsLabel.setFont(fontTerminal.deriveFont(19f));
creditsButton.add(creditsLabel);
}
}
GameWindow
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.UIManager.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.JPanel;
import java.awt.Insets;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.GridLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
import java.awt.FlowLayout;
import javax.swing.JTable;
public class GameWindow {
private JFrame frame;
private Font fontTerminal;
private JPanel workerPanel1;
private GProgressbar Bar1;
private GameButton upgradeWorker1;
private JLabel upgradeWorker1_1;
private JPanel workerPanel2;
private GProgressbar Bar2;
private GameButton upgradeWorker2;
private JPanel workerPanel3;
private GProgressbar Bar3;
private GameButton upgradeWorker3;
private JPanel workerPanel4;
private GProgressbar Bar4;
private GameButton upgradeWorker4;
private JPanel upgradesPanel;
private JLabel upgradeWorker2_1;
private JLabel upgradeWorker3_1;
private JLabel upgradeWorker4_1;
private JPanel specialPanel;
private JPanel upgradesButton;
private JTable table, table2;
/**
* Create the application.
*/
public GameWindow() {
initialize();
this.frame.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
fontTerminal = Menu.fontTerminal;
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 306, 430);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
frame.addWindowListener( new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.setVisible(false);
frame.dispose();
Menu.frame.setVisible(true);
}});
GamePanel gamePanel = new GamePanel();
gamePanel.setLayout(null);
GridBagConstraints gbc_menuPanel = new GridBagConstraints();
gbc_menuPanel.fill = GridBagConstraints.BOTH;
gbc_menuPanel.gridx = 0;
gbc_menuPanel.gridy = 0;
frame.getContentPane().add(gamePanel, gbc_menuPanel);
upgradesPanel = new JPanel();
upgradesPanel.setBounds(23, 221, 253, 174);
upgradesPanel.setBackground(new Color(0,0,0,0));
gamePanel.add(upgradesPanel);
workerPanel1 = new JPanel();
workerPanel1.setBackground(new Color(0,0,0,0));
GridBagLayout gbl_workerPanel1 = new GridBagLayout();
gbl_workerPanel1.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel1.rowHeights = new int[]{36, 0};
gbl_workerPanel1.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel1.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel1.setLayout(gbl_workerPanel1);
Bar1 = new GProgressbar();
Bar1.setStringPainted(true);
GridBagConstraints gbc_Bar1 = new GridBagConstraints();
gbc_Bar1.fill = GridBagConstraints.BOTH;
gbc_Bar1.insets = new Insets(0, 0, 0, 5);
gbc_Bar1.gridx = 0;
gbc_Bar1.gridy = 0;
workerPanel1.add(Bar1, gbc_Bar1);
upgradeWorker1 = new GameButton();
GridBagConstraints gbc_upgradeWorker1 = new GridBagConstraints();
gbc_upgradeWorker1.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker1.gridx = 1;
gbc_upgradeWorker1.gridy = 0;
workerPanel1.add(upgradeWorker1, gbc_upgradeWorker1);
upgradeWorker1_1 = new GLabel("Upgrade", upgradeWorker1, SwingConstants.CENTER);
upgradeWorker1_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//upgrade worker 1
}
});
upgradeWorker1.setLayout(new BorderLayout(0, 0));
upgradeWorker1_1.setForeground(new Color(0,0,0));
upgradeWorker1.add(upgradeWorker1_1);
workerPanel2 = new JPanel();
workerPanel2.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{119, 118, 0};
gbl_panel.rowHeights = new int[]{36, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel2.setLayout(gbl_panel);
Bar2 = new GProgressbar();
Bar2.setStringPainted(true);
GridBagConstraints gbc_Bar2 = new GridBagConstraints();
gbc_Bar2.fill = GridBagConstraints.BOTH;
gbc_Bar2.insets = new Insets(0, 0, 0, 5);
gbc_Bar2.gridx = 0;
gbc_Bar2.gridy = 0;
workerPanel2.add(Bar2, gbc_Bar2);
upgradeWorker2 = new GameButton();
GridBagConstraints gbc_upgradeWorker2 = new GridBagConstraints();
gbc_upgradeWorker2.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker2.gridx = 1;
gbc_upgradeWorker2.gridy = 0;
workerPanel2.add(upgradeWorker2, gbc_upgradeWorker2);
upgradeWorker2.setLayout(new BorderLayout(0, 0));
upgradeWorker2_1 = new GLabel("Upgrade", upgradeWorker2, SwingConstants.CENTER);
upgradeWorker2_1.setForeground(Color.BLACK);
upgradeWorker2_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//upgrade worker 2
}
});
upgradeWorker2.setLayout(new BorderLayout(0, 0));
upgradeWorker2_1.setFont(fontTerminal.deriveFont(15f));
upgradeWorker2.add(upgradeWorker2_1);
workerPanel3 = new JPanel();
workerPanel3.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_workerPanel3 = new GridBagLayout();
gbl_workerPanel3.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel3.rowHeights = new int[]{36, 0};
gbl_workerPanel3.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel3.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel3.setLayout(gbl_workerPanel3);
Bar3 = new GProgressbar();
Bar3.setStringPainted(true);
GridBagConstraints gbc_Bar3 = new GridBagConstraints();
gbc_Bar3.fill = GridBagConstraints.BOTH;
gbc_Bar3.insets = new Insets(0, 0, 0, 5);
gbc_Bar3.gridx = 0;
gbc_Bar3.gridy = 0;
workerPanel3.add(Bar3, gbc_Bar3);
upgradeWorker3 = new GameButton();
GridBagConstraints gbc_upgradeWorker3 = new GridBagConstraints();
gbc_upgradeWorker3.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker3.gridx = 1;
gbc_upgradeWorker3.gridy = 0;
workerPanel3.add(upgradeWorker3, gbc_upgradeWorker3);
upgradeWorker3.setLayout(new BorderLayout(0, 0));
upgradeWorker3_1 = new GLabel("Upgrade", upgradeWorker3, SwingConstants.CENTER);
upgradeWorker3.add(upgradeWorker3_1);
workerPanel4 = new JPanel();
workerPanel4.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_workerPanel4 = new GridBagLayout();
gbl_workerPanel4.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel4.rowHeights = new int[]{36, 0};
gbl_workerPanel4.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel4.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel4.setLayout(gbl_workerPanel4);
Bar4 = new GProgressbar();
Bar4.setStringPainted(true);
GridBagConstraints gbc_Bar4 = new GridBagConstraints();
gbc_Bar4.fill = GridBagConstraints.BOTH;
gbc_Bar4.insets = new Insets(0, 0, 0, 5);
gbc_Bar4.gridx = 0;
gbc_Bar4.gridy = 0;
workerPanel4.add(Bar4, gbc_Bar4);
upgradeWorker4 = new GameButton();
GridBagConstraints gbc_upgradeWorker4 = new GridBagConstraints();
gbc_upgradeWorker4.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker4.gridx = 1;
gbc_upgradeWorker4.gridy = 0;
workerPanel4.add(upgradeWorker4, gbc_upgradeWorker4);
upgradeWorker4.setLayout(new BorderLayout(0, 0));
upgradeWorker4_1 = new GLabel("Upgrade", upgradeWorker4, SwingConstants.CENTER);
upgradeWorker4.add(upgradeWorker4_1);
GroupLayout gl_upgradesPanel = new GroupLayout(upgradesPanel);
gl_upgradesPanel.setHorizontalGroup(
gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_upgradesPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addComponent(workerPanel1, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel2, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel3, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel4, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE))
.addContainerGap(15, Short.MAX_VALUE))
);
gl_upgradesPanel.setVerticalGroup(
gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_upgradesPanel.createSequentialGroup()
.addContainerGap()
.addComponent(workerPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
upgradesPanel.setLayout(gl_upgradesPanel);
specialPanel = new JPanel();
specialPanel.setBackground(new Color(0,0,0,0.2f));
specialPanel.setBounds(6, 6, 288, 203);
gamePanel.add(specialPanel);
specialPanel.setLayout(null);
String[] columnNames = {"Upgrades", ""};
Object[][] data =
{
{"Vozík +2", "2000$"},
{"Kalhoty +3", "15000$"},
{"Šperháky +4", "50000$"},
{"Auto *2", "200000$"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames){
#Override
public boolean isCellEditable(int row, int column) {
if(column != 1) return false;
else return true;
}
};
table = new JTable( model );
Action upgradeMultiplier = new AbstractAction()
{
int count = 0;
public void actionPerformed(ActionEvent e)
{
/*
*
JTable table = (JTable)e.getSource();
int modelRow = Integer.valueOf( e.getActionCommand() );
String sPrice = (String) table.getModel().getValueAt(modelRow, 1);
int price = Integer.parseInt(sPrice.substring(0,sPrice.length()-1));
String sMultip = (String) table.getModel().getValueAt(modelRow, 0);
if(sMultip.lastIndexOf("*") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("*")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.multiplyMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
} else if(sMultip.lastIndexOf("+") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("+")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.plusMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
}
progressBar1.setString(worker.getProfit()+"$");
lblMultiplier.setText(worker.multiplier+"x");
*
*/
}
};
ButtonColumn buttonColumn = new ButtonColumn(table, upgradeMultiplier , 1);
buttonColumn.setMnemonic(KeyEvent.VK_D);
table.setBounds(8, 55, 272, 142);
specialPanel.add(table);
String[] columnNames2 = {"Upgrades", ""};
Object[][] data2 =
{
{"Special +1", "2000$"},
{"Special +3", "15000$"},
{"Special +4", "50000$"},
{"SPecial *2", "200000$"},
};
DefaultTableModel model2 = new DefaultTableModel(data2, columnNames2){
#Override
public boolean isCellEditable(int row, int column) {
if(column != 1) return false;
else return true;
}
};
table2 = new JTable( model2 );
Action specialUpgrade = new AbstractAction()
{
int count = 0;
public void actionPerformed(ActionEvent e)
{
/*
*
JTable table = (JTable)e.getSource();
int modelRow = Integer.valueOf( e.getActionCommand() );
String sPrice = (String) table.getModel().getValueAt(modelRow, 1);
int price = Integer.parseInt(sPrice.substring(0,sPrice.length()-1));
String sMultip = (String) table.getModel().getValueAt(modelRow, 0);
if(sMultip.lastIndexOf("*") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("*")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.multiplyMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
} else if(sMultip.lastIndexOf("+") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("+")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.plusMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
}
progressBar1.setString(worker.getProfit()+"$");
lblMultiplier.setText(worker.multiplier+"x");
*
*/
}
};
ButtonColumn buttonColumn2 = new ButtonColumn(table, specialUpgrade , 1);
buttonColumn2.setMnemonic(KeyEvent.VK_D);
table2.setBounds(8, 55, 272, 142);
table2.setVisible(false);
specialPanel.add(table2);
upgradesButton = new GameButton();
upgradesButton.setBounds(8, 6, 121, 43);
specialPanel.add(upgradesButton);
upgradesButton.setBackground(new Color(0,0,0,0));
upgradesButton.setLayout(new BorderLayout(0, 0));
GLabel label4 = new GLabel("Upgrades", (GameButton) upgradesButton, SwingConstants.CENTER);
label4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
table.setVisible(true);
table2.setVisible(false);
}
});
upgradesButton.add(label4);
JPanel specialsButton = new GameButton();
specialsButton.setBounds(159, 6, 121, 43);
specialPanel.add(specialsButton);
specialsButton.setBackground(new Color(0,0,0,0));
specialsButton.setLayout(new BorderLayout(0, 0));
GLabel lblSpecials = new GLabel("Specials", (GameButton) specialsButton, SwingConstants.CENTER);
lblSpecials.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
table.setVisible(false);
table2.setVisible(true);
}
});
specialsButton.add(lblSpecials);
}
}
GamePanel extends JPanel
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
final BufferedImage image = ImageIO.read(new File("./res/gameBackground.jpg"));
g.drawImage(image, 0, 0, 300, 400, this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JProgressBar;
public class GProgressbar extends JProgressBar {
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
GameButton extends JPanel
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class GameButton extends JPanel {
private static final long serialVersionUID = 1L;
boolean entered = false;
boolean pressed = false;
GameButton that = this;
public GameButton() {
this.setOpaque(true);
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
that.entered = true;
that.repaint();
}
#Override
public void mouseExited(MouseEvent e) {
that.entered = false;
that.repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
that.pressed = true;
that.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
that.pressed = false;
that.repaint();
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0,0,0,0));
g.fillRect(0, 0, WIDTH, HEIGHT);
if(!entered) {
try {
final BufferedImage image = ImageIO.read(new File("./res/button.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
} else if(pressed){
try {
final BufferedImage image = ImageIO.read(new File("./res/buttonpressed.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
} else {
try {
final BufferedImage image = ImageIO.read(new File("./res/buttonactive.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
GLabel extends JLabel
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class GLabel extends JLabel{
GameButton that;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0,0,0,0));
g.fillRect(0, 0, WIDTH, HEIGHT);
}
public GLabel(String s, GameButton that, int center) {
this.setText(s);
this.that = that;
this.setHorizontalAlignment(center);
setForeground(Color.BLACK);
setFont(Menu.fontTerminal.deriveFont(15f));
setBackground(new Color(0,0,0,0));
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
that.entered = true;
that.repaint();
}
#Override
public void mouseExited(MouseEvent e) {
that.entered = false;
that.repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
that.pressed = true;
that.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
that.pressed = false;
that.repaint();
}
});
}
}

I want to make the background fully transparent.
Then all you need is:
component.setOpaque( false );
If you need partial transparency of the background then you will get artifacts as you will be breaking the painting contract with Swing components and the opaque property. Check out
Backgrounds With Transparency for more information and solutions to this problem.

Looks like you set a fully transparent JPanel for 'workerPanel1'.
As such, the background is showing behind the JPanel.
Instead of:
workerPanel1.setBackground(new Color(0,0,0,0))
use:
workerPanel1.setBackground(new Color(0,0,0))
(which is the same as: new Color(0,0,0,255))
Edit:
If you wish to keep a transparent panel, you can do so with JPanel#setOpaque(false).
When opaque is false, the panel does not draw its background at all and you will have to keep in mind whatever is displayed behind that panel.
Currently, you have two buttons showing behind it, so you might setVisible(false) them or remove them while this panel is active.

Related

How to Apply the background gradient of a JFrame

I want to apply gradient in JFrame.
I try my best but some problem I faced.
Please help me.
In following code.
I want to set pnlMain as BorderLayout but I used gradient paint so that BorderLayout is not set properly.
And also graphics2d.fillRect(0, 0, width, height) not fill whole pnlMain JPanel.
So please give some suggestion for it.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Frame extends javax.swing.JFrame {
// Getter & Setter
public Frame() {
setExtendedState(Frame.MAXIMIZED_BOTH);
setTitle("Gradient");
initComponents();
}
private void initComponents() {
menu_bar = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
pnlMain = new JPanel();
pnlSuper = new JPanel(new BorderLayout(15,15))
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Point point1 = new Point(10, 10);
Point point2 = new Point(
getWidth() - 10,
getHeight() - 10);
final GradientPaint gp = new GradientPaint(
point1, Color.YELLOW,
point2, new Color(255, 225, 100),
true);
final Graphics2D g2 = (Graphics2D) g;
g2.setPaint(gp);
g.fillRect(0, 0, getWidth(), getHeight());
}
};
pnlSuper.setBorder(new EmptyBorder(30,30,30,30));
pnlMain.setLayout(new BorderLayout());
pnlMain.setOpaque(false);
pnlImage = new JPanel(new BorderLayout());
pnlFooter = new JPanel(new GridLayout(1,2));
footerBox = Box.createVerticalBox();
lblBackground = new JLabel("Image");
lblBackground.setFont(new java.awt.Font("URW Bookman L", 0, 20));
lblAddress = new JLabel();
lblContactNumber = new JLabel();
lblBackground.setHorizontalAlignment(SwingConstants.CENTER);
lblAddress.setText("Address");
lblAddress.setAlignmentX(JLabel.CENTER_ALIGNMENT);
lblAddress.setFont(new java.awt.Font("URW Bookman L", 0, 20)); // NOI18N
footerBox.add(lblAddress);
lblContactNumber.setText("Contact Number ");
lblContactNumber.setFont(new java.awt.Font("URW Bookman L", 0, 20)); // NOI18N
lblContactNumber.setAlignmentX(JLabel.CENTER_ALIGNMENT);
footerBox.add(lblContactNumber);
pnlFooter.add(footerBox);
pnlImage.add(lblBackground);
pnlMain.add(pnlImage, BorderLayout.CENTER);
pnlMain.add(pnlFooter, BorderLayout.SOUTH);
pnlSuper.add(pnlMain);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenu1.setFont(new java.awt.Font("URW Bookman L", 0, 18));
jMenu1.setPreferredSize(new java.awt.Dimension(45, 25));
menu_bar.add(jMenu1);
setJMenuBar(menu_bar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addGap(0, 1352, Short.MAX_VALUE).addComponent(pnlSuper));
layout.setVerticalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGap(0, 757, Short.MAX_VALUE).addComponent(pnlSuper));
pack();
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}
private javax.swing.JMenu jMenu1;
private javax.swing.JToggleButton jToggleButton1;
private javax.swing.JMenuBar menu_bar;
private JLabel lblBackground;
private JPanel pnlMain;
private JPanel pnlFooter;
private JPanel pnlImage;
private JLabel lblAddress;
private JLabel lblContactNumber;
private Box footerBox;
private JPanel pnlSuper;
}
Thanq For Reading
In order to see the BG, all the components on top of it must be transparent. So this:
pnlImage = new JPanel(new BorderLayout());
pnlFooter = new JPanel(new GridLayout(1,2));
Should be:
pnlImage = new JPanel(new BorderLayout());
pnlImage.setOpaque(false);
pnlFooter = new JPanel(new GridLayout(1,2));
pnlFooter.setOpaque(false);

JProgressBar Gets Squeezed/ Resizes Improperly

I'm using a JProgressBar on my Swing gui:
When I minimize the window while it's updating with progressBar.setValue() it will squeeze like this:
Note that resizing or similar doesn't fix it.
Why does it happen and how to prevent it? What causes it? I want the progressbar to stay the same size like in the first image.
I'm using the GridBagLayout.
Code to reproduce:
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.JProgressBar;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
#SuppressWarnings("serial")
public class ProgressBarSqueezeFixedExample extends JFrame
{
public ProgressBarSqueezeFixedExample()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 0, 0, 0 };
gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0, 0 };
gridBagLayout.columnWeights = new double[] { 1.0, 0.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 1.0,
Double.MIN_VALUE };
getContentPane().setLayout(gridBagLayout);
JProgressBar progressBar = new JProgressBar();
JTextArea textArea = new JTextArea();
JButton btnRun = new JButton("Run");
setPreferredSize(new Dimension(200, 200));
btnRun.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
SwingWorker<String, String> worker = new SwingWorker<String, String>()
{
#Override
protected String doInBackground() throws Exception
{
for (int i = 0; i < 10001; i++)
{
try
{
Thread.sleep(1);
} catch (InterruptedException e)
{
e.printStackTrace();
}
progressBar.setValue(i);
progressBar.setString(i + " %");
textArea.append(i + System.lineSeparator());
}
return null;
}
};
worker.execute();
}
});
GridBagConstraints gbc_btnRun = new GridBagConstraints();
gbc_btnRun.insets = new Insets(0, 0, 5, 5);
gbc_btnRun.gridx = 0;
gbc_btnRun.gridy = 0;
getContentPane().add(btnRun, gbc_btnRun);
JLabel lblProgress = new JLabel("Progress");
GridBagConstraints gbc_lblProgress = new GridBagConstraints();
gbc_lblProgress.insets = new Insets(0, 0, 5, 5);
gbc_lblProgress.gridx = 0;
gbc_lblProgress.gridy = 1;
getContentPane().add(lblProgress, gbc_lblProgress);
progressBar.setMaximum(10000);
progressBar.setStringPainted(true);
progressBar.setMinimumSize(progressBar.getPreferredSize()); // Fixes squeezing issues
GridBagConstraints gbc_progressBar = new GridBagConstraints();
gbc_progressBar.insets = new Insets(0, 0, 5, 5);
gbc_progressBar.gridx = 0;
gbc_progressBar.gridy = 2;
getContentPane().add(progressBar, gbc_progressBar);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_progressBar.fill=GridBagConstraints.HORIZONTAL; // Alternate fix
gbc_scrollPane.gridwidth = 2;
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 3;
getContentPane().add(scrollPane, gbc_scrollPane);
scrollPane.setViewportView(textArea);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new ProgressBarSqueezeFixedExample();
}
}
The resizing of the gui and squeezing the progressbar has to to with the textArea append() how it seems.
Use GridBagConstraints#fill property that is used when the component's display area is larger than the component's requested size. It determines whether to resize the component.
gbc_progressBar.fill=GridBagConstraints.HORIZONTAL;
Note: There is no need to create multiple instance of GridBagConstraints. you can achieve same thing using single object as well.
Read more about How to Use GridBagLayout and have a look at the example.

Set color of FillRect() using value of scrollbar or spinner

I have created two JPanels and added them on to a mainpanel, then added this JPanel on the JFrame. I am unable to set the color of rectangle using changing value of spinner or scrollbar. If any one have solution then help me for this paroblem.
TestColorFrame.java
import java.awt.BorderLayout;
import java.awt.GridLayout;import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.metal.MetalLookAndFeel;
import com.swing.Myframe;
public class TestColorFrame extends JFrame {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JFrame f = new JFrame();
JPanel Mainpanel = new JPanel(new GridLayout(2, 1));
ColorPanel1 p = new ColorPanel1();
ColorPanel2 p1 = new ColorPanel2();
//f.getContentPane().setLayout(new BorderLayout() );
f.add(Mainpanel);
Mainpanel.add(p);
Mainpanel.add(p1,BorderLayout.SOUTH);
f.setVisible(true);
f.setResizable(false);
f.setSize(500,500);
f.setTitle("My Color Frame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
ColorPanel1.java
import java.awt.Adjustable;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ColorPanel1 extends JPanel implements
AdjustmentListener,ChangeListener {
ColorPanel2 p;
private JLabel jLabelred,jLabelgreen,jLabelblue;
public JScrollBar jRedScrollbar,jGreenScollbar,jBlueScrollbar;
//private JTextField jRedtext,jGreentext,jBluetext;
protected JSpinner jRed, jGreen, jBlue;
ColorPanel2 color2;
public Color current;
public ColorPanel1() {
setLayout(new GridLayout(3, 3,60,60));
jLabelred = new JLabel("RED");
add(jLabelred);
SpinnerModel spinnerModel = new SpinnerNumberModel(100, 0, 255, 1) ;
jRed = new JSpinner(spinnerModel);
add(jRed);
jRedScrollbar = new JScrollBar(JScrollBar.HORIZONTAL, 100, 40, 0, 255);
add(jRedScrollbar);
jLabelgreen = new JLabel("GREEN");
add(jLabelgreen);
SpinnerModel spinnerModel1 = new SpinnerNumberModel(200, 0, 255, 1);
jGreen = new JSpinner(spinnerModel1);
add(jGreen);
jGreenScollbar = new JScrollBar(JScrollBar.HORIZONTAL, 200, 4, 0, 255);
add(jGreenScollbar);
jLabelblue = new JLabel("BLUE");
add(jLabelblue);
SpinnerModel spinnerModel2 = new SpinnerNumberModel(50, 0, 255, 1);
jBlue = new JSpinner(spinnerModel2);
add(jBlue);
jBlueScrollbar = new JScrollBar(JScrollBar.HORIZONTAL, 50, 40, 0, 255);
add(jBlueScrollbar);
jRedScrollbar.addAdjustmentListener(this);
jBlueScrollbar.addAdjustmentListener(this);
jGreenScollbar.addAdjustmentListener(this);
spinnerModel.addChangeListener(this);
spinnerModel1.addChangeListener(this);
spinnerModel2.addChangeListener(this);
}
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
int r = jRedScrollbar.getValue();
int g = jGreenScollbar.getValue();
int b = jBlueScrollbar.getValue();
jRed.setValue(jRedScrollbar.getValue());
jBlue.setValue(jBlueScrollbar.getValue());
jGreen.setValue(jGreenScollbar.getValue());
}
#Override
public void stateChanged(ChangeEvent e) {
SpinnerModel spinnerModel = jRed.getModel();
if (spinnerModel instanceof SpinnerModel) {
jRedScrollbar.setValue((int) spinnerModel.getValue());
}
SpinnerModel spinnerModel1 = jGreen.getModel();
if(spinnerModel1 instanceof SpinnerModel) {
jGreenScollbar.setValue((int) jGreen.getValue());
}
SpinnerModel spinnerModel2 = jBlue.getModel();
if(spinnerModel2 instanceof SpinnerModel) {
jBlueScrollbar.setValue((int) jBlue.getValue());
}
}
}
ColorPanel2.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
public class ColorPanel2 extends JPanel {
private JColorChooser colorchooser;
ColorPanel1 color=new ColorPanel1();
public ColorPanel2() {
setLayout(new BorderLayout());
}
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
int r = (int) color.jRed.getValue();
int g = (int) color.jGreen.getValue();
int b = (int) color.jBlue.getValue();
graphics.setColor(new Color(r,g,b));
graphics.fillRect(100, 50, 300, 150);
}
}
You need a class member Color in your ColorPanel class. And also have a setter for it. In the setter, call repaint(). In your paintComponent method, use the class member Color instead of creating a create a new Color(). Something like
public class ColorPanel extends JPanel {
private Color color;
public void setColor(Color color) {
this.color = color;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
...
g.setColor(color);
}
}
When you setColor on on the ColorPanel passing the new color, the panel will be repainted with the updated color.
Here's a complete example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestColorFrame {
private static final int DEFAULT_VALUE = 100;
private JSpinner rSpinner;
private JSpinner gSpinner;
private JSpinner bSpinner;
private ColorPanel colorPanel;
public TestColorFrame() {
colorPanel = new ColorPanel();
rSpinner = createRGBSpinner();
gSpinner = createRGBSpinner();
bSpinner = createRGBSpinner();
JPanel spinnerPanel = new JPanel();
spinnerPanel.add(new JLabel("R"));
spinnerPanel.add(rSpinner);
spinnerPanel.add(new JLabel("G"));
spinnerPanel.add(gSpinner);
spinnerPanel.add(new JLabel("B"));
spinnerPanel.add(bSpinner);
JFrame frame = new JFrame("Color Spinners");
frame.add(colorPanel);
frame.add(spinnerPanel, BorderLayout.NORTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JSpinner createRGBSpinner() {
SpinnerNumberModel model = new SpinnerNumberModel(DEFAULT_VALUE, 0, 255, 1);
JSpinner spinner = new JSpinner(model);
spinner.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
int[] values = getModelValues();
colorPanel.setColor(new Color(values[0], values[1], values[2]));
}
});
return spinner;
}
private int[] getModelValues() {
int r = (Integer)((SpinnerNumberModel)rSpinner.getModel()).getValue();
int g = (Integer)((SpinnerNumberModel)gSpinner.getModel()).getValue();
int b = (Integer)((SpinnerNumberModel)bSpinner.getModel()).getValue();
return new int[] {r, g, b};
}
class ColorPanel extends JPanel {
private Color color = new Color(DEFAULT_VALUE, DEFAULT_VALUE, DEFAULT_VALUE);
public void setColor(Color color) {
this.color = color;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestColorFrame();
}
});
}
}
Aside, you should probably look into using a JSlider, which seems more natural than using a JScrollBar for value adjustment
UPDATE
With refactor
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestColorFrame extends JFrame {
public static void main(String[] args) {
JFrame f = new JFrame();
JPanel Mainpanel = new JPanel(new GridLayout(2, 1));
ColorPanel2 p1 = new ColorPanel2();
ColorPanel1 p = new ColorPanel1(p1);
//f.getContentPane().setLayout(new BorderLayout() );
f.add(Mainpanel);
Mainpanel.add(p);
Mainpanel.add(p1, BorderLayout.SOUTH);
f.setVisible(true);
f.setResizable(false);
f.setSize(500, 500);
f.setTitle("My Color Frame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class ColorPanel1 extends JPanel implements
AdjustmentListener, ChangeListener {
private JLabel jLabelred, jLabelgreen, jLabelblue;
public JScrollBar jRedScrollbar, jGreenScollbar, jBlueScrollbar;
//private JTextField jRedtext,jGreentext,jBluetext;
protected JSpinner jRed, jGreen, jBlue;
ColorPanel2 colorPanel2;
public Color current;
public ColorPanel1(ColorPanel2 colorPanel2) {
this.colorPanel2 = colorPanel2;
setLayout(new GridLayout(3, 3, 60, 60));
jLabelred = new JLabel("RED");
add(jLabelred);
SpinnerModel spinnerModel = new SpinnerNumberModel(100, 0, 255, 1);
jRed = new JSpinner(spinnerModel);
add(jRed);
jRedScrollbar = new JScrollBar(JScrollBar.HORIZONTAL, 100, 40, 0, 255);
add(jRedScrollbar);
jLabelgreen = new JLabel("GREEN");
add(jLabelgreen);
SpinnerModel spinnerModel1 = new SpinnerNumberModel(200, 0, 255, 1);
jGreen = new JSpinner(spinnerModel1);
add(jGreen);
jGreenScollbar = new JScrollBar(JScrollBar.HORIZONTAL, 200, 4, 0, 255);
add(jGreenScollbar);
jLabelblue = new JLabel("BLUE");
add(jLabelblue);
SpinnerModel spinnerModel2 = new SpinnerNumberModel(50, 0, 255, 1);
jBlue = new JSpinner(spinnerModel2);
add(jBlue);
jBlueScrollbar = new JScrollBar(JScrollBar.HORIZONTAL, 50, 40, 0, 255);
add(jBlueScrollbar);
jRedScrollbar.addAdjustmentListener(this);
jBlueScrollbar.addAdjustmentListener(this);
jGreenScollbar.addAdjustmentListener(this);
spinnerModel.addChangeListener(this);
spinnerModel1.addChangeListener(this);
spinnerModel2.addChangeListener(this);
}
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
int r = jRedScrollbar.getValue();
int g = jGreenScollbar.getValue();
int b = jBlueScrollbar.getValue();
jRed.setValue(jRedScrollbar.getValue());
jBlue.setValue(jBlueScrollbar.getValue());
jGreen.setValue(jGreenScollbar.getValue());
setNewPanelColor();
}
#Override
public void stateChanged(ChangeEvent e) {
SpinnerModel spinnerModel = jRed.getModel();
if (spinnerModel instanceof SpinnerModel) {
jRedScrollbar.setValue((int) spinnerModel.getValue());
setNewPanelColor();
}
SpinnerModel spinnerModel1 = jGreen.getModel();
if (spinnerModel1 instanceof SpinnerModel) {
jGreenScollbar.setValue((int) jGreen.getValue());
setNewPanelColor();
}
SpinnerModel spinnerModel2 = jBlue.getModel();
if (spinnerModel2 instanceof SpinnerModel) {
jBlueScrollbar.setValue((int) jBlue.getValue());
setNewPanelColor();
}
}
public void setNewPanelColor() {
int r = (int)((SpinnerModel)jRed.getModel()).getValue();
int g = (int)((SpinnerModel)jGreen.getModel()).getValue();
int b = (int)((SpinnerModel)jBlue.getModel()).getValue();
colorPanel2.setColor(new Color(r, g, b));
}
}
class ColorPanel2 extends JPanel {
private JColorChooser colorchooser;
private Color color = new Color(100, 200, 50);
public ColorPanel2() {
setLayout(new BorderLayout());
}
public void setColor(Color color) {
this.color = color;
repaint();
}
#Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.setColor(color);
graphics.fillRect(100, 50, 300, 150);
}
}

Picture slideshow with fade in/fade out on a JPanel

So, my problem here is that I want a JPanel on my JFrame to function as a slideshow where 4 different pictures fade in and fade out.
I'm using the Scalr library to resize, everything works except with I use run();
As soon as I use that my window won't open and it get stuck with just the text running through. Is there anyway to make this panel have it's own way? Just sitting in the corner and doing his own thing?
A basic explanation would be lovely because I'm very new with Threads and everything around that.
Thank you!
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JTextArea;
import javax.swing.JList;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.AbstractAction;
import se.lundell.team.Team;
import javax.swing.ListSelectionModel;
import javax.swing.Action;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import org.imgscalr.Scalr;
public class MainWindow {
private JFrame frame;
private JTextField textField;
private final ButtonGroup buttonGroup = new ButtonGroup();
protected DefaultListModel<Team> teamList;
private JList list;
private JTextArea textArea;
private final Action addTeamAction = new AddTeamAction();
private final Action removeTeamAction = new RemoveTeamAction();
private final Action clearListAction = new ClearListAction();
private final Action generateAction = new GenerateAction();
public ArrayList<Team> teamA;
public ArrayList<Team> teamB;
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 957, 642);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
JSplitPane splitPane = new JSplitPane();
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
JPanel leftPanel = new JPanel();
splitPane.setLeftComponent(leftPanel);
GridBagLayout gbl_leftPanel = new GridBagLayout();
gbl_leftPanel.columnWidths = new int[]{0, 0};
gbl_leftPanel.rowHeights = new int[]{0, 0, 41, 66, 0, 0};
gbl_leftPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_leftPanel.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
leftPanel.setLayout(gbl_leftPanel);
teamList = new DefaultListModel<Team>();
teamList.addElement(new Team("team1"));
teamList.addElement(new Team("team2"));
teamList.addElement(new Team("team3"));
teamList.addElement(new Team("team4"));
list = new JList();
list.setModel(teamList);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 0, 5, 0);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
leftPanel.add(list, gbc_list);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 0;
gbc_textField.gridy = 1;
leftPanel.add(textField, gbc_textField);
textField.setColumns(10);
JPanel btnPanel = new JPanel();
GridBagConstraints gbc_btnPanel = new GridBagConstraints();
gbc_btnPanel.insets = new Insets(0, 0, 5, 0);
gbc_btnPanel.fill = GridBagConstraints.VERTICAL;
gbc_btnPanel.gridx = 0;
gbc_btnPanel.gridy = 2;
leftPanel.add(btnPanel, gbc_btnPanel);
btnPanel.setLayout(new GridLayout(0, 3, 0, 0));
JButton btnAdd = new JButton("Add");
btnAdd.setAction(addTeamAction);
buttonGroup.add(btnAdd);
btnPanel.add(btnAdd);
JButton btnRemove = new JButton("Remove");
btnRemove.setAction(removeTeamAction);
buttonGroup.add(btnRemove);
btnPanel.add(btnRemove);
JButton btnClear = new JButton("Clear");
btnClear.setAction(clearListAction);
buttonGroup.add(btnClear);
btnPanel.add(btnClear);
JPanel generatePanel = new JPanel();
generatePanel.setPreferredSize(new Dimension(10, 20));
GridBagConstraints gbc_generatePanel = new GridBagConstraints();
gbc_generatePanel.fill = GridBagConstraints.BOTH;
gbc_generatePanel.insets = new Insets(0, 0, 5, 0);
gbc_generatePanel.gridx = 0;
gbc_generatePanel.gridy = 3;
leftPanel.add(generatePanel, gbc_generatePanel);
generatePanel.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnGenerate = new JButton("Generate");
btnGenerate.setAction(generateAction);
btnGenerate.setFont(new Font("Tahoma", Font.PLAIN, 26));
generatePanel.add(btnGenerate);
PictureFrame canvasPanel = new PictureFrame();
GridBagConstraints gbc_canvasPanel = new GridBagConstraints();
gbc_canvasPanel.fill = GridBagConstraints.BOTH;
gbc_canvasPanel.gridx = 0;
gbc_canvasPanel.gridy = 4;
leftPanel.add(canvasPanel, gbc_canvasPanel);
JPanel rightPanel = new JPanel();
splitPane.setRightComponent(rightPanel);
rightPanel.setLayout(new BorderLayout(0, 0));
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setAlignmentY(Component.BOTTOM_ALIGNMENT);
textArea.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(textArea, BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar();
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu mnMenu = new JMenu("Menu");
menuBar.add(mnMenu);
JMenuItem mntmLoad = new JMenuItem("Load");
mnMenu.add(mntmLoad);
JMenuItem mntmSave = new JMenuItem("Save");
mnMenu.add(mntmSave);
JMenuItem mntmExit = new JMenuItem("Exit");
mnMenu.add(mntmExit);
frame.setVisible(true);
}
protected JList getList() {
return list;
}
private class AddTeamAction extends AbstractAction {
public AddTeamAction() {
putValue(NAME, "Add");
putValue(SHORT_DESCRIPTION, "Add team to list.");
}
public void actionPerformed(ActionEvent e) {
if(!textField.getText().isEmpty()) {
teamList.addElement(new Team(textField.getText()));
textField.setText("");
} else {
JOptionPane.showMessageDialog(null, "You need to enter a name.", "Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
private class RemoveTeamAction extends AbstractAction {
public RemoveTeamAction() {
putValue(NAME, "Remove");
putValue(SHORT_DESCRIPTION, "Remove the selected team.");
}
public void actionPerformed(ActionEvent e) {
int choice = getList().getSelectedIndex();
teamList.removeElementAt(choice);
}
}
private class ClearListAction extends AbstractAction {
public ClearListAction() {
putValue(NAME, "Clear");
putValue(SHORT_DESCRIPTION, "Clear the list and the tournament window");
}
public void actionPerformed(ActionEvent e) {
teamList.clear();
textArea.setText("");
teamA.clear();
teamB.clear();
}
}
private class GenerateAction extends AbstractAction {
public GenerateAction() {
putValue(NAME, "Generate");
putValue(SHORT_DESCRIPTION, "Generate a new Round Robin tournament.");
teamA = new ArrayList<Team>();
teamB = new ArrayList<Team>();
}
public void actionPerformed(ActionEvent e) {
rotateSchedual();
}
private void rotateSchedual(){
if(teamList.getSize() % 2 == 0) {
start();
} else {
teamList.addElement(new Team("Dummy"));
start();
}
}
protected void start() {
for(int i = 0; i < teamList.getSize(); i++) {
teamA.add(teamList.getElementAt(i));
}
// Split the arrayList to two and invert.
splitSchedual();
int length = teamA.size();
System.out.println(teamB.size());
System.out.println(length);
printSchedual(length);
//remove index 0 from teamA and add index 0 from teamB first in the list. then add the first team back in again.
for(int i = 0;i <= (length - 1); i++){
//copy index 0 and add it to the other array.
//remove index 0 in both arrays.
teamA.add(1, teamB.get(0));
teamB.remove(0);
teamB.add(teamA.get(length));
teamA.remove(length);
printSchedual(length);
}
}
//Splits the array in to two arrays.
protected void splitSchedual(){
int length = teamA.size();
for(int i = (length/2);i < (length);i++){
teamB.add(teamA.get(i));
}
for(int i = (length - 1);i >= (length/2); i--) {
teamA.remove(i);
}
}
protected void printSchedual(int length){
int rounds = length;
for(int i = 0; i < (rounds - 1); i++){
textArea.append((i+1) + ". " + teamA.get(i).getTeamname() + " - " + teamB.get(i).getTeamname() + "\n");
}
textArea.append("-----------------------------\n");
}
}
public class PictureFrame extends JPanel implements Runnable {
Runnable run;
Image[] imageArray = new Image[4];
Image resized;
public PictureFrame() {
setVisible(true);
try {
imageArray[0] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/TrophyTheChampion.gif").getFile()));
imageArray[1] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy.gif").getFile()));
imageArray[2] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy1.gif").getFile()));
imageArray[3] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/nicolas_cage.jpg").getFile()));
} catch (IOException e) {
e.printStackTrace();
}
resized = Scalr.resize((BufferedImage)imageArray[0], 190, 190);
}
#Override
public void run() {
System.out.println("körs bara en gång.");
while(true) {
System.out.println("This will print, over and over again.");
for(int i = 0; i < imageArray.length; i++) {
resized = Scalr.resize((BufferedImage)imageArray[i], 190, 190);
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
#Override
public void paint(Graphics g) {
g.drawImage(resized, 30, 0, null);
}
}
}

JLabel alignment issues

So, I have a problem. I have a JPanel(BoxLayout, Y_AXIS). In it, I have JLabel, and JTextArea. JTextArea expands freely as I fill it with text, expanding the JPanel with it.
JLabel expands to. That is okay as long the text is vertically aligned to the top. But that command doesn't work for some reason (setVerticalTextPosition, setVerticalAlignment, setAlignmentX). I think the first one is acctually a bug within Java.
Since that didn't work, I tried glueing JLabel to the top border.
I have also set all three setXXSize to sam value to keep the size of JLabel constant.
But it just wont stick, depending on the layout it either snaps to the center or just fills the whole JPanel.
Now, I don't care how, but all I need is a couple of letters that are top-aligned in the space occupied with JLabel (I can even use another JTextComponent, if it will make any difference). Is there a way to do that?
I'd provide you with code, but it's pretty much what I have written above, and since the JPanel is a part of more complex GUI, I'd really have to give you the whole code...
(Which I will, if it will be needed.)
package core;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
#SuppressWarnings("serial")
class DefaultFont extends Font
{
public DefaultFont()
{
super("Arial", PLAIN, 20);
}
}
#SuppressWarnings("serial")
class Page extends JPanel
{
public JPanel largePage;
public int content;
public Page(JPanel panel, int index)
{
largePage = new JPanel();
largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS));
largePage.setMaximumSize(new Dimension(794, 1123));
largePage.setPreferredSize(new Dimension(794, 1123));
largePage.setAlignmentX(Component.CENTER_ALIGNMENT);
largePage.setBackground(Color.WHITE);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
setMaximumSize(new Dimension(556, 931));
setBackground(Color.LIGHT_GRAY);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931)));
largePage.add(this);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
panel.add(largePage, index);
panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
content = 0;
Main.pages.add(this);
}
}
#SuppressWarnings("serial")
class Heading extends JTextArea
{
public boolean type;
public AbstractDocument doc;
public ArrayList<JPanel/*Question*/> questions;
public ArrayList<JPanel/*List*/> list;
public Heading(boolean segment, Page page)
{
type = segment;
setBackground(Color.RED);
setFont(new Font("Arial", Font.BOLD, 20));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE);
setBorder(BorderFactory.createCompoundBorder(out, in));
setLineWrap(true);
setWrapStyleWord(true);
setText("Heading 1 Heading 1 Heading 1 Heading 1");
doc = (AbstractDocument)this.getDocument();
doc.setDocumentFilter(new DocumentFilter()
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 150)
{
;
fb.insertString(offs, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 150 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
fb.insertString(offs, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 150)
{
fb.replace(offs, length, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 150 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
});
page.add(this, 0);
page.content++;
if (type)
{
questions = new ArrayList<JPanel>();
}
else
{
list = new ArrayList<JPanel>();
}
}
}
#SuppressWarnings("serial")
class Question extends JPanel
{
public JPanel questionArea, numberArea, answerArea;
public JLabel number;
public JTextArea question;
public Question(Page page, int pageNum, int index)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
questionArea = new JPanel();
questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS));
numberArea = new JPanel();
numberArea.setLayout(new BoxLayout(numberArea, BoxLayout.Y_AXIS));
numberArea.setBackground(Color.YELLOW);
number = new JLabel(pageNum+".", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
//number.setAlignmentX(TOP_ALIGNMENT);
number.setFont(new Font("Arial", Font.PLAIN, 18));
number.setBackground(Color.BLUE);
numberArea.add(number);
//numberArea.add(new Box.Filler(new Dimension(40, 0), new Dimension(40, 30), new Dimension(40, 300)), BorderLayout.CENTER);
questionArea.add(numberArea);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 18));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("dafd afdfd fasdfsdaah fg dfgd");
questionArea.add(question);
add(questionArea);
page.add(this, index);
}
}
public class Main
{
public static Properties config;
public static Locale currentLocale;
public static ResourceBundle lang;
public static JFrame mWindow;
public static JMenuBar menu;
public static JMenu menuFile, menuEdit;
public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties;
public static JDialog newDoc;
public static JLabel newDocText1, newDocText2;
public static JRadioButton questions, list;
public static ButtonGroup newDocButtons;
public static JButton newDocOk;
public static Boolean firstSegment;
public static JPanel workspace;
public static JScrollPane scroll;
public static ArrayList<Page> pages;
public static void newDocumentForm()
{
//new document dialog
mWindow.setEnabled(false);
newDoc = new JDialog(mWindow, "newDoc");
newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
newDoc.addWindowListener(new WindowListener ()
{
public void windowActivated(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0)
{
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
newDoc.setSize(400, 200);
newDoc.setLocationRelativeTo(null);
newDoc.setResizable(false);
newDoc.setLayout(null);
newDoc.setVisible(true);
newDocText1 = new JLabel("newDocText1");
newDocText1.setBounds(5, 0, 400, 20);
newDocText2 = new JLabel("newDocText2");
newDocText2.setBounds(5, 20, 400, 20);
newDoc.add(newDocText1);
newDoc.add(newDocText2);
firstSegment = true;
questions = new JRadioButton("questions");
questions.setSelected(true);
questions.setFocusPainted(false);
questions.setBounds(10, 60, 400, 20);
questions.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = true;
}
});
list = new JRadioButton("list");
list.setFocusPainted(false);
list.setBounds(10, 80, 400, 20);
list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = false;
}
});
newDoc.add(questions);
newDoc.add(list);
newDocButtons = new ButtonGroup();
newDocButtons.add(questions);
newDocButtons.add(list);
newDocOk = new JButton("ok");
newDocOk.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
newDocOk.doClick();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
newDocOk.setFocusPainted(false);
newDocOk.setBounds(160, 120, 80, 40);
newDocOk.setMnemonic(KeyEvent.VK_ACCEPT);
newDocOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
createNewDocument();
}
});
newDoc.add(newDocOk);
newDocOk.requestFocus();
}
public static void createNewDocument()
{
//dispose of new document dialog
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
//create document display
workspace = new JPanel();
workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS));
workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
workspace.setBackground(Color.BLACK);
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setViewportView(workspace);
pages = new ArrayList<Page>();
#SuppressWarnings("unused")
Page p = new Page(workspace, 1);
Heading g = new Heading(true, p);
Question q = new Question(p, 1, 1);
mWindow.add(scroll, BorderLayout.CENTER);
mWindow.repaint();
mWindow.validate();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
//create menu bar
menu = new JMenuBar();
menuFile = new JMenu("file");
menuEdit = new JMenu("edit");
itmNew = new JMenuItem("new");
itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
itmNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDocumentForm();
}
});
itmClose = new JMenuItem("close");
itmClose.setActionCommand("Close");
itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
itmLoad = new JMenuItem("load");
itmLoad.setActionCommand("Load");
itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
itmSave = new JMenuItem("save");
itmSave.setActionCommand("Save");
itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
itmSaveAs = new JMenuItem("saveAs");
itmSaveAs.setActionCommand("SaveAs");
itmExit = new JMenuItem("exit");
itmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Add confirmation window!
System.exit(0);
}
});
itmCut = new JMenuItem("cut");
itmCut.setActionCommand("Cut");
itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
itmCopy = new JMenuItem("copy");
itmCopy.setActionCommand("Copy");
itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
itmPaste = new JMenuItem("paste");
itmPaste.setActionCommand("Paste");
itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
itmProperties = new JMenuItem("properties");
itmProperties.setActionCommand("properties");
itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
menuFile.add(itmNew);
menuFile.add(itmClose);
menuFile.addSeparator();
menuFile.add(itmLoad);
menuFile.addSeparator();
menuFile.add(itmSave);
menuFile.add(itmSaveAs);
menuFile.addSeparator();
menuFile.add(itmExit);
menuEdit.add(itmCut);
menuEdit.add(itmCopy);
menuEdit.add(itmPaste);
menuEdit.addSeparator();
menuEdit.add(itmProperties);
menu.add(menuFile);
menu.add(menuEdit);
//create actionListener for menus
mWindow.add(menu, BorderLayout.NORTH);
mWindow.repaint();
mWindow.validate();
}
}
This is the best I can do, refer to Question class for issue.
To get GUI drawn, run it, pres ctrl+n, and then enter.
As I understood you want to achieve this:
If that is true, all you have to do is this:
numberArea.setLayout(new BorderLayout());
and
numberArea.add(number,BorderLayout.NORTH);
As brano88 suggests, change layout manager...
public Question(Page page, int pageNum, int index) {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
questionArea = new JPanel();
questionArea.setLayout(new GridBagLayout());
numberArea = new JPanel();
numberArea.setLayout(new BoxLayout(numberArea, BoxLayout.Y_AXIS));
numberArea.setBackground(Color.YELLOW);
number = new JLabel(pageNum + ".", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
//number.setAlignmentX(TOP_ALIGNMENT);
number.setFont(new Font("Arial", Font.PLAIN, 18));
number.setBackground(Color.BLUE);
numberArea.add(number);
//numberArea.add(new Box.Filler(new Dimension(40, 0), new Dimension(40, 30), new Dimension(40, 300)), BorderLayout.CENTER);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.NORTH;
questionArea.add(numberArea, gbc);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 18));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("dafd afdfd fasdfsdaah fg dfgd");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTH;
questionArea.add(question, gbc);
add(questionArea);
page.add(this, index);
}

Categories